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