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