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