Coverage Report

Created: 2022-01-25 06:29

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Plugins/Platform/MacOSX/PlatformDarwinKernel.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- PlatformDarwinKernel.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 "PlatformDarwinKernel.h"
10
11
#if defined(__APPLE__) // This Plugin uses the Mac-specific
12
                       // source/Host/macosx/cfcpp utilities
13
14
#include "lldb/Breakpoint/BreakpointLocation.h"
15
#include "lldb/Core/Module.h"
16
#include "lldb/Core/ModuleList.h"
17
#include "lldb/Core/ModuleSpec.h"
18
#include "lldb/Core/PluginManager.h"
19
#include "lldb/Host/Host.h"
20
#include "lldb/Host/HostInfo.h"
21
#include "lldb/Interpreter/OptionValueFileSpecList.h"
22
#include "lldb/Interpreter/OptionValueProperties.h"
23
#include "lldb/Interpreter/Property.h"
24
#include "lldb/Symbol/ObjectFile.h"
25
#include "lldb/Target/Platform.h"
26
#include "lldb/Target/Process.h"
27
#include "lldb/Target/Target.h"
28
#include "lldb/Utility/ArchSpec.h"
29
#include "lldb/Utility/FileSpec.h"
30
#include "lldb/Utility/Log.h"
31
#include "lldb/Utility/Status.h"
32
#include "lldb/Utility/StreamString.h"
33
34
#include "llvm/Support/FileSystem.h"
35
36
#include <CoreFoundation/CoreFoundation.h>
37
38
#include <memory>
39
40
#include "Host/macosx/cfcpp/CFCBundle.h"
41
42
using namespace lldb;
43
using namespace lldb_private;
44
45
// Static Variables
46
static uint32_t g_initialize_count = 0;
47
48
// Static Functions
49
3.44k
void PlatformDarwinKernel::Initialize() {
50
3.44k
  PlatformDarwin::Initialize();
51
52
3.44k
  if (g_initialize_count++ == 0) {
53
3.44k
    PluginManager::RegisterPlugin(PlatformDarwinKernel::GetPluginNameStatic(),
54
3.44k
                                  PlatformDarwinKernel::GetDescriptionStatic(),
55
3.44k
                                  PlatformDarwinKernel::CreateInstance,
56
3.44k
                                  PlatformDarwinKernel::DebuggerInitialize);
57
3.44k
  }
58
3.44k
}
59
60
3.43k
void PlatformDarwinKernel::Terminate() {
61
3.43k
  if (g_initialize_count > 0) {
62
3.43k
    if (--g_initialize_count == 0) {
63
3.43k
      PluginManager::UnregisterPlugin(PlatformDarwinKernel::CreateInstance);
64
3.43k
    }
65
3.43k
  }
66
67
3.43k
  PlatformDarwin::Terminate();
68
3.43k
}
69
70
PlatformSP PlatformDarwinKernel::CreateInstance(bool force,
71
78
                                                const ArchSpec *arch) {
72
78
  Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
73
78
  if (log) {
74
0
    const char *arch_name;
75
0
    if (arch && arch->GetArchitectureName())
76
0
      arch_name = arch->GetArchitectureName();
77
0
    else
78
0
      arch_name = "<null>";
79
80
0
    const char *triple_cstr =
81
0
        arch ? arch->GetTriple().getTriple().c_str() : "<null>";
82
83
0
    LLDB_LOGF(log, "PlatformDarwinKernel::%s(force=%s, arch={%s,%s})",
84
0
              __FUNCTION__, force ? "true" : "false", arch_name, triple_cstr);
85
0
  }
86
87
  // This is a special plugin that we don't want to activate just based on an
88
  // ArchSpec for normal userland debugging.  It is only useful in kernel debug
89
  // sessions and the DynamicLoaderDarwinPlugin (or a user doing 'platform
90
  // select') will force the creation of this Platform plugin.
91
78
  if (!force) {
92
78
    LLDB_LOGF(log,
93
78
              "PlatformDarwinKernel::%s() aborting creation of platform "
94
78
              "because force == false",
95
78
              __FUNCTION__);
96
78
    return PlatformSP();
97
78
  }
98
99
0
  bool create = force;
100
0
  LazyBool is_ios_debug_session = eLazyBoolCalculate;
101
102
0
  if (!create && arch && arch->IsValid()) {
103
0
    const llvm::Triple &triple = arch->GetTriple();
104
0
    switch (triple.getVendor()) {
105
0
    case llvm::Triple::Apple:
106
0
      create = true;
107
0
      break;
108
109
    // Only accept "unknown" for vendor if the host is Apple and it "unknown"
110
    // wasn't specified (it was just returned because it was NOT specified)
111
0
    case llvm::Triple::UnknownVendor:
112
0
      create = !arch->TripleVendorWasSpecified();
113
0
      break;
114
0
    default:
115
0
      break;
116
0
    }
117
118
0
    if (create) {
119
0
      switch (triple.getOS()) {
120
0
      case llvm::Triple::Darwin:
121
0
      case llvm::Triple::MacOSX:
122
0
      case llvm::Triple::IOS:
123
0
      case llvm::Triple::WatchOS:
124
0
      case llvm::Triple::TvOS:
125
      // NEED_BRIDGEOS_TRIPLE case llvm::Triple::BridgeOS:
126
0
        break;
127
      // Only accept "vendor" for vendor if the host is Apple and it "unknown"
128
      // wasn't specified (it was just returned because it was NOT specified)
129
0
      case llvm::Triple::UnknownOS:
130
0
        create = !arch->TripleOSWasSpecified();
131
0
        break;
132
0
      default:
133
0
        create = false;
134
0
        break;
135
0
      }
136
0
    }
137
0
  }
138
0
  if (arch && arch->IsValid()) {
139
0
    switch (arch->GetMachine()) {
140
0
    case llvm::Triple::x86:
141
0
    case llvm::Triple::x86_64:
142
0
    case llvm::Triple::ppc:
143
0
    case llvm::Triple::ppc64:
144
0
      is_ios_debug_session = eLazyBoolNo;
145
0
      break;
146
0
    case llvm::Triple::arm:
147
0
    case llvm::Triple::aarch64:
148
0
    case llvm::Triple::thumb:
149
0
      is_ios_debug_session = eLazyBoolYes;
150
0
      break;
151
0
    default:
152
0
      is_ios_debug_session = eLazyBoolCalculate;
153
0
      break;
154
0
    }
155
0
  }
156
0
  if (create) {
157
0
    LLDB_LOGF(log, "PlatformDarwinKernel::%s() creating platform",
158
0
              __FUNCTION__);
159
160
0
    return PlatformSP(new PlatformDarwinKernel(is_ios_debug_session));
161
0
  }
162
163
0
  LLDB_LOGF(log, "PlatformDarwinKernel::%s() aborting creation of platform",
164
0
            __FUNCTION__);
165
166
0
  return PlatformSP();
167
0
}
168
169
3.44k
llvm::StringRef PlatformDarwinKernel::GetDescriptionStatic() {
170
3.44k
  return "Darwin Kernel platform plug-in.";
171
3.44k
}
172
173
/// Code to handle the PlatformDarwinKernel settings
174
175
#define LLDB_PROPERTIES_platformdarwinkernel
176
#include "PlatformMacOSXProperties.inc"
177
178
enum {
179
#define LLDB_PROPERTIES_platformdarwinkernel
180
#include "PlatformMacOSXPropertiesEnum.inc"
181
};
182
183
class PlatformDarwinKernelProperties : public Properties {
184
public:
185
9.34k
  static ConstString &GetSettingName() {
186
9.34k
    static ConstString g_setting_name("darwin-kernel");
187
9.34k
    return g_setting_name;
188
9.34k
  }
189
190
3.39k
  PlatformDarwinKernelProperties() : Properties() {
191
3.39k
    m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
192
3.39k
    m_collection_sp->Initialize(g_platformdarwinkernel_properties);
193
3.39k
  }
194
195
3.39k
  virtual ~PlatformDarwinKernelProperties() = default;
196
197
0
  FileSpecList GetKextDirectories() const {
198
0
    const uint32_t idx = ePropertyKextDirectories;
199
0
    const OptionValueFileSpecList *option_value =
200
0
        m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(
201
0
            NULL, false, idx);
202
0
    assert(option_value);
203
0
    return option_value->GetCurrentValue();
204
0
  }
205
};
206
207
3.39k
static PlatformDarwinKernelProperties &GetGlobalProperties() {
208
3.39k
  static PlatformDarwinKernelProperties g_settings;
209
3.39k
  return g_settings;
210
3.39k
}
211
212
void PlatformDarwinKernel::DebuggerInitialize(
213
5.94k
    lldb_private::Debugger &debugger) {
214
5.94k
  if (!PluginManager::GetSettingForPlatformPlugin(
215
5.94k
          debugger, PlatformDarwinKernelProperties::GetSettingName())) {
216
3.39k
    const bool is_global_setting = true;
217
3.39k
    PluginManager::CreateSettingForPlatformPlugin(
218
3.39k
        debugger, GetGlobalProperties().GetValueProperties(),
219
3.39k
        ConstString("Properties for the PlatformDarwinKernel plug-in."),
220
3.39k
        is_global_setting);
221
3.39k
  }
222
5.94k
}
223
224
/// Default Constructor
225
PlatformDarwinKernel::PlatformDarwinKernel(
226
    lldb_private::LazyBool is_ios_debug_session)
227
    : PlatformDarwin(false), // This is a remote platform
228
      m_name_to_kext_path_map_with_dsyms(),
229
      m_name_to_kext_path_map_without_dsyms(), m_search_directories(),
230
      m_search_directories_no_recursing(), m_kernel_binaries_with_dsyms(),
231
      m_kernel_binaries_without_dsyms(), m_kernel_dsyms_no_binaries(),
232
      m_kernel_dsyms_yaas(), m_ios_debug_session(is_ios_debug_session)
233
234
0
{
235
0
  CollectKextAndKernelDirectories();
236
0
  SearchForKextsAndKernelsRecursively();
237
0
}
238
239
/// Destructor.
240
///
241
/// The destructor is virtual since this class is designed to be
242
/// inherited from by the plug-in instance.
243
0
PlatformDarwinKernel::~PlatformDarwinKernel() = default;
244
245
0
void PlatformDarwinKernel::GetStatus(Stream &strm) {
246
0
  Platform::GetStatus(strm);
247
0
  strm.Printf(" Debug session type: ");
248
0
  if (m_ios_debug_session == eLazyBoolYes)
249
0
    strm.Printf("iOS kernel debugging\n");
250
0
  else if (m_ios_debug_session == eLazyBoolNo)
251
0
    strm.Printf("Mac OS X kernel debugging\n");
252
0
  else
253
0
    strm.Printf("unknown kernel debugging\n");
254
255
0
  strm.Printf("Directories searched recursively:\n");
256
0
  const uint32_t num_kext_dirs = m_search_directories.size();
257
0
  for (uint32_t i = 0; i < num_kext_dirs; ++i) {
258
0
    strm.Printf("[%d] %s\n", i, m_search_directories[i].GetPath().c_str());
259
0
  }
260
261
0
  strm.Printf("Directories not searched recursively:\n");
262
0
  const uint32_t num_kext_dirs_no_recursion =
263
0
      m_search_directories_no_recursing.size();
264
0
  for (uint32_t i = 0; i < num_kext_dirs_no_recursion; i++) {
265
0
    strm.Printf("[%d] %s\n", i,
266
0
                m_search_directories_no_recursing[i].GetPath().c_str());
267
0
  }
268
269
0
  strm.Printf(" Number of kexts with dSYMs indexed: %d\n",
270
0
              (int)m_name_to_kext_path_map_with_dsyms.size());
271
0
  strm.Printf(" Number of kexts without dSYMs indexed: %d\n",
272
0
              (int)m_name_to_kext_path_map_without_dsyms.size());
273
0
  strm.Printf(" Number of Kernel binaries with dSYMs indexed: %d\n",
274
0
              (int)m_kernel_binaries_with_dsyms.size());
275
0
  strm.Printf(" Number of Kernel binaries without dSYMs indexed: %d\n",
276
0
              (int)m_kernel_binaries_without_dsyms.size());
277
0
  strm.Printf(" Number of Kernel dSYMs with no binaries indexed: %d\n",
278
0
              (int)m_kernel_dsyms_no_binaries.size());
279
0
  strm.Printf(" Number of Kernel dSYM.yaa's indexed: %d\n",
280
0
              (int)m_kernel_dsyms_yaas.size());
281
282
0
  Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
283
0
  if (log) {
284
0
    LLDB_LOGF(log, "\nkexts with dSYMs");
285
0
    for (auto pos : m_name_to_kext_path_map_with_dsyms) {
286
0
      LLDB_LOGF(log, "%s", pos.second.GetPath().c_str());
287
0
    }
288
0
    LLDB_LOGF(log, "\nkexts without dSYMs");
289
290
0
    for (auto pos : m_name_to_kext_path_map_without_dsyms) {
291
0
      LLDB_LOGF(log, "%s", pos.second.GetPath().c_str());
292
0
    }
293
0
    LLDB_LOGF(log, "\nkernel binaries with dSYMS");
294
0
    for (auto fs : m_kernel_binaries_with_dsyms) {
295
0
      LLDB_LOGF(log, "%s", fs.GetPath().c_str());
296
0
    }
297
0
    LLDB_LOGF(log, "\nkernel binaries without dSYMS");
298
0
    for (auto fs : m_kernel_binaries_without_dsyms) {
299
0
      LLDB_LOGF(log, "%s", fs.GetPath().c_str());
300
0
    }
301
0
    LLDB_LOGF(log, "\nkernel dSYMS with no binaries");
302
0
    for (auto fs : m_kernel_dsyms_no_binaries) {
303
0
      LLDB_LOGF(log, "%s", fs.GetPath().c_str());
304
0
    }
305
0
    LLDB_LOGF(log, "\nkernels .dSYM.yaa's");
306
0
    for (auto fs : m_kernel_dsyms_yaas) {
307
0
      LLDB_LOGF(log, "%s", fs.GetPath().c_str());
308
0
    }
309
0
    LLDB_LOGF(log, "\n");
310
0
  }
311
0
}
312
313
// Populate the m_search_directories vector with directories we should search
314
// for kernel & kext binaries.
315
316
0
void PlatformDarwinKernel::CollectKextAndKernelDirectories() {
317
  // Differentiate between "ios debug session" and "mac debug session" so we
318
  // don't index kext bundles that won't be used in this debug session.  If
319
  // this is an ios kext debug session, looking in /System/Library/Extensions
320
  // is a waste of stat()s, for example.
321
322
  // DeveloperDirectory is something like
323
  // "/Applications/Xcode.app/Contents/Developer"
324
0
  std::string developer_dir = HostInfo::GetXcodeDeveloperDirectory().GetPath();
325
0
  if (developer_dir.empty())
326
0
    developer_dir = "/Applications/Xcode.app/Contents/Developer";
327
328
0
  if (m_ios_debug_session != eLazyBoolNo) {
329
0
    AddSDKSubdirsToSearchPaths(developer_dir +
330
0
                               "/Platforms/iPhoneOS.platform/Developer/SDKs");
331
0
    AddSDKSubdirsToSearchPaths(developer_dir +
332
0
                               "/Platforms/AppleTVOS.platform/Developer/SDKs");
333
0
    AddSDKSubdirsToSearchPaths(developer_dir +
334
0
                               "/Platforms/WatchOS.platform/Developer/SDKs");
335
0
    AddSDKSubdirsToSearchPaths(developer_dir +
336
0
                               "/Platforms/BridgeOS.platform/Developer/SDKs");
337
0
  }
338
0
  if (m_ios_debug_session != eLazyBoolYes) {
339
0
    AddSDKSubdirsToSearchPaths(developer_dir +
340
0
                               "/Platforms/MacOSX.platform/Developer/SDKs");
341
0
  }
342
343
0
  AddSDKSubdirsToSearchPaths("/Volumes/KernelDebugKit");
344
0
  AddSDKSubdirsToSearchPaths("/AppleInternal/Developer/KDKs");
345
  // The KDKs distributed from Apple installed on external developer systems
346
  // may be in directories like /Library/Developer/KDKs/KDK_10.10_14A298i.kdk
347
0
  AddSDKSubdirsToSearchPaths("/Library/Developer/KDKs");
348
349
0
  if (m_ios_debug_session != eLazyBoolNo) {
350
0
  }
351
0
  if (m_ios_debug_session != eLazyBoolYes) {
352
0
    AddRootSubdirsToSearchPaths(this, "/");
353
0
  }
354
355
0
  GetUserSpecifiedDirectoriesToSearch();
356
357
  // Add simple directory /Applications/Xcode.app/Contents/Developer/../Symbols
358
0
  FileSpec possible_dir(developer_dir + "/../Symbols");
359
0
  FileSystem::Instance().Resolve(possible_dir);
360
0
  if (FileSystem::Instance().IsDirectory(possible_dir))
361
0
    m_search_directories.push_back(possible_dir);
362
363
  // Add simple directory of the current working directory
364
0
  FileSpec cwd(".");
365
0
  FileSystem::Instance().Resolve(cwd);
366
0
  m_search_directories_no_recursing.push_back(cwd);
367
0
}
368
369
0
void PlatformDarwinKernel::GetUserSpecifiedDirectoriesToSearch() {
370
0
  FileSpecList user_dirs(GetGlobalProperties().GetKextDirectories());
371
0
  std::vector<FileSpec> possible_sdk_dirs;
372
373
0
  const uint32_t user_dirs_count = user_dirs.GetSize();
374
0
  for (uint32_t i = 0; i < user_dirs_count; i++) {
375
0
    FileSpec dir = user_dirs.GetFileSpecAtIndex(i);
376
0
    FileSystem::Instance().Resolve(dir);
377
0
    if (FileSystem::Instance().IsDirectory(dir)) {
378
0
      m_search_directories.push_back(dir);
379
0
    }
380
0
  }
381
0
}
382
383
void PlatformDarwinKernel::AddRootSubdirsToSearchPaths(
384
0
    PlatformDarwinKernel *thisp, const std::string &dir) {
385
0
  const char *subdirs[] = {
386
0
      "/System/Library/Extensions", "/Library/Extensions",
387
0
      "/System/Library/Kernels",
388
0
      "/System/Library/Extensions/KDK", // this one probably only exist in
389
                                        // /AppleInternal/Developer/KDKs/*.kdk/...
390
0
      nullptr};
391
0
  for (int i = 0; subdirs[i] != nullptr; i++) {
392
0
    FileSpec testdir(dir + subdirs[i]);
393
0
    FileSystem::Instance().Resolve(testdir);
394
0
    if (FileSystem::Instance().IsDirectory(testdir))
395
0
      thisp->m_search_directories.push_back(testdir);
396
0
  }
397
398
  // Look for kernel binaries in the top level directory, without any recursion
399
0
  thisp->m_search_directories_no_recursing.push_back(FileSpec(dir + "/"));
400
0
}
401
402
// Given a directory path dir, look for any subdirs named *.kdk and *.sdk
403
0
void PlatformDarwinKernel::AddSDKSubdirsToSearchPaths(const std::string &dir) {
404
  // Look for *.kdk and *.sdk in dir
405
0
  const bool find_directories = true;
406
0
  const bool find_files = false;
407
0
  const bool find_other = false;
408
0
  FileSystem::Instance().EnumerateDirectory(
409
0
      dir.c_str(), find_directories, find_files, find_other,
410
0
      FindKDKandSDKDirectoriesInDirectory, this);
411
0
}
412
413
// Helper function to find *.sdk and *.kdk directories in a given directory.
414
FileSystem::EnumerateDirectoryResult
415
PlatformDarwinKernel::FindKDKandSDKDirectoriesInDirectory(
416
0
    void *baton, llvm::sys::fs::file_type ft, llvm::StringRef path) {
417
0
  static ConstString g_sdk_suffix = ConstString(".sdk");
418
0
  static ConstString g_kdk_suffix = ConstString(".kdk");
419
420
0
  PlatformDarwinKernel *thisp = (PlatformDarwinKernel *)baton;
421
0
  FileSpec file_spec(path);
422
0
  if (ft == llvm::sys::fs::file_type::directory_file &&
423
0
      (file_spec.GetFileNameExtension() == g_sdk_suffix ||
424
0
       file_spec.GetFileNameExtension() == g_kdk_suffix)) {
425
0
    AddRootSubdirsToSearchPaths(thisp, file_spec.GetPath());
426
0
  }
427
0
  return FileSystem::eEnumerateDirectoryResultNext;
428
0
}
429
430
// Recursively search trough m_search_directories looking for kext and kernel
431
// binaries, adding files found to the appropriate lists.
432
0
void PlatformDarwinKernel::SearchForKextsAndKernelsRecursively() {
433
0
  const uint32_t num_dirs = m_search_directories.size();
434
0
  for (uint32_t i = 0; i < num_dirs; i++) {
435
0
    const FileSpec &dir = m_search_directories[i];
436
0
    const bool find_directories = true;
437
0
    const bool find_files = true;
438
0
    const bool find_other = true; // I think eFileTypeSymbolicLink are "other"s.
439
0
    FileSystem::Instance().EnumerateDirectory(
440
0
        dir.GetPath().c_str(), find_directories, find_files, find_other,
441
0
        GetKernelsAndKextsInDirectoryWithRecursion, this);
442
0
  }
443
0
  const uint32_t num_dirs_no_recurse = m_search_directories_no_recursing.size();
444
0
  for (uint32_t i = 0; i < num_dirs_no_recurse; i++) {
445
0
    const FileSpec &dir = m_search_directories_no_recursing[i];
446
0
    const bool find_directories = true;
447
0
    const bool find_files = true;
448
0
    const bool find_other = true; // I think eFileTypeSymbolicLink are "other"s.
449
0
    FileSystem::Instance().EnumerateDirectory(
450
0
        dir.GetPath().c_str(), find_directories, find_files, find_other,
451
0
        GetKernelsAndKextsInDirectoryNoRecursion, this);
452
0
  }
453
0
}
454
455
// We're only doing a filename match here.  We won't try opening the file to
456
// see if it's really a kernel or not until we need to find a kernel of a given
457
// UUID.  There's no cheap way to find the UUID of a file (or if it's a Mach-O
458
// binary at all) without creating a whole Module for the file and throwing it
459
// away if it's not wanted.
460
//
461
// Recurse into any subdirectories found.
462
463
FileSystem::EnumerateDirectoryResult
464
PlatformDarwinKernel::GetKernelsAndKextsInDirectoryWithRecursion(
465
0
    void *baton, llvm::sys::fs::file_type ft, llvm::StringRef path) {
466
0
  return GetKernelsAndKextsInDirectoryHelper(baton, ft, path, true);
467
0
}
468
469
FileSystem::EnumerateDirectoryResult
470
PlatformDarwinKernel::GetKernelsAndKextsInDirectoryNoRecursion(
471
0
    void *baton, llvm::sys::fs::file_type ft, llvm::StringRef path) {
472
0
  return GetKernelsAndKextsInDirectoryHelper(baton, ft, path, false);
473
0
}
474
475
FileSystem::EnumerateDirectoryResult
476
PlatformDarwinKernel::GetKernelsAndKextsInDirectoryHelper(
477
    void *baton, llvm::sys::fs::file_type ft, llvm::StringRef path,
478
0
    bool recurse) {
479
0
  static ConstString g_kext_suffix = ConstString(".kext");
480
0
  static ConstString g_dsym_suffix = ConstString(".dSYM");
481
0
  static ConstString g_bundle_suffix = ConstString("Bundle");
482
483
0
  FileSpec file_spec(path);
484
0
  ConstString file_spec_extension = file_spec.GetFileNameExtension();
485
486
0
  Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
487
0
  Log *log_verbose(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM | LLDB_LOG_OPTION_VERBOSE));
488
489
0
  LLDB_LOGF(log_verbose, "PlatformDarwinKernel examining '%s'",
490
0
            file_spec.GetPath().c_str());
491
492
0
  PlatformDarwinKernel *thisp = (PlatformDarwinKernel *)baton;
493
494
0
  llvm::StringRef filename = file_spec.GetFilename().GetStringRef();
495
0
  bool is_kernel_filename =
496
0
      filename.startswith("kernel") || filename.startswith("mach");
497
0
  bool is_dsym_yaa = filename.endswith(".dSYM.yaa");
498
499
0
  if (ft == llvm::sys::fs::file_type::regular_file ||
500
0
      ft == llvm::sys::fs::file_type::symlink_file) {
501
0
    if (is_kernel_filename) {
502
0
      if (file_spec_extension != g_dsym_suffix && !is_dsym_yaa) {
503
0
        if (KernelHasdSYMSibling(file_spec)) {
504
0
          LLDB_LOGF(log,
505
0
                    "PlatformDarwinKernel registering kernel binary '%s' with "
506
0
                    "dSYM sibling",
507
0
                    file_spec.GetPath().c_str());
508
0
          thisp->m_kernel_binaries_with_dsyms.push_back(file_spec);
509
0
        } else {
510
0
          LLDB_LOGF(
511
0
              log,
512
0
              "PlatformDarwinKernel registering kernel binary '%s', no dSYM",
513
0
              file_spec.GetPath().c_str());
514
0
          thisp->m_kernel_binaries_without_dsyms.push_back(file_spec);
515
0
        }
516
0
      }
517
0
      if (is_dsym_yaa) {
518
0
        LLDB_LOGF(log, "PlatformDarwinKernel registering kernel .dSYM.yaa '%s'",
519
0
                  file_spec.GetPath().c_str());
520
0
        thisp->m_kernel_dsyms_yaas.push_back(file_spec);
521
0
      }
522
0
      return FileSystem::eEnumerateDirectoryResultNext;
523
0
    }
524
0
  } else {
525
0
    if (ft == llvm::sys::fs::file_type::directory_file) {
526
0
      if (file_spec_extension == g_kext_suffix) {
527
0
        AddKextToMap(thisp, file_spec);
528
        // Look to see if there is a PlugIns subdir with more kexts
529
0
        FileSpec contents_plugins(file_spec.GetPath() + "/Contents/PlugIns");
530
0
        std::string search_here_too;
531
0
        if (FileSystem::Instance().IsDirectory(contents_plugins)) {
532
0
          search_here_too = contents_plugins.GetPath();
533
0
        } else {
534
0
          FileSpec plugins(file_spec.GetPath() + "/PlugIns");
535
0
          if (FileSystem::Instance().IsDirectory(plugins)) {
536
0
            search_here_too = plugins.GetPath();
537
0
          }
538
0
        }
539
540
0
        if (!search_here_too.empty()) {
541
0
          const bool find_directories = true;
542
0
          const bool find_files = false;
543
0
          const bool find_other = false;
544
0
          FileSystem::Instance().EnumerateDirectory(
545
0
              search_here_too.c_str(), find_directories, find_files, find_other,
546
0
              recurse ? GetKernelsAndKextsInDirectoryWithRecursion
547
0
                      : GetKernelsAndKextsInDirectoryNoRecursion,
548
0
              baton);
549
0
        }
550
0
        return FileSystem::eEnumerateDirectoryResultNext;
551
0
      }
552
      // Do we have a kernel dSYM with no kernel binary?
553
0
      if (is_kernel_filename && file_spec_extension == g_dsym_suffix) {
554
0
        if (KerneldSYMHasNoSiblingBinary(file_spec)) {
555
0
          LLDB_LOGF(log,
556
0
                    "PlatformDarwinKernel registering kernel dSYM '%s' with "
557
0
                    "no binary sibling",
558
0
                    file_spec.GetPath().c_str());
559
0
          thisp->m_kernel_dsyms_no_binaries.push_back(file_spec);
560
0
          return FileSystem::eEnumerateDirectoryResultNext;
561
0
        }
562
0
      }
563
0
    }
564
0
  }
565
566
  // Don't recurse into dSYM/kext/bundle directories
567
0
  if (recurse && file_spec_extension != g_dsym_suffix &&
568
0
      file_spec_extension != g_kext_suffix &&
569
0
      file_spec_extension != g_bundle_suffix) {
570
0
    LLDB_LOGF(log_verbose,
571
0
              "PlatformDarwinKernel descending into directory '%s'",
572
0
              file_spec.GetPath().c_str());
573
0
    return FileSystem::eEnumerateDirectoryResultEnter;
574
0
  } else {
575
0
    return FileSystem::eEnumerateDirectoryResultNext;
576
0
  }
577
0
}
578
579
void PlatformDarwinKernel::AddKextToMap(PlatformDarwinKernel *thisp,
580
0
                                        const FileSpec &file_spec) {
581
0
  Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
582
0
  CFCBundle bundle(file_spec.GetPath().c_str());
583
0
  CFStringRef bundle_id(bundle.GetIdentifier());
584
0
  if (bundle_id && CFGetTypeID(bundle_id) == CFStringGetTypeID()) {
585
0
    char bundle_id_buf[PATH_MAX];
586
0
    if (CFStringGetCString(bundle_id, bundle_id_buf, sizeof(bundle_id_buf),
587
0
                           kCFStringEncodingUTF8)) {
588
0
      ConstString bundle_conststr(bundle_id_buf);
589
0
      if (KextHasdSYMSibling(file_spec))
590
0
      {
591
0
        LLDB_LOGF(log,
592
0
                  "PlatformDarwinKernel registering kext binary '%s' with dSYM "
593
0
                  "sibling",
594
0
                  file_spec.GetPath().c_str());
595
0
        thisp->m_name_to_kext_path_map_with_dsyms.insert(
596
0
            std::pair<ConstString, FileSpec>(bundle_conststr, file_spec));
597
0
      }
598
0
      else
599
0
      {
600
0
        LLDB_LOGF(log,
601
0
                  "PlatformDarwinKernel registering kext binary '%s', no dSYM",
602
0
                  file_spec.GetPath().c_str());
603
0
        thisp->m_name_to_kext_path_map_without_dsyms.insert(
604
0
            std::pair<ConstString, FileSpec>(bundle_conststr, file_spec));
605
0
      }
606
0
    }
607
0
  }
608
0
}
609
610
// Given a FileSpec of /dir/dir/foo.kext
611
// Return true if any of these exist:
612
//    /dir/dir/foo.kext.dSYM
613
//    /dir/dir/foo.kext/Contents/MacOS/foo.dSYM
614
//    /dir/dir/foo.kext/foo.dSYM
615
bool PlatformDarwinKernel::KextHasdSYMSibling(
616
0
    const FileSpec &kext_bundle_filepath) {
617
0
  FileSpec dsym_fspec = kext_bundle_filepath;
618
0
  std::string filename = dsym_fspec.GetFilename().AsCString();
619
0
  filename += ".dSYM";
620
0
  dsym_fspec.GetFilename() = ConstString(filename);
621
0
  if (FileSystem::Instance().IsDirectory(dsym_fspec)) {
622
0
    return true;
623
0
  }
624
  // Should probably get the CFBundleExecutable here or call
625
  // CFBundleCopyExecutableURL
626
627
  // Look for a deep bundle foramt
628
0
  ConstString executable_name =
629
0
      kext_bundle_filepath.GetFileNameStrippingExtension();
630
0
  std::string deep_bundle_str =
631
0
      kext_bundle_filepath.GetPath() + "/Contents/MacOS/";
632
0
  deep_bundle_str += executable_name.AsCString();
633
0
  deep_bundle_str += ".dSYM";
634
0
  dsym_fspec.SetFile(deep_bundle_str, FileSpec::Style::native);
635
0
  FileSystem::Instance().Resolve(dsym_fspec);
636
0
  if (FileSystem::Instance().IsDirectory(dsym_fspec)) {
637
0
    return true;
638
0
  }
639
640
  // look for a shallow bundle format
641
  //
642
0
  std::string shallow_bundle_str = kext_bundle_filepath.GetPath() + "/";
643
0
  shallow_bundle_str += executable_name.AsCString();
644
0
  shallow_bundle_str += ".dSYM";
645
0
  dsym_fspec.SetFile(shallow_bundle_str, FileSpec::Style::native);
646
0
  FileSystem::Instance().Resolve(dsym_fspec);
647
0
  return FileSystem::Instance().IsDirectory(dsym_fspec);
648
0
}
649
650
// Given a FileSpec of /dir/dir/mach.development.t7004 Return true if a dSYM
651
// exists next to it:
652
//    /dir/dir/mach.development.t7004.dSYM
653
0
bool PlatformDarwinKernel::KernelHasdSYMSibling(const FileSpec &kernel_binary) {
654
0
  FileSpec kernel_dsym = kernel_binary;
655
0
  std::string filename = kernel_binary.GetFilename().AsCString();
656
0
  filename += ".dSYM";
657
0
  kernel_dsym.GetFilename() = ConstString(filename);
658
0
  return FileSystem::Instance().IsDirectory(kernel_dsym);
659
0
}
660
661
// Given a FileSpec of /dir/dir/mach.development.t7004.dSYM
662
// Return true if only the dSYM exists, no binary next to it.
663
//    /dir/dir/mach.development.t7004.dSYM
664
//    but no
665
//    /dir/dir/mach.development.t7004
666
bool PlatformDarwinKernel::KerneldSYMHasNoSiblingBinary(
667
0
    const FileSpec &kernel_dsym) {
668
0
  static ConstString g_dsym_suffix = ConstString(".dSYM");
669
0
  std::string possible_path = kernel_dsym.GetPath();
670
0
  if (kernel_dsym.GetFileNameExtension() != g_dsym_suffix)
671
0
    return false;
672
673
0
  FileSpec binary_filespec = kernel_dsym;
674
  // Chop off the '.dSYM' extension on the filename
675
0
  binary_filespec.GetFilename() =
676
0
      binary_filespec.GetFileNameStrippingExtension();
677
678
  // Is there a binary next to this this?  Then return false.
679
0
  if (FileSystem::Instance().Exists(binary_filespec))
680
0
    return false;
681
682
  // If we have at least one binary in the DWARF subdir, then
683
  // this is a properly formed dSYM and it has no binary next
684
  // to it.
685
0
  if (GetDWARFBinaryInDSYMBundle(kernel_dsym).size() > 0)
686
0
    return true;
687
688
0
  return false;
689
0
}
690
691
// TODO: This method returns a vector of FileSpec's because a
692
// dSYM bundle may contain multiple DWARF binaries, but it
693
// only implements returning the base name binary for now;
694
// it should iterate over every binary in the DWARF subdir
695
// and return them all.
696
std::vector<FileSpec>
697
0
PlatformDarwinKernel::GetDWARFBinaryInDSYMBundle(FileSpec dsym_bundle) {
698
0
  std::vector<FileSpec> results;
699
0
  static ConstString g_dsym_suffix = ConstString(".dSYM");
700
0
  if (dsym_bundle.GetFileNameExtension() != g_dsym_suffix) {
701
0
    return results;
702
0
  }
703
  // Drop the '.dSYM' from the filename
704
0
  std::string filename =
705
0
      dsym_bundle.GetFileNameStrippingExtension().GetCString();
706
0
  std::string dirname = dsym_bundle.GetDirectory().GetCString();
707
708
0
  std::string binary_filepath = dsym_bundle.GetPath();
709
0
  binary_filepath += "/Contents/Resources/DWARF/";
710
0
  binary_filepath += filename;
711
712
0
  FileSpec binary_fspec(binary_filepath);
713
0
  if (FileSystem::Instance().Exists(binary_fspec))
714
0
    results.push_back(binary_fspec);
715
0
  return results;
716
0
}
717
718
Status PlatformDarwinKernel::GetSharedModule(
719
    const ModuleSpec &module_spec, Process *process, ModuleSP &module_sp,
720
    const FileSpecList *module_search_paths_ptr,
721
0
    llvm::SmallVectorImpl<ModuleSP> *old_modules, bool *did_create_ptr) {
722
0
  Status error;
723
0
  module_sp.reset();
724
0
  const FileSpec &platform_file = module_spec.GetFileSpec();
725
726
  // Treat the file's path as a kext bundle ID (e.g.
727
  // "com.apple.driver.AppleIRController") and search our kext index.
728
0
  std::string kext_bundle_id = platform_file.GetPath();
729
730
0
  if (!kext_bundle_id.empty() && module_spec.GetUUID().IsValid()) {
731
0
    if (kext_bundle_id == "mach_kernel") {
732
0
      return GetSharedModuleKernel(module_spec, process, module_sp,
733
0
                                   module_search_paths_ptr, old_modules,
734
0
                                   did_create_ptr);
735
0
    } else {
736
0
      return GetSharedModuleKext(module_spec, process, module_sp,
737
0
                                 module_search_paths_ptr, old_modules,
738
0
                                 did_create_ptr);
739
0
    }
740
0
  } else {
741
    // Give the generic methods, including possibly calling into  DebugSymbols
742
    // framework on macOS systems, a chance.
743
0
    return PlatformDarwin::GetSharedModule(module_spec, process, module_sp,
744
0
                                           module_search_paths_ptr, old_modules,
745
0
                                           did_create_ptr);
746
0
  }
747
0
}
748
749
Status PlatformDarwinKernel::GetSharedModuleKext(
750
    const ModuleSpec &module_spec, Process *process, ModuleSP &module_sp,
751
    const FileSpecList *module_search_paths_ptr,
752
0
    llvm::SmallVectorImpl<ModuleSP> *old_modules, bool *did_create_ptr) {
753
0
  Status error;
754
0
  module_sp.reset();
755
0
  const FileSpec &platform_file = module_spec.GetFileSpec();
756
757
  // Treat the file's path as a kext bundle ID (e.g.
758
  // "com.apple.driver.AppleIRController") and search our kext index.
759
0
  ConstString kext_bundle(platform_file.GetPath().c_str());
760
  // First look through the kext bundles that had a dsym next to them
761
0
  if (m_name_to_kext_path_map_with_dsyms.count(kext_bundle) > 0) {
762
0
    for (BundleIDToKextIterator it = m_name_to_kext_path_map_with_dsyms.begin();
763
0
         it != m_name_to_kext_path_map_with_dsyms.end(); ++it) {
764
0
      if (it->first == kext_bundle) {
765
0
        error = ExamineKextForMatchingUUID(it->second, module_spec.GetUUID(),
766
0
                                           module_spec.GetArchitecture(),
767
0
                                           module_sp);
768
0
        if (module_sp.get()) {
769
0
          return error;
770
0
        }
771
0
      }
772
0
    }
773
0
  }
774
775
  // Give the generic methods, including possibly calling into  DebugSymbols
776
  // framework on macOS systems, a chance.
777
0
  error = PlatformDarwin::GetSharedModule(module_spec, process, module_sp,
778
0
                                          module_search_paths_ptr, old_modules,
779
0
                                          did_create_ptr);
780
0
  if (error.Success() && module_sp.get()) {
781
0
    return error;
782
0
  }
783
784
0
  return error;
785
0
}
786
787
Status PlatformDarwinKernel::GetSharedModuleKernel(
788
    const ModuleSpec &module_spec, Process *process, ModuleSP &module_sp,
789
    const FileSpecList *module_search_paths_ptr,
790
0
    llvm::SmallVectorImpl<ModuleSP> *old_modules, bool *did_create_ptr) {
791
0
  Status error;
792
0
  module_sp.reset();
793
794
  // First try all kernel binaries that have a dSYM next to them
795
0
  for (auto possible_kernel : m_kernel_binaries_with_dsyms) {
796
0
    if (FileSystem::Instance().Exists(possible_kernel)) {
797
0
      ModuleSpec kern_spec(possible_kernel);
798
0
      kern_spec.GetUUID() = module_spec.GetUUID();
799
0
      module_sp.reset(new Module(kern_spec));
800
0
      if (module_sp && module_sp->GetObjectFile() &&
801
0
          module_sp->MatchesModuleSpec(kern_spec)) {
802
        // module_sp is an actual kernel binary we want to add.
803
0
        if (process) {
804
0
          process->GetTarget().GetImages().AppendIfNeeded(module_sp);
805
0
          error.Clear();
806
0
          return error;
807
0
        } else {
808
0
          error = ModuleList::GetSharedModule(kern_spec, module_sp, nullptr,
809
0
                                              nullptr, nullptr);
810
0
          if (module_sp && module_sp->GetObjectFile() &&
811
0
              module_sp->GetObjectFile()->GetType() !=
812
0
                  ObjectFile::Type::eTypeCoreFile) {
813
0
            return error;
814
0
          }
815
0
          module_sp.reset();
816
0
        }
817
0
      }
818
0
    }
819
0
  }
820
821
  // Next try all dSYMs that have no kernel binary next to them (load
822
  // the kernel DWARF stub as the main binary)
823
0
  for (auto possible_kernel_dsym : m_kernel_dsyms_no_binaries) {
824
0
    std::vector<FileSpec> objfile_names =
825
0
        GetDWARFBinaryInDSYMBundle(possible_kernel_dsym);
826
0
    for (FileSpec objfile : objfile_names) {
827
0
      ModuleSpec kern_spec(objfile);
828
0
      kern_spec.GetUUID() = module_spec.GetUUID();
829
0
      kern_spec.GetSymbolFileSpec() = possible_kernel_dsym;
830
831
0
      module_sp.reset(new Module(kern_spec));
832
0
      if (module_sp && module_sp->GetObjectFile() &&
833
0
          module_sp->MatchesModuleSpec(kern_spec)) {
834
        // module_sp is an actual kernel binary we want to add.
835
0
        if (process) {
836
0
          process->GetTarget().GetImages().AppendIfNeeded(module_sp);
837
0
          error.Clear();
838
0
          return error;
839
0
        } else {
840
0
          error = ModuleList::GetSharedModule(kern_spec, module_sp, nullptr,
841
0
                                              nullptr, nullptr);
842
0
          if (module_sp && module_sp->GetObjectFile() &&
843
0
              module_sp->GetObjectFile()->GetType() !=
844
0
                  ObjectFile::Type::eTypeCoreFile) {
845
0
            return error;
846
0
          }
847
0
          module_sp.reset();
848
0
        }
849
0
      }
850
0
    }
851
0
  }
852
853
  // Give the generic methods, including possibly calling into  DebugSymbols
854
  // framework on macOS systems, a chance.
855
0
  error = PlatformDarwin::GetSharedModule(module_spec, process, module_sp,
856
0
                                          module_search_paths_ptr, old_modules,
857
0
                                          did_create_ptr);
858
0
  if (error.Success() && module_sp.get()) {
859
0
    return error;
860
0
  }
861
862
0
  return error;
863
0
}
864
865
std::vector<lldb_private::FileSpec>
866
0
PlatformDarwinKernel::SearchForExecutablesRecursively(const std::string &dir) {
867
0
  std::vector<FileSpec> executables;
868
0
  std::error_code EC;
869
0
  for (llvm::sys::fs::recursive_directory_iterator it(dir.c_str(), EC),
870
0
       end;
871
0
       it != end && !EC; it.increment(EC)) {
872
0
    auto status = it->status();
873
0
    if (!status)
874
0
      break;
875
0
    if (llvm::sys::fs::is_regular_file(*status) &&
876
0
        llvm::sys::fs::can_execute(it->path()))
877
0
      executables.emplace_back(it->path());
878
0
  }
879
0
  return executables;
880
0
}
881
882
Status PlatformDarwinKernel::ExamineKextForMatchingUUID(
883
    const FileSpec &kext_bundle_path, const lldb_private::UUID &uuid,
884
0
    const ArchSpec &arch, ModuleSP &exe_module_sp) {
885
0
  for (const auto &exe_file :
886
0
       SearchForExecutablesRecursively(kext_bundle_path.GetPath())) {
887
0
    if (FileSystem::Instance().Exists(exe_file)) {
888
0
      ModuleSpec exe_spec(exe_file);
889
0
      exe_spec.GetUUID() = uuid;
890
0
      if (!uuid.IsValid()) {
891
0
        exe_spec.GetArchitecture() = arch;
892
0
      }
893
894
      // First try to create a ModuleSP with the file / arch and see if the UUID
895
      // matches. If that fails (this exec file doesn't have the correct uuid),
896
      // don't call GetSharedModule (which may call in to the DebugSymbols
897
      // framework and therefore can be slow.)
898
0
      ModuleSP module_sp(new Module(exe_spec));
899
0
      if (module_sp && module_sp->GetObjectFile() &&
900
0
          module_sp->MatchesModuleSpec(exe_spec)) {
901
0
        Status error = ModuleList::GetSharedModule(exe_spec, exe_module_sp,
902
0
                                                   NULL, NULL, NULL);
903
0
        if (exe_module_sp && exe_module_sp->GetObjectFile()) {
904
0
          return error;
905
0
        }
906
0
      }
907
0
      exe_module_sp.reset();
908
0
    }
909
0
  }
910
911
0
  return {};
912
0
}
913
914
0
std::vector<ArchSpec> PlatformDarwinKernel::GetSupportedArchitectures() {
915
0
  std::vector<ArchSpec> result;
916
#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
917
  ARMGetSupportedArchitectures(result);
918
#else
919
0
  x86GetSupportedArchitectures(result);
920
0
#endif
921
0
  return result;
922
0
}
923
924
0
void PlatformDarwinKernel::CalculateTrapHandlerSymbolNames() {
925
0
  m_trap_handlers.push_back(ConstString("trap_from_kernel"));
926
0
  m_trap_handlers.push_back(ConstString("hndl_machine_check"));
927
0
  m_trap_handlers.push_back(ConstString("hndl_double_fault"));
928
0
  m_trap_handlers.push_back(ConstString("hndl_allintrs"));
929
0
  m_trap_handlers.push_back(ConstString("hndl_alltraps"));
930
0
  m_trap_handlers.push_back(ConstString("interrupt"));
931
0
  m_trap_handlers.push_back(ConstString("fleh_prefabt"));
932
0
  m_trap_handlers.push_back(ConstString("ExceptionVectorsBase"));
933
0
  m_trap_handlers.push_back(ConstString("ExceptionVectorsTable"));
934
0
  m_trap_handlers.push_back(ConstString("fleh_undef"));
935
0
  m_trap_handlers.push_back(ConstString("fleh_dataabt"));
936
0
  m_trap_handlers.push_back(ConstString("fleh_irq"));
937
0
  m_trap_handlers.push_back(ConstString("fleh_decirq"));
938
0
  m_trap_handlers.push_back(ConstString("fleh_fiq_generic"));
939
0
  m_trap_handlers.push_back(ConstString("fleh_dec"));
940
0
}
941
942
#endif // __APPLE__