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