1 //===- HeaderSearch.cpp - Resolve Header File Locations -------------------===// 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 // This file implements the DirectoryLookup and HeaderSearch interfaces. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Lex/HeaderSearch.h" 14 #include "clang/Basic/Diagnostic.h" 15 #include "clang/Basic/FileManager.h" 16 #include "clang/Basic/IdentifierTable.h" 17 #include "clang/Basic/Module.h" 18 #include "clang/Basic/SourceManager.h" 19 #include "clang/Lex/DirectoryLookup.h" 20 #include "clang/Lex/ExternalPreprocessorSource.h" 21 #include "clang/Lex/HeaderMap.h" 22 #include "clang/Lex/HeaderSearchOptions.h" 23 #include "clang/Lex/LexDiagnostic.h" 24 #include "clang/Lex/ModuleMap.h" 25 #include "clang/Lex/Preprocessor.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/Hashing.h" 28 #include "llvm/ADT/SmallString.h" 29 #include "llvm/ADT/SmallVector.h" 30 #include "llvm/ADT/Statistic.h" 31 #include "llvm/ADT/StringRef.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/Support/Allocator.h" 34 #include "llvm/Support/Capacity.h" 35 #include "llvm/Support/Errc.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/FileSystem.h" 38 #include "llvm/Support/Path.h" 39 #include "llvm/Support/VirtualFileSystem.h" 40 #include <algorithm> 41 #include <cassert> 42 #include <cstddef> 43 #include <cstdio> 44 #include <cstring> 45 #include <string> 46 #include <system_error> 47 #include <utility> 48 49 using namespace clang; 50 51 #define DEBUG_TYPE "file-search" 52 53 ALWAYS_ENABLED_STATISTIC(NumIncluded, "Number of attempted #includes."); 54 ALWAYS_ENABLED_STATISTIC( 55 NumMultiIncludeFileOptzn, 56 "Number of #includes skipped due to the multi-include optimization."); 57 ALWAYS_ENABLED_STATISTIC(NumFrameworkLookups, "Number of framework lookups."); 58 ALWAYS_ENABLED_STATISTIC(NumSubFrameworkLookups, 59 "Number of subframework lookups."); 60 61 const IdentifierInfo * 62 HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) { 63 if (ControllingMacro) { 64 if (ControllingMacro->isOutOfDate()) { 65 assert(External && "We must have an external source if we have a " 66 "controlling macro that is out of date."); 67 External->updateOutOfDateIdentifier( 68 *const_cast<IdentifierInfo *>(ControllingMacro)); 69 } 70 return ControllingMacro; 71 } 72 73 if (!ControllingMacroID || !External) 74 return nullptr; 75 76 ControllingMacro = External->GetIdentifier(ControllingMacroID); 77 return ControllingMacro; 78 } 79 80 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() = default; 81 82 HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts, 83 SourceManager &SourceMgr, DiagnosticsEngine &Diags, 84 const LangOptions &LangOpts, 85 const TargetInfo *Target) 86 : HSOpts(std::move(HSOpts)), Diags(Diags), 87 FileMgr(SourceMgr.getFileManager()), FrameworkMap(64), 88 ModMap(SourceMgr, Diags, LangOpts, Target, *this) {} 89 90 void HeaderSearch::PrintStats() { 91 llvm::errs() << "\n*** HeaderSearch Stats:\n" 92 << FileInfo.size() << " files tracked.\n"; 93 unsigned NumOnceOnlyFiles = 0; 94 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) 95 NumOnceOnlyFiles += (FileInfo[i].isPragmaOnce || FileInfo[i].isImport); 96 llvm::errs() << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n"; 97 98 llvm::errs() << " " << NumIncluded << " #include/#include_next/#import.\n" 99 << " " << NumMultiIncludeFileOptzn 100 << " #includes skipped due to the multi-include optimization.\n"; 101 102 llvm::errs() << NumFrameworkLookups << " framework lookups.\n" 103 << NumSubFrameworkLookups << " subframework lookups.\n"; 104 } 105 106 void HeaderSearch::SetSearchPaths( 107 std::vector<DirectoryLookup> dirs, unsigned int angledDirIdx, 108 unsigned int systemDirIdx, bool noCurDirSearch, 109 llvm::DenseMap<unsigned int, unsigned int> searchDirToHSEntry) { 110 assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() && 111 "Directory indices are unordered"); 112 SearchDirs = std::move(dirs); 113 SearchDirsUsage.assign(SearchDirs.size(), false); 114 AngledDirIdx = angledDirIdx; 115 SystemDirIdx = systemDirIdx; 116 NoCurDirSearch = noCurDirSearch; 117 SearchDirToHSEntry = std::move(searchDirToHSEntry); 118 //LookupFileCache.clear(); 119 } 120 121 void HeaderSearch::AddSearchPath(const DirectoryLookup &dir, bool isAngled) { 122 unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx; 123 SearchDirs.insert(SearchDirs.begin() + idx, dir); 124 SearchDirsUsage.insert(SearchDirsUsage.begin() + idx, false); 125 if (!isAngled) 126 AngledDirIdx++; 127 SystemDirIdx++; 128 } 129 130 std::vector<bool> HeaderSearch::computeUserEntryUsage() const { 131 std::vector<bool> UserEntryUsage(HSOpts->UserEntries.size()); 132 for (unsigned I = 0, E = SearchDirsUsage.size(); I < E; ++I) { 133 // Check whether this DirectoryLookup has been successfully used. 134 if (SearchDirsUsage[I]) { 135 auto UserEntryIdxIt = SearchDirToHSEntry.find(I); 136 // Check whether this DirectoryLookup maps to a HeaderSearch::UserEntry. 137 if (UserEntryIdxIt != SearchDirToHSEntry.end()) 138 UserEntryUsage[UserEntryIdxIt->second] = true; 139 } 140 } 141 return UserEntryUsage; 142 } 143 144 /// CreateHeaderMap - This method returns a HeaderMap for the specified 145 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure. 146 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) { 147 // We expect the number of headermaps to be small, and almost always empty. 148 // If it ever grows, use of a linear search should be re-evaluated. 149 if (!HeaderMaps.empty()) { 150 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i) 151 // Pointer equality comparison of FileEntries works because they are 152 // already uniqued by inode. 153 if (HeaderMaps[i].first == FE) 154 return HeaderMaps[i].second.get(); 155 } 156 157 if (std::unique_ptr<HeaderMap> HM = HeaderMap::Create(FE, FileMgr)) { 158 HeaderMaps.emplace_back(FE, std::move(HM)); 159 return HeaderMaps.back().second.get(); 160 } 161 162 return nullptr; 163 } 164 165 /// Get filenames for all registered header maps. 166 void HeaderSearch::getHeaderMapFileNames( 167 SmallVectorImpl<std::string> &Names) const { 168 for (auto &HM : HeaderMaps) 169 Names.push_back(std::string(HM.first->getName())); 170 } 171 172 std::string HeaderSearch::getCachedModuleFileName(Module *Module) { 173 const FileEntry *ModuleMap = 174 getModuleMap().getModuleMapFileForUniquing(Module); 175 // The ModuleMap maybe a nullptr, when we load a cached C++ module without 176 // *.modulemap file. In this case, just return an empty string. 177 if (ModuleMap == nullptr) 178 return {}; 179 return getCachedModuleFileName(Module->Name, ModuleMap->getName()); 180 } 181 182 std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName, 183 bool FileMapOnly) { 184 // First check the module name to pcm file map. 185 auto i(HSOpts->PrebuiltModuleFiles.find(ModuleName)); 186 if (i != HSOpts->PrebuiltModuleFiles.end()) 187 return i->second; 188 189 if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty()) 190 return {}; 191 192 // Then go through each prebuilt module directory and try to find the pcm 193 // file. 194 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) { 195 SmallString<256> Result(Dir); 196 llvm::sys::fs::make_absolute(Result); 197 if (ModuleName.contains(':')) 198 // The separator of C++20 modules partitions (':') is not good for file 199 // systems, here clang and gcc choose '-' by default since it is not a 200 // valid character of C++ indentifiers. So we could avoid conflicts. 201 llvm::sys::path::append(Result, ModuleName.split(':').first + "-" + 202 ModuleName.split(':').second + 203 ".pcm"); 204 else 205 llvm::sys::path::append(Result, ModuleName + ".pcm"); 206 if (getFileMgr().getFile(Result.str())) 207 return std::string(Result); 208 } 209 210 return {}; 211 } 212 213 std::string HeaderSearch::getPrebuiltImplicitModuleFileName(Module *Module) { 214 const FileEntry *ModuleMap = 215 getModuleMap().getModuleMapFileForUniquing(Module); 216 StringRef ModuleName = Module->Name; 217 StringRef ModuleMapPath = ModuleMap->getName(); 218 StringRef ModuleCacheHash = HSOpts->DisableModuleHash ? "" : getModuleHash(); 219 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) { 220 SmallString<256> CachePath(Dir); 221 llvm::sys::fs::make_absolute(CachePath); 222 llvm::sys::path::append(CachePath, ModuleCacheHash); 223 std::string FileName = 224 getCachedModuleFileNameImpl(ModuleName, ModuleMapPath, CachePath); 225 if (!FileName.empty() && getFileMgr().getFile(FileName)) 226 return FileName; 227 } 228 return {}; 229 } 230 231 std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName, 232 StringRef ModuleMapPath) { 233 return getCachedModuleFileNameImpl(ModuleName, ModuleMapPath, 234 getModuleCachePath()); 235 } 236 237 std::string HeaderSearch::getCachedModuleFileNameImpl(StringRef ModuleName, 238 StringRef ModuleMapPath, 239 StringRef CachePath) { 240 // If we don't have a module cache path or aren't supposed to use one, we 241 // can't do anything. 242 if (CachePath.empty()) 243 return {}; 244 245 SmallString<256> Result(CachePath); 246 llvm::sys::fs::make_absolute(Result); 247 248 if (HSOpts->DisableModuleHash) { 249 llvm::sys::path::append(Result, ModuleName + ".pcm"); 250 } else { 251 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should 252 // ideally be globally unique to this particular module. Name collisions 253 // in the hash are safe (because any translation unit can only import one 254 // module with each name), but result in a loss of caching. 255 // 256 // To avoid false-negatives, we form as canonical a path as we can, and map 257 // to lower-case in case we're on a case-insensitive file system. 258 std::string Parent = 259 std::string(llvm::sys::path::parent_path(ModuleMapPath)); 260 if (Parent.empty()) 261 Parent = "."; 262 auto Dir = FileMgr.getDirectory(Parent); 263 if (!Dir) 264 return {}; 265 auto DirName = FileMgr.getCanonicalName(*Dir); 266 auto FileName = llvm::sys::path::filename(ModuleMapPath); 267 268 llvm::hash_code Hash = 269 llvm::hash_combine(DirName.lower(), FileName.lower()); 270 271 SmallString<128> HashStr; 272 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36); 273 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm"); 274 } 275 return Result.str().str(); 276 } 277 278 Module *HeaderSearch::lookupModule(StringRef ModuleName, 279 SourceLocation ImportLoc, bool AllowSearch, 280 bool AllowExtraModuleMapSearch) { 281 // Look in the module map to determine if there is a module by this name. 282 Module *Module = ModMap.findModule(ModuleName); 283 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps) 284 return Module; 285 286 StringRef SearchName = ModuleName; 287 Module = lookupModule(ModuleName, SearchName, ImportLoc, 288 AllowExtraModuleMapSearch); 289 290 // The facility for "private modules" -- adjacent, optional module maps named 291 // module.private.modulemap that are supposed to define private submodules -- 292 // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private. 293 // 294 // Foo.Private is now deprecated in favor of Foo_Private. Users of FooPrivate 295 // should also rename to Foo_Private. Representing private as submodules 296 // could force building unwanted dependencies into the parent module and cause 297 // dependency cycles. 298 if (!Module && SearchName.consume_back("_Private")) 299 Module = lookupModule(ModuleName, SearchName, ImportLoc, 300 AllowExtraModuleMapSearch); 301 if (!Module && SearchName.consume_back("Private")) 302 Module = lookupModule(ModuleName, SearchName, ImportLoc, 303 AllowExtraModuleMapSearch); 304 return Module; 305 } 306 307 Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName, 308 SourceLocation ImportLoc, 309 bool AllowExtraModuleMapSearch) { 310 Module *Module = nullptr; 311 312 // Look through the various header search paths to load any available module 313 // maps, searching for a module map that describes this module. 314 for (DirectoryLookup Dir : search_dir_range()) { 315 if (Dir.isFramework()) { 316 // Search for or infer a module map for a framework. Here we use 317 // SearchName rather than ModuleName, to permit finding private modules 318 // named FooPrivate in buggy frameworks named Foo. 319 SmallString<128> FrameworkDirName; 320 FrameworkDirName += Dir.getFrameworkDir()->getName(); 321 llvm::sys::path::append(FrameworkDirName, SearchName + ".framework"); 322 if (auto FrameworkDir = FileMgr.getDirectory(FrameworkDirName)) { 323 bool IsSystem = Dir.getDirCharacteristic() != SrcMgr::C_User; 324 Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem); 325 if (Module) 326 break; 327 } 328 } 329 330 // FIXME: Figure out how header maps and module maps will work together. 331 332 // Only deal with normal search directories. 333 if (!Dir.isNormalDir()) 334 continue; 335 336 bool IsSystem = Dir.isSystemHeaderDirectory(); 337 // Search for a module map file in this directory. 338 if (loadModuleMapFile(Dir.getDir(), IsSystem, 339 /*IsFramework*/false) == LMM_NewlyLoaded) { 340 // We just loaded a module map file; check whether the module is 341 // available now. 342 Module = ModMap.findModule(ModuleName); 343 if (Module) 344 break; 345 } 346 347 // Search for a module map in a subdirectory with the same name as the 348 // module. 349 SmallString<128> NestedModuleMapDirName; 350 NestedModuleMapDirName = Dir.getDir()->getName(); 351 llvm::sys::path::append(NestedModuleMapDirName, ModuleName); 352 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem, 353 /*IsFramework*/false) == LMM_NewlyLoaded){ 354 // If we just loaded a module map file, look for the module again. 355 Module = ModMap.findModule(ModuleName); 356 if (Module) 357 break; 358 } 359 360 // If we've already performed the exhaustive search for module maps in this 361 // search directory, don't do it again. 362 if (Dir.haveSearchedAllModuleMaps()) 363 continue; 364 365 // Load all module maps in the immediate subdirectories of this search 366 // directory if ModuleName was from @import. 367 if (AllowExtraModuleMapSearch) 368 loadSubdirectoryModuleMaps(Dir); 369 370 // Look again for the module. 371 Module = ModMap.findModule(ModuleName); 372 if (Module) 373 break; 374 } 375 376 return Module; 377 } 378 379 //===----------------------------------------------------------------------===// 380 // File lookup within a DirectoryLookup scope 381 //===----------------------------------------------------------------------===// 382 383 /// getName - Return the directory or filename corresponding to this lookup 384 /// object. 385 StringRef DirectoryLookup::getName() const { 386 // FIXME: Use the name from \c DirectoryEntryRef. 387 if (isNormalDir()) 388 return getDir()->getName(); 389 if (isFramework()) 390 return getFrameworkDir()->getName(); 391 assert(isHeaderMap() && "Unknown DirectoryLookup"); 392 return getHeaderMap()->getFileName(); 393 } 394 395 Optional<FileEntryRef> HeaderSearch::getFileAndSuggestModule( 396 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir, 397 bool IsSystemHeaderDir, Module *RequestingModule, 398 ModuleMap::KnownHeader *SuggestedModule) { 399 // If we have a module map that might map this header, load it and 400 // check whether we'll have a suggestion for a module. 401 auto File = getFileMgr().getFileRef(FileName, /*OpenFile=*/true); 402 if (!File) { 403 // For rare, surprising errors (e.g. "out of file handles"), diag the EC 404 // message. 405 std::error_code EC = llvm::errorToErrorCode(File.takeError()); 406 if (EC != llvm::errc::no_such_file_or_directory && 407 EC != llvm::errc::invalid_argument && 408 EC != llvm::errc::is_a_directory && EC != llvm::errc::not_a_directory) { 409 Diags.Report(IncludeLoc, diag::err_cannot_open_file) 410 << FileName << EC.message(); 411 } 412 return None; 413 } 414 415 // If there is a module that corresponds to this header, suggest it. 416 if (!findUsableModuleForHeader( 417 &File->getFileEntry(), Dir ? Dir : File->getFileEntry().getDir(), 418 RequestingModule, SuggestedModule, IsSystemHeaderDir)) 419 return None; 420 421 return *File; 422 } 423 424 /// LookupFile - Lookup the specified file in this search path, returning it 425 /// if it exists or returning null if not. 426 Optional<FileEntryRef> DirectoryLookup::LookupFile( 427 StringRef &Filename, HeaderSearch &HS, SourceLocation IncludeLoc, 428 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, 429 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule, 430 bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound, 431 bool &IsInHeaderMap, SmallVectorImpl<char> &MappedName) const { 432 InUserSpecifiedSystemFramework = false; 433 IsInHeaderMap = false; 434 MappedName.clear(); 435 436 SmallString<1024> TmpDir; 437 if (isNormalDir()) { 438 // Concatenate the requested file onto the directory. 439 TmpDir = getDirRef()->getName(); 440 llvm::sys::path::append(TmpDir, Filename); 441 if (SearchPath) { 442 StringRef SearchPathRef(getDirRef()->getName()); 443 SearchPath->clear(); 444 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); 445 } 446 if (RelativePath) { 447 RelativePath->clear(); 448 RelativePath->append(Filename.begin(), Filename.end()); 449 } 450 451 return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(), 452 isSystemHeaderDirectory(), 453 RequestingModule, SuggestedModule); 454 } 455 456 if (isFramework()) 457 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath, 458 RequestingModule, SuggestedModule, 459 InUserSpecifiedSystemFramework, IsFrameworkFound); 460 461 assert(isHeaderMap() && "Unknown directory lookup"); 462 const HeaderMap *HM = getHeaderMap(); 463 SmallString<1024> Path; 464 StringRef Dest = HM->lookupFilename(Filename, Path); 465 if (Dest.empty()) 466 return None; 467 468 IsInHeaderMap = true; 469 470 auto FixupSearchPath = [&]() { 471 if (SearchPath) { 472 StringRef SearchPathRef(getName()); 473 SearchPath->clear(); 474 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); 475 } 476 if (RelativePath) { 477 RelativePath->clear(); 478 RelativePath->append(Filename.begin(), Filename.end()); 479 } 480 }; 481 482 // Check if the headermap maps the filename to a framework include 483 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the 484 // framework include. 485 if (llvm::sys::path::is_relative(Dest)) { 486 MappedName.append(Dest.begin(), Dest.end()); 487 Filename = StringRef(MappedName.begin(), MappedName.size()); 488 Dest = HM->lookupFilename(Filename, Path); 489 } 490 491 if (auto Res = HS.getFileMgr().getOptionalFileRef(Dest)) { 492 FixupSearchPath(); 493 return *Res; 494 } 495 496 // Header maps need to be marked as used whenever the filename matches. 497 // The case where the target file **exists** is handled by callee of this 498 // function as part of the regular logic that applies to include search paths. 499 // The case where the target file **does not exist** is handled here: 500 HS.noteLookupUsage(HS.searchDirIdx(*this), IncludeLoc); 501 return None; 502 } 503 504 /// Given a framework directory, find the top-most framework directory. 505 /// 506 /// \param FileMgr The file manager to use for directory lookups. 507 /// \param DirName The name of the framework directory. 508 /// \param SubmodulePath Will be populated with the submodule path from the 509 /// returned top-level module to the originally named framework. 510 static const DirectoryEntry * 511 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName, 512 SmallVectorImpl<std::string> &SubmodulePath) { 513 assert(llvm::sys::path::extension(DirName) == ".framework" && 514 "Not a framework directory"); 515 516 // Note: as an egregious but useful hack we use the real path here, because 517 // frameworks moving between top-level frameworks to embedded frameworks tend 518 // to be symlinked, and we base the logical structure of modules on the 519 // physical layout. In particular, we need to deal with crazy includes like 520 // 521 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h> 522 // 523 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework 524 // which one should access with, e.g., 525 // 526 // #include <Bar/Wibble.h> 527 // 528 // Similar issues occur when a top-level framework has moved into an 529 // embedded framework. 530 const DirectoryEntry *TopFrameworkDir = nullptr; 531 if (auto TopFrameworkDirOrErr = FileMgr.getDirectory(DirName)) 532 TopFrameworkDir = *TopFrameworkDirOrErr; 533 534 if (TopFrameworkDir) 535 DirName = FileMgr.getCanonicalName(TopFrameworkDir); 536 do { 537 // Get the parent directory name. 538 DirName = llvm::sys::path::parent_path(DirName); 539 if (DirName.empty()) 540 break; 541 542 // Determine whether this directory exists. 543 auto Dir = FileMgr.getDirectory(DirName); 544 if (!Dir) 545 break; 546 547 // If this is a framework directory, then we're a subframework of this 548 // framework. 549 if (llvm::sys::path::extension(DirName) == ".framework") { 550 SubmodulePath.push_back(std::string(llvm::sys::path::stem(DirName))); 551 TopFrameworkDir = *Dir; 552 } 553 } while (true); 554 555 return TopFrameworkDir; 556 } 557 558 static bool needModuleLookup(Module *RequestingModule, 559 bool HasSuggestedModule) { 560 return HasSuggestedModule || 561 (RequestingModule && RequestingModule->NoUndeclaredIncludes); 562 } 563 564 /// DoFrameworkLookup - Do a lookup of the specified file in the current 565 /// DirectoryLookup, which is a framework directory. 566 Optional<FileEntryRef> DirectoryLookup::DoFrameworkLookup( 567 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath, 568 SmallVectorImpl<char> *RelativePath, Module *RequestingModule, 569 ModuleMap::KnownHeader *SuggestedModule, 570 bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound) const { 571 FileManager &FileMgr = HS.getFileMgr(); 572 573 // Framework names must have a '/' in the filename. 574 size_t SlashPos = Filename.find('/'); 575 if (SlashPos == StringRef::npos) 576 return None; 577 578 // Find out if this is the home for the specified framework, by checking 579 // HeaderSearch. Possible answers are yes/no and unknown. 580 FrameworkCacheEntry &CacheEntry = 581 HS.LookupFrameworkCache(Filename.substr(0, SlashPos)); 582 583 // If it is known and in some other directory, fail. 584 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDirRef()) 585 return None; 586 587 // Otherwise, construct the path to this framework dir. 588 589 // FrameworkName = "/System/Library/Frameworks/" 590 SmallString<1024> FrameworkName; 591 FrameworkName += getFrameworkDirRef()->getName(); 592 if (FrameworkName.empty() || FrameworkName.back() != '/') 593 FrameworkName.push_back('/'); 594 595 // FrameworkName = "/System/Library/Frameworks/Cocoa" 596 StringRef ModuleName(Filename.begin(), SlashPos); 597 FrameworkName += ModuleName; 598 599 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/" 600 FrameworkName += ".framework/"; 601 602 // If the cache entry was unresolved, populate it now. 603 if (!CacheEntry.Directory) { 604 ++NumFrameworkLookups; 605 606 // If the framework dir doesn't exist, we fail. 607 auto Dir = FileMgr.getDirectory(FrameworkName); 608 if (!Dir) 609 return None; 610 611 // Otherwise, if it does, remember that this is the right direntry for this 612 // framework. 613 CacheEntry.Directory = getFrameworkDirRef(); 614 615 // If this is a user search directory, check if the framework has been 616 // user-specified as a system framework. 617 if (getDirCharacteristic() == SrcMgr::C_User) { 618 SmallString<1024> SystemFrameworkMarker(FrameworkName); 619 SystemFrameworkMarker += ".system_framework"; 620 if (llvm::sys::fs::exists(SystemFrameworkMarker)) { 621 CacheEntry.IsUserSpecifiedSystemFramework = true; 622 } 623 } 624 } 625 626 // Set out flags. 627 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework; 628 IsFrameworkFound = CacheEntry.Directory.hasValue(); 629 630 if (RelativePath) { 631 RelativePath->clear(); 632 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end()); 633 } 634 635 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h" 636 unsigned OrigSize = FrameworkName.size(); 637 638 FrameworkName += "Headers/"; 639 640 if (SearchPath) { 641 SearchPath->clear(); 642 // Without trailing '/'. 643 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1); 644 } 645 646 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end()); 647 648 auto File = 649 FileMgr.getOptionalFileRef(FrameworkName, /*OpenFile=*/!SuggestedModule); 650 if (!File) { 651 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h" 652 const char *Private = "Private"; 653 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private, 654 Private+strlen(Private)); 655 if (SearchPath) 656 SearchPath->insert(SearchPath->begin()+OrigSize, Private, 657 Private+strlen(Private)); 658 659 File = FileMgr.getOptionalFileRef(FrameworkName, 660 /*OpenFile=*/!SuggestedModule); 661 } 662 663 // If we found the header and are allowed to suggest a module, do so now. 664 if (File && needModuleLookup(RequestingModule, SuggestedModule)) { 665 // Find the framework in which this header occurs. 666 StringRef FrameworkPath = File->getFileEntry().getDir()->getName(); 667 bool FoundFramework = false; 668 do { 669 // Determine whether this directory exists. 670 auto Dir = FileMgr.getDirectory(FrameworkPath); 671 if (!Dir) 672 break; 673 674 // If this is a framework directory, then we're a subframework of this 675 // framework. 676 if (llvm::sys::path::extension(FrameworkPath) == ".framework") { 677 FoundFramework = true; 678 break; 679 } 680 681 // Get the parent directory name. 682 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath); 683 if (FrameworkPath.empty()) 684 break; 685 } while (true); 686 687 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User; 688 if (FoundFramework) { 689 if (!HS.findUsableModuleForFrameworkHeader( 690 &File->getFileEntry(), FrameworkPath, RequestingModule, 691 SuggestedModule, IsSystem)) 692 return None; 693 } else { 694 if (!HS.findUsableModuleForHeader(&File->getFileEntry(), getDir(), 695 RequestingModule, SuggestedModule, 696 IsSystem)) 697 return None; 698 } 699 } 700 if (File) 701 return *File; 702 return None; 703 } 704 705 void HeaderSearch::cacheLookupSuccess(LookupFileCacheInfo &CacheLookup, 706 ConstSearchDirIterator HitIt, 707 SourceLocation Loc) { 708 CacheLookup.HitIt = HitIt; 709 noteLookupUsage(HitIt.Idx, Loc); 710 } 711 712 void HeaderSearch::noteLookupUsage(unsigned HitIdx, SourceLocation Loc) { 713 SearchDirsUsage[HitIdx] = true; 714 715 auto UserEntryIdxIt = SearchDirToHSEntry.find(HitIdx); 716 if (UserEntryIdxIt != SearchDirToHSEntry.end()) 717 Diags.Report(Loc, diag::remark_pp_search_path_usage) 718 << HSOpts->UserEntries[UserEntryIdxIt->second].Path; 719 } 720 721 void HeaderSearch::setTarget(const TargetInfo &Target) { 722 ModMap.setTarget(Target); 723 } 724 725 //===----------------------------------------------------------------------===// 726 // Header File Location. 727 //===----------------------------------------------------------------------===// 728 729 /// Return true with a diagnostic if the file that MSVC would have found 730 /// fails to match the one that Clang would have found with MSVC header search 731 /// disabled. 732 static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags, 733 const FileEntry *MSFE, const FileEntry *FE, 734 SourceLocation IncludeLoc) { 735 if (MSFE && FE != MSFE) { 736 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName(); 737 return true; 738 } 739 return false; 740 } 741 742 static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) { 743 assert(!Str.empty()); 744 char *CopyStr = Alloc.Allocate<char>(Str.size()+1); 745 std::copy(Str.begin(), Str.end(), CopyStr); 746 CopyStr[Str.size()] = '\0'; 747 return CopyStr; 748 } 749 750 static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader, 751 SmallVectorImpl<char> &FrameworkName, 752 SmallVectorImpl<char> &IncludeSpelling) { 753 using namespace llvm::sys; 754 path::const_iterator I = path::begin(Path); 755 path::const_iterator E = path::end(Path); 756 IsPrivateHeader = false; 757 758 // Detect different types of framework style paths: 759 // 760 // ...Foo.framework/{Headers,PrivateHeaders} 761 // ...Foo.framework/Versions/{A,Current}/{Headers,PrivateHeaders} 762 // ...Foo.framework/Frameworks/Nested.framework/{Headers,PrivateHeaders} 763 // ...<other variations with 'Versions' like in the above path> 764 // 765 // and some other variations among these lines. 766 int FoundComp = 0; 767 while (I != E) { 768 if (*I == "Headers") { 769 ++FoundComp; 770 } else if (*I == "PrivateHeaders") { 771 ++FoundComp; 772 IsPrivateHeader = true; 773 } else if (I->endswith(".framework")) { 774 StringRef Name = I->drop_back(10); // Drop .framework 775 // Need to reset the strings and counter to support nested frameworks. 776 FrameworkName.clear(); 777 FrameworkName.append(Name.begin(), Name.end()); 778 IncludeSpelling.clear(); 779 IncludeSpelling.append(Name.begin(), Name.end()); 780 FoundComp = 1; 781 } else if (FoundComp >= 2) { 782 IncludeSpelling.push_back('/'); 783 IncludeSpelling.append(I->begin(), I->end()); 784 } 785 ++I; 786 } 787 788 return !FrameworkName.empty() && FoundComp >= 2; 789 } 790 791 static void 792 diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc, 793 StringRef Includer, StringRef IncludeFilename, 794 const FileEntry *IncludeFE, bool isAngled = false, 795 bool FoundByHeaderMap = false) { 796 bool IsIncluderPrivateHeader = false; 797 SmallString<128> FromFramework, ToFramework; 798 SmallString<128> FromIncludeSpelling, ToIncludeSpelling; 799 if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework, 800 FromIncludeSpelling)) 801 return; 802 bool IsIncludeePrivateHeader = false; 803 bool IsIncludeeInFramework = 804 isFrameworkStylePath(IncludeFE->getName(), IsIncludeePrivateHeader, 805 ToFramework, ToIncludeSpelling); 806 807 if (!isAngled && !FoundByHeaderMap) { 808 SmallString<128> NewInclude("<"); 809 if (IsIncludeeInFramework) { 810 NewInclude += ToIncludeSpelling; 811 NewInclude += ">"; 812 } else { 813 NewInclude += IncludeFilename; 814 NewInclude += ">"; 815 } 816 Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header) 817 << IncludeFilename 818 << FixItHint::CreateReplacement(IncludeLoc, NewInclude); 819 } 820 821 // Headers in Foo.framework/Headers should not include headers 822 // from Foo.framework/PrivateHeaders, since this violates public/private 823 // API boundaries and can cause modular dependency cycles. 824 if (!IsIncluderPrivateHeader && IsIncludeeInFramework && 825 IsIncludeePrivateHeader && FromFramework == ToFramework) 826 Diags.Report(IncludeLoc, diag::warn_framework_include_private_from_public) 827 << IncludeFilename; 828 } 829 830 /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file, 831 /// return null on failure. isAngled indicates whether the file reference is 832 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if 833 /// non-empty, indicates where the \#including file(s) are, in case a relative 834 /// search is needed. Microsoft mode will pass all \#including files. 835 Optional<FileEntryRef> HeaderSearch::LookupFile( 836 StringRef Filename, SourceLocation IncludeLoc, bool isAngled, 837 ConstSearchDirIterator FromDir, ConstSearchDirIterator *CurDirArg, 838 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers, 839 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, 840 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule, 841 bool *IsMapped, bool *IsFrameworkFound, bool SkipCache, 842 bool BuildSystemModule) { 843 ConstSearchDirIterator CurDirLocal = nullptr; 844 ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal; 845 846 if (IsMapped) 847 *IsMapped = false; 848 849 if (IsFrameworkFound) 850 *IsFrameworkFound = false; 851 852 if (SuggestedModule) 853 *SuggestedModule = ModuleMap::KnownHeader(); 854 855 // If 'Filename' is absolute, check to see if it exists and no searching. 856 if (llvm::sys::path::is_absolute(Filename)) { 857 CurDir = nullptr; 858 859 // If this was an #include_next "/absolute/file", fail. 860 if (FromDir) 861 return None; 862 863 if (SearchPath) 864 SearchPath->clear(); 865 if (RelativePath) { 866 RelativePath->clear(); 867 RelativePath->append(Filename.begin(), Filename.end()); 868 } 869 // Otherwise, just return the file. 870 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr, 871 /*IsSystemHeaderDir*/false, 872 RequestingModule, SuggestedModule); 873 } 874 875 // This is the header that MSVC's header search would have found. 876 ModuleMap::KnownHeader MSSuggestedModule; 877 Optional<FileEntryRef> MSFE; 878 879 // Unless disabled, check to see if the file is in the #includer's 880 // directory. This cannot be based on CurDir, because each includer could be 881 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent 882 // include of "baz.h" should resolve to "whatever/foo/baz.h". 883 // This search is not done for <> headers. 884 if (!Includers.empty() && !isAngled && !NoCurDirSearch) { 885 SmallString<1024> TmpDir; 886 bool First = true; 887 for (const auto &IncluderAndDir : Includers) { 888 const FileEntry *Includer = IncluderAndDir.first; 889 890 // Concatenate the requested file onto the directory. 891 // FIXME: Portability. Filename concatenation should be in sys::Path. 892 TmpDir = IncluderAndDir.second->getName(); 893 TmpDir.push_back('/'); 894 TmpDir.append(Filename.begin(), Filename.end()); 895 896 // FIXME: We don't cache the result of getFileInfo across the call to 897 // getFileAndSuggestModule, because it's a reference to an element of 898 // a container that could be reallocated across this call. 899 // 900 // If we have no includer, that means we're processing a #include 901 // from a module build. We should treat this as a system header if we're 902 // building a [system] module. 903 bool IncluderIsSystemHeader = 904 Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User : 905 BuildSystemModule; 906 if (Optional<FileEntryRef> FE = getFileAndSuggestModule( 907 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader, 908 RequestingModule, SuggestedModule)) { 909 if (!Includer) { 910 assert(First && "only first includer can have no file"); 911 return FE; 912 } 913 914 // Leave CurDir unset. 915 // This file is a system header or C++ unfriendly if the old file is. 916 // 917 // Note that we only use one of FromHFI/ToHFI at once, due to potential 918 // reallocation of the underlying vector potentially making the first 919 // reference binding dangling. 920 HeaderFileInfo &FromHFI = getFileInfo(Includer); 921 unsigned DirInfo = FromHFI.DirInfo; 922 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader; 923 StringRef Framework = FromHFI.Framework; 924 925 HeaderFileInfo &ToHFI = getFileInfo(&FE->getFileEntry()); 926 ToHFI.DirInfo = DirInfo; 927 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader; 928 ToHFI.Framework = Framework; 929 930 if (SearchPath) { 931 StringRef SearchPathRef(IncluderAndDir.second->getName()); 932 SearchPath->clear(); 933 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); 934 } 935 if (RelativePath) { 936 RelativePath->clear(); 937 RelativePath->append(Filename.begin(), Filename.end()); 938 } 939 if (First) { 940 diagnoseFrameworkInclude(Diags, IncludeLoc, 941 IncluderAndDir.second->getName(), Filename, 942 &FE->getFileEntry()); 943 return FE; 944 } 945 946 // Otherwise, we found the path via MSVC header search rules. If 947 // -Wmsvc-include is enabled, we have to keep searching to see if we 948 // would've found this header in -I or -isystem directories. 949 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) { 950 return FE; 951 } else { 952 MSFE = FE; 953 if (SuggestedModule) { 954 MSSuggestedModule = *SuggestedModule; 955 *SuggestedModule = ModuleMap::KnownHeader(); 956 } 957 break; 958 } 959 } 960 First = false; 961 } 962 } 963 964 CurDir = nullptr; 965 966 // If this is a system #include, ignore the user #include locs. 967 ConstSearchDirIterator It = 968 isAngled ? angled_dir_begin() : search_dir_begin(); 969 970 // If this is a #include_next request, start searching after the directory the 971 // file was found in. 972 if (FromDir) 973 It = FromDir; 974 975 // Cache all of the lookups performed by this method. Many headers are 976 // multiply included, and the "pragma once" optimization prevents them from 977 // being relex/pp'd, but they would still have to search through a 978 // (potentially huge) series of SearchDirs to find it. 979 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename]; 980 981 ConstSearchDirIterator NextIt = std::next(It); 982 983 // If the entry has been previously looked up, the first value will be 984 // non-zero. If the value is equal to i (the start point of our search), then 985 // this is a matching hit. 986 if (!SkipCache && CacheLookup.StartIt == NextIt) { 987 // Skip querying potentially lots of directories for this lookup. 988 if (CacheLookup.HitIt) 989 It = CacheLookup.HitIt; 990 if (CacheLookup.MappedName) { 991 Filename = CacheLookup.MappedName; 992 if (IsMapped) 993 *IsMapped = true; 994 } 995 } else { 996 // Otherwise, this is the first query, or the previous query didn't match 997 // our search start. We will fill in our found location below, so prime the 998 // start point value. 999 CacheLookup.reset(/*NewStartIt=*/NextIt); 1000 } 1001 1002 SmallString<64> MappedName; 1003 1004 // Check each directory in sequence to see if it contains this file. 1005 for (; It != search_dir_end(); ++It) { 1006 bool InUserSpecifiedSystemFramework = false; 1007 bool IsInHeaderMap = false; 1008 bool IsFrameworkFoundInDir = false; 1009 Optional<FileEntryRef> File = It->LookupFile( 1010 Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule, 1011 SuggestedModule, InUserSpecifiedSystemFramework, IsFrameworkFoundInDir, 1012 IsInHeaderMap, MappedName); 1013 if (!MappedName.empty()) { 1014 assert(IsInHeaderMap && "MappedName should come from a header map"); 1015 CacheLookup.MappedName = 1016 copyString(MappedName, LookupFileCache.getAllocator()); 1017 } 1018 if (IsMapped) 1019 // A filename is mapped when a header map remapped it to a relative path 1020 // used in subsequent header search or to an absolute path pointing to an 1021 // existing file. 1022 *IsMapped |= (!MappedName.empty() || (IsInHeaderMap && File)); 1023 if (IsFrameworkFound) 1024 // Because we keep a filename remapped for subsequent search directory 1025 // lookups, ignore IsFrameworkFoundInDir after the first remapping and not 1026 // just for remapping in a current search directory. 1027 *IsFrameworkFound |= (IsFrameworkFoundInDir && !CacheLookup.MappedName); 1028 if (!File) 1029 continue; 1030 1031 CurDir = It; 1032 1033 // This file is a system header or C++ unfriendly if the dir is. 1034 HeaderFileInfo &HFI = getFileInfo(&File->getFileEntry()); 1035 HFI.DirInfo = CurDir->getDirCharacteristic(); 1036 1037 // If the directory characteristic is User but this framework was 1038 // user-specified to be treated as a system framework, promote the 1039 // characteristic. 1040 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework) 1041 HFI.DirInfo = SrcMgr::C_System; 1042 1043 // If the filename matches a known system header prefix, override 1044 // whether the file is a system header. 1045 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) { 1046 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) { 1047 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System 1048 : SrcMgr::C_User; 1049 break; 1050 } 1051 } 1052 1053 // Set the `Framework` info if this file is in a header map with framework 1054 // style include spelling or found in a framework dir. The header map case 1055 // is possible when building frameworks which use header maps. 1056 if (CurDir->isHeaderMap() && isAngled) { 1057 size_t SlashPos = Filename.find('/'); 1058 if (SlashPos != StringRef::npos) 1059 HFI.Framework = 1060 getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos)); 1061 if (CurDir->isIndexHeaderMap()) 1062 HFI.IndexHeaderMapHeader = 1; 1063 } else if (CurDir->isFramework()) { 1064 size_t SlashPos = Filename.find('/'); 1065 if (SlashPos != StringRef::npos) 1066 HFI.Framework = 1067 getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos)); 1068 } 1069 1070 if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr, 1071 &File->getFileEntry(), IncludeLoc)) { 1072 if (SuggestedModule) 1073 *SuggestedModule = MSSuggestedModule; 1074 return MSFE; 1075 } 1076 1077 bool FoundByHeaderMap = !IsMapped ? false : *IsMapped; 1078 if (!Includers.empty()) 1079 diagnoseFrameworkInclude( 1080 Diags, IncludeLoc, Includers.front().second->getName(), Filename, 1081 &File->getFileEntry(), isAngled, FoundByHeaderMap); 1082 1083 // Remember this location for the next lookup we do. 1084 cacheLookupSuccess(CacheLookup, It, IncludeLoc); 1085 return File; 1086 } 1087 1088 // If we are including a file with a quoted include "foo.h" from inside 1089 // a header in a framework that is currently being built, and we couldn't 1090 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where 1091 // "Foo" is the name of the framework in which the including header was found. 1092 if (!Includers.empty() && Includers.front().first && !isAngled && 1093 !Filename.contains('/')) { 1094 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first); 1095 if (IncludingHFI.IndexHeaderMapHeader) { 1096 SmallString<128> ScratchFilename; 1097 ScratchFilename += IncludingHFI.Framework; 1098 ScratchFilename += '/'; 1099 ScratchFilename += Filename; 1100 1101 Optional<FileEntryRef> File = LookupFile( 1102 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, &CurDir, 1103 Includers.front(), SearchPath, RelativePath, RequestingModule, 1104 SuggestedModule, IsMapped, /*IsFrameworkFound=*/nullptr); 1105 1106 if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr, 1107 File ? &File->getFileEntry() : nullptr, 1108 IncludeLoc)) { 1109 if (SuggestedModule) 1110 *SuggestedModule = MSSuggestedModule; 1111 return MSFE; 1112 } 1113 1114 cacheLookupSuccess(LookupFileCache[Filename], 1115 LookupFileCache[ScratchFilename].HitIt, IncludeLoc); 1116 // FIXME: SuggestedModule. 1117 return File; 1118 } 1119 } 1120 1121 if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr, 1122 nullptr, IncludeLoc)) { 1123 if (SuggestedModule) 1124 *SuggestedModule = MSSuggestedModule; 1125 return MSFE; 1126 } 1127 1128 // Otherwise, didn't find it. Remember we didn't find this. 1129 CacheLookup.HitIt = search_dir_end(); 1130 return None; 1131 } 1132 1133 /// LookupSubframeworkHeader - Look up a subframework for the specified 1134 /// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from 1135 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox 1136 /// is a subframework within Carbon.framework. If so, return the FileEntry 1137 /// for the designated file, otherwise return null. 1138 Optional<FileEntryRef> HeaderSearch::LookupSubframeworkHeader( 1139 StringRef Filename, const FileEntry *ContextFileEnt, 1140 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, 1141 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule) { 1142 assert(ContextFileEnt && "No context file?"); 1143 1144 // Framework names must have a '/' in the filename. Find it. 1145 // FIXME: Should we permit '\' on Windows? 1146 size_t SlashPos = Filename.find('/'); 1147 if (SlashPos == StringRef::npos) 1148 return None; 1149 1150 // Look up the base framework name of the ContextFileEnt. 1151 StringRef ContextName = ContextFileEnt->getName(); 1152 1153 // If the context info wasn't a framework, couldn't be a subframework. 1154 const unsigned DotFrameworkLen = 10; 1155 auto FrameworkPos = ContextName.find(".framework"); 1156 if (FrameworkPos == StringRef::npos || 1157 (ContextName[FrameworkPos + DotFrameworkLen] != '/' && 1158 ContextName[FrameworkPos + DotFrameworkLen] != '\\')) 1159 return None; 1160 1161 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() + 1162 FrameworkPos + 1163 DotFrameworkLen + 1); 1164 1165 // Append Frameworks/HIToolbox.framework/ 1166 FrameworkName += "Frameworks/"; 1167 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos); 1168 FrameworkName += ".framework/"; 1169 1170 auto &CacheLookup = 1171 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos), 1172 FrameworkCacheEntry())).first; 1173 1174 // Some other location? 1175 if (CacheLookup.second.Directory && 1176 CacheLookup.first().size() == FrameworkName.size() && 1177 memcmp(CacheLookup.first().data(), &FrameworkName[0], 1178 CacheLookup.first().size()) != 0) 1179 return None; 1180 1181 // Cache subframework. 1182 if (!CacheLookup.second.Directory) { 1183 ++NumSubFrameworkLookups; 1184 1185 // If the framework dir doesn't exist, we fail. 1186 auto Dir = FileMgr.getOptionalDirectoryRef(FrameworkName); 1187 if (!Dir) 1188 return None; 1189 1190 // Otherwise, if it does, remember that this is the right direntry for this 1191 // framework. 1192 CacheLookup.second.Directory = Dir; 1193 } 1194 1195 1196 if (RelativePath) { 1197 RelativePath->clear(); 1198 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end()); 1199 } 1200 1201 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h" 1202 SmallString<1024> HeadersFilename(FrameworkName); 1203 HeadersFilename += "Headers/"; 1204 if (SearchPath) { 1205 SearchPath->clear(); 1206 // Without trailing '/'. 1207 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1); 1208 } 1209 1210 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end()); 1211 auto File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true); 1212 if (!File) { 1213 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h" 1214 HeadersFilename = FrameworkName; 1215 HeadersFilename += "PrivateHeaders/"; 1216 if (SearchPath) { 1217 SearchPath->clear(); 1218 // Without trailing '/'. 1219 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1); 1220 } 1221 1222 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end()); 1223 File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true); 1224 1225 if (!File) 1226 return None; 1227 } 1228 1229 // This file is a system header or C++ unfriendly if the old file is. 1230 // 1231 // Note that the temporary 'DirInfo' is required here, as either call to 1232 // getFileInfo could resize the vector and we don't want to rely on order 1233 // of evaluation. 1234 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo; 1235 getFileInfo(&File->getFileEntry()).DirInfo = DirInfo; 1236 1237 FrameworkName.pop_back(); // remove the trailing '/' 1238 if (!findUsableModuleForFrameworkHeader(&File->getFileEntry(), FrameworkName, 1239 RequestingModule, SuggestedModule, 1240 /*IsSystem*/ false)) 1241 return None; 1242 1243 return *File; 1244 } 1245 1246 //===----------------------------------------------------------------------===// 1247 // File Info Management. 1248 //===----------------------------------------------------------------------===// 1249 1250 /// Merge the header file info provided by \p OtherHFI into the current 1251 /// header file info (\p HFI) 1252 static void mergeHeaderFileInfo(HeaderFileInfo &HFI, 1253 const HeaderFileInfo &OtherHFI) { 1254 assert(OtherHFI.External && "expected to merge external HFI"); 1255 1256 HFI.isImport |= OtherHFI.isImport; 1257 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce; 1258 HFI.isModuleHeader |= OtherHFI.isModuleHeader; 1259 1260 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) { 1261 HFI.ControllingMacro = OtherHFI.ControllingMacro; 1262 HFI.ControllingMacroID = OtherHFI.ControllingMacroID; 1263 } 1264 1265 HFI.DirInfo = OtherHFI.DirInfo; 1266 HFI.External = (!HFI.IsValid || HFI.External); 1267 HFI.IsValid = true; 1268 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader; 1269 1270 if (HFI.Framework.empty()) 1271 HFI.Framework = OtherHFI.Framework; 1272 } 1273 1274 /// getFileInfo - Return the HeaderFileInfo structure for the specified 1275 /// FileEntry. 1276 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) { 1277 if (FE->getUID() >= FileInfo.size()) 1278 FileInfo.resize(FE->getUID() + 1); 1279 1280 HeaderFileInfo *HFI = &FileInfo[FE->getUID()]; 1281 // FIXME: Use a generation count to check whether this is really up to date. 1282 if (ExternalSource && !HFI->Resolved) { 1283 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE); 1284 if (ExternalHFI.IsValid) { 1285 HFI->Resolved = true; 1286 if (ExternalHFI.External) 1287 mergeHeaderFileInfo(*HFI, ExternalHFI); 1288 } 1289 } 1290 1291 HFI->IsValid = true; 1292 // We have local information about this header file, so it's no longer 1293 // strictly external. 1294 HFI->External = false; 1295 return *HFI; 1296 } 1297 1298 const HeaderFileInfo * 1299 HeaderSearch::getExistingFileInfo(const FileEntry *FE, 1300 bool WantExternal) const { 1301 // If we have an external source, ensure we have the latest information. 1302 // FIXME: Use a generation count to check whether this is really up to date. 1303 HeaderFileInfo *HFI; 1304 if (ExternalSource) { 1305 if (FE->getUID() >= FileInfo.size()) { 1306 if (!WantExternal) 1307 return nullptr; 1308 FileInfo.resize(FE->getUID() + 1); 1309 } 1310 1311 HFI = &FileInfo[FE->getUID()]; 1312 if (!WantExternal && (!HFI->IsValid || HFI->External)) 1313 return nullptr; 1314 if (!HFI->Resolved) { 1315 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE); 1316 if (ExternalHFI.IsValid) { 1317 HFI->Resolved = true; 1318 if (ExternalHFI.External) 1319 mergeHeaderFileInfo(*HFI, ExternalHFI); 1320 } 1321 } 1322 } else if (FE->getUID() >= FileInfo.size()) { 1323 return nullptr; 1324 } else { 1325 HFI = &FileInfo[FE->getUID()]; 1326 } 1327 1328 if (!HFI->IsValid || (HFI->External && !WantExternal)) 1329 return nullptr; 1330 1331 return HFI; 1332 } 1333 1334 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) { 1335 // Check if we've entered this file and found an include guard or #pragma 1336 // once. Note that we dor't check for #import, because that's not a property 1337 // of the file itself. 1338 if (auto *HFI = getExistingFileInfo(File)) 1339 return HFI->isPragmaOnce || HFI->ControllingMacro || 1340 HFI->ControllingMacroID; 1341 return false; 1342 } 1343 1344 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE, 1345 ModuleMap::ModuleHeaderRole Role, 1346 bool isCompilingModuleHeader) { 1347 bool isModularHeader = !(Role & ModuleMap::TextualHeader); 1348 1349 // Don't mark the file info as non-external if there's nothing to change. 1350 if (!isCompilingModuleHeader) { 1351 if (!isModularHeader) 1352 return; 1353 auto *HFI = getExistingFileInfo(FE); 1354 if (HFI && HFI->isModuleHeader) 1355 return; 1356 } 1357 1358 auto &HFI = getFileInfo(FE); 1359 HFI.isModuleHeader |= isModularHeader; 1360 HFI.isCompilingModuleHeader |= isCompilingModuleHeader; 1361 } 1362 1363 bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP, 1364 const FileEntry *File, bool isImport, 1365 bool ModulesEnabled, Module *M, 1366 bool &IsFirstIncludeOfFile) { 1367 ++NumIncluded; // Count # of attempted #includes. 1368 1369 IsFirstIncludeOfFile = false; 1370 1371 // Get information about this file. 1372 HeaderFileInfo &FileInfo = getFileInfo(File); 1373 1374 // FIXME: this is a workaround for the lack of proper modules-aware support 1375 // for #import / #pragma once 1376 auto TryEnterImported = [&]() -> bool { 1377 if (!ModulesEnabled) 1378 return false; 1379 // Ensure FileInfo bits are up to date. 1380 ModMap.resolveHeaderDirectives(File); 1381 // Modules with builtins are special; multiple modules use builtins as 1382 // modular headers, example: 1383 // 1384 // module stddef { header "stddef.h" export * } 1385 // 1386 // After module map parsing, this expands to: 1387 // 1388 // module stddef { 1389 // header "/path_to_builtin_dirs/stddef.h" 1390 // textual "stddef.h" 1391 // } 1392 // 1393 // It's common that libc++ and system modules will both define such 1394 // submodules. Make sure cached results for a builtin header won't 1395 // prevent other builtin modules from potentially entering the builtin 1396 // header. Note that builtins are header guarded and the decision to 1397 // actually enter them is postponed to the controlling macros logic below. 1398 bool TryEnterHdr = false; 1399 if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader) 1400 TryEnterHdr = ModMap.isBuiltinHeader(File); 1401 1402 // Textual headers can be #imported from different modules. Since ObjC 1403 // headers find in the wild might rely only on #import and do not contain 1404 // controlling macros, be conservative and only try to enter textual headers 1405 // if such macro is present. 1406 if (!FileInfo.isModuleHeader && 1407 FileInfo.getControllingMacro(ExternalLookup)) 1408 TryEnterHdr = true; 1409 return TryEnterHdr; 1410 }; 1411 1412 // If this is a #import directive, check that we have not already imported 1413 // this header. 1414 if (isImport) { 1415 // If this has already been imported, don't import it again. 1416 FileInfo.isImport = true; 1417 1418 // Has this already been #import'ed or #include'd? 1419 if (PP.alreadyIncluded(File) && !TryEnterImported()) 1420 return false; 1421 } else { 1422 // Otherwise, if this is a #include of a file that was previously #import'd 1423 // or if this is the second #include of a #pragma once file, ignore it. 1424 if ((FileInfo.isPragmaOnce || FileInfo.isImport) && !TryEnterImported()) 1425 return false; 1426 } 1427 1428 // Next, check to see if the file is wrapped with #ifndef guards. If so, and 1429 // if the macro that guards it is defined, we know the #include has no effect. 1430 if (const IdentifierInfo *ControllingMacro 1431 = FileInfo.getControllingMacro(ExternalLookup)) { 1432 // If the header corresponds to a module, check whether the macro is already 1433 // defined in that module rather than checking in the current set of visible 1434 // modules. 1435 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M) 1436 : PP.isMacroDefined(ControllingMacro)) { 1437 ++NumMultiIncludeFileOptzn; 1438 return false; 1439 } 1440 } 1441 1442 IsFirstIncludeOfFile = PP.markIncluded(File); 1443 1444 return true; 1445 } 1446 1447 size_t HeaderSearch::getTotalMemory() const { 1448 return SearchDirs.capacity() 1449 + llvm::capacity_in_bytes(FileInfo) 1450 + llvm::capacity_in_bytes(HeaderMaps) 1451 + LookupFileCache.getAllocator().getTotalMemory() 1452 + FrameworkMap.getAllocator().getTotalMemory(); 1453 } 1454 1455 unsigned HeaderSearch::searchDirIdx(const DirectoryLookup &DL) const { 1456 return &DL - &*SearchDirs.begin(); 1457 } 1458 1459 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) { 1460 return FrameworkNames.insert(Framework).first->first(); 1461 } 1462 1463 bool HeaderSearch::hasModuleMap(StringRef FileName, 1464 const DirectoryEntry *Root, 1465 bool IsSystem) { 1466 if (!HSOpts->ImplicitModuleMaps) 1467 return false; 1468 1469 SmallVector<const DirectoryEntry *, 2> FixUpDirectories; 1470 1471 StringRef DirName = FileName; 1472 do { 1473 // Get the parent directory name. 1474 DirName = llvm::sys::path::parent_path(DirName); 1475 if (DirName.empty()) 1476 return false; 1477 1478 // Determine whether this directory exists. 1479 auto Dir = FileMgr.getDirectory(DirName); 1480 if (!Dir) 1481 return false; 1482 1483 // Try to load the module map file in this directory. 1484 switch (loadModuleMapFile(*Dir, IsSystem, 1485 llvm::sys::path::extension((*Dir)->getName()) == 1486 ".framework")) { 1487 case LMM_NewlyLoaded: 1488 case LMM_AlreadyLoaded: 1489 // Success. All of the directories we stepped through inherit this module 1490 // map file. 1491 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I) 1492 DirectoryHasModuleMap[FixUpDirectories[I]] = true; 1493 return true; 1494 1495 case LMM_NoDirectory: 1496 case LMM_InvalidModuleMap: 1497 break; 1498 } 1499 1500 // If we hit the top of our search, we're done. 1501 if (*Dir == Root) 1502 return false; 1503 1504 // Keep track of all of the directories we checked, so we can mark them as 1505 // having module maps if we eventually do find a module map. 1506 FixUpDirectories.push_back(*Dir); 1507 } while (true); 1508 } 1509 1510 ModuleMap::KnownHeader 1511 HeaderSearch::findModuleForHeader(const FileEntry *File, 1512 bool AllowTextual) const { 1513 if (ExternalSource) { 1514 // Make sure the external source has handled header info about this file, 1515 // which includes whether the file is part of a module. 1516 (void)getExistingFileInfo(File); 1517 } 1518 return ModMap.findModuleForHeader(File, AllowTextual); 1519 } 1520 1521 ArrayRef<ModuleMap::KnownHeader> 1522 HeaderSearch::findAllModulesForHeader(const FileEntry *File) const { 1523 if (ExternalSource) { 1524 // Make sure the external source has handled header info about this file, 1525 // which includes whether the file is part of a module. 1526 (void)getExistingFileInfo(File); 1527 } 1528 return ModMap.findAllModulesForHeader(File); 1529 } 1530 1531 static bool suggestModule(HeaderSearch &HS, const FileEntry *File, 1532 Module *RequestingModule, 1533 ModuleMap::KnownHeader *SuggestedModule) { 1534 ModuleMap::KnownHeader Module = 1535 HS.findModuleForHeader(File, /*AllowTextual*/true); 1536 1537 // If this module specifies [no_undeclared_includes], we cannot find any 1538 // file that's in a non-dependency module. 1539 if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) { 1540 HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/ false); 1541 if (!RequestingModule->directlyUses(Module.getModule())) { 1542 // Builtin headers are a special case. Multiple modules can use the same 1543 // builtin as a modular header (see also comment in 1544 // ShouldEnterIncludeFile()), so the builtin header may have been 1545 // "claimed" by an unrelated module. This shouldn't prevent us from 1546 // including the builtin header textually in this module. 1547 if (HS.getModuleMap().isBuiltinHeader(File)) { 1548 if (SuggestedModule) 1549 *SuggestedModule = ModuleMap::KnownHeader(); 1550 return true; 1551 } 1552 return false; 1553 } 1554 } 1555 1556 if (SuggestedModule) 1557 *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader) 1558 ? ModuleMap::KnownHeader() 1559 : Module; 1560 1561 return true; 1562 } 1563 1564 bool HeaderSearch::findUsableModuleForHeader( 1565 const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule, 1566 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) { 1567 if (File && needModuleLookup(RequestingModule, SuggestedModule)) { 1568 // If there is a module that corresponds to this header, suggest it. 1569 hasModuleMap(File->getName(), Root, IsSystemHeaderDir); 1570 return suggestModule(*this, File, RequestingModule, SuggestedModule); 1571 } 1572 return true; 1573 } 1574 1575 bool HeaderSearch::findUsableModuleForFrameworkHeader( 1576 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule, 1577 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) { 1578 // If we're supposed to suggest a module, look for one now. 1579 if (needModuleLookup(RequestingModule, SuggestedModule)) { 1580 // Find the top-level framework based on this framework. 1581 SmallVector<std::string, 4> SubmodulePath; 1582 const DirectoryEntry *TopFrameworkDir 1583 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath); 1584 1585 // Determine the name of the top-level framework. 1586 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName()); 1587 1588 // Load this framework module. If that succeeds, find the suggested module 1589 // for this header, if any. 1590 loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework); 1591 1592 // FIXME: This can find a module not part of ModuleName, which is 1593 // important so that we're consistent about whether this header 1594 // corresponds to a module. Possibly we should lock down framework modules 1595 // so that this is not possible. 1596 return suggestModule(*this, File, RequestingModule, SuggestedModule); 1597 } 1598 return true; 1599 } 1600 1601 static const FileEntry *getPrivateModuleMap(const FileEntry *File, 1602 FileManager &FileMgr) { 1603 StringRef Filename = llvm::sys::path::filename(File->getName()); 1604 SmallString<128> PrivateFilename(File->getDir()->getName()); 1605 if (Filename == "module.map") 1606 llvm::sys::path::append(PrivateFilename, "module_private.map"); 1607 else if (Filename == "module.modulemap") 1608 llvm::sys::path::append(PrivateFilename, "module.private.modulemap"); 1609 else 1610 return nullptr; 1611 if (auto File = FileMgr.getFile(PrivateFilename)) 1612 return *File; 1613 return nullptr; 1614 } 1615 1616 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem, 1617 FileID ID, unsigned *Offset, 1618 StringRef OriginalModuleMapFile) { 1619 // Find the directory for the module. For frameworks, that may require going 1620 // up from the 'Modules' directory. 1621 const DirectoryEntry *Dir = nullptr; 1622 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) { 1623 if (auto DirOrErr = FileMgr.getDirectory(".")) 1624 Dir = *DirOrErr; 1625 } else { 1626 if (!OriginalModuleMapFile.empty()) { 1627 // We're building a preprocessed module map. Find or invent the directory 1628 // that it originally occupied. 1629 auto DirOrErr = FileMgr.getDirectory( 1630 llvm::sys::path::parent_path(OriginalModuleMapFile)); 1631 if (DirOrErr) { 1632 Dir = *DirOrErr; 1633 } else { 1634 auto *FakeFile = FileMgr.getVirtualFile(OriginalModuleMapFile, 0, 0); 1635 Dir = FakeFile->getDir(); 1636 } 1637 } else { 1638 Dir = File->getDir(); 1639 } 1640 1641 StringRef DirName(Dir->getName()); 1642 if (llvm::sys::path::filename(DirName) == "Modules") { 1643 DirName = llvm::sys::path::parent_path(DirName); 1644 if (DirName.endswith(".framework")) 1645 if (auto DirOrErr = FileMgr.getDirectory(DirName)) 1646 Dir = *DirOrErr; 1647 // FIXME: This assert can fail if there's a race between the above check 1648 // and the removal of the directory. 1649 assert(Dir && "parent must exist"); 1650 } 1651 } 1652 1653 switch (loadModuleMapFileImpl(File, IsSystem, Dir, ID, Offset)) { 1654 case LMM_AlreadyLoaded: 1655 case LMM_NewlyLoaded: 1656 return false; 1657 case LMM_NoDirectory: 1658 case LMM_InvalidModuleMap: 1659 return true; 1660 } 1661 llvm_unreachable("Unknown load module map result"); 1662 } 1663 1664 HeaderSearch::LoadModuleMapResult 1665 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem, 1666 const DirectoryEntry *Dir, FileID ID, 1667 unsigned *Offset) { 1668 assert(File && "expected FileEntry"); 1669 1670 // Check whether we've already loaded this module map, and mark it as being 1671 // loaded in case we recursively try to load it from itself. 1672 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true)); 1673 if (!AddResult.second) 1674 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap; 1675 1676 if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) { 1677 LoadedModuleMaps[File] = false; 1678 return LMM_InvalidModuleMap; 1679 } 1680 1681 // Try to load a corresponding private module map. 1682 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) { 1683 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) { 1684 LoadedModuleMaps[File] = false; 1685 return LMM_InvalidModuleMap; 1686 } 1687 } 1688 1689 // This directory has a module map. 1690 return LMM_NewlyLoaded; 1691 } 1692 1693 const FileEntry * 1694 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) { 1695 if (!HSOpts->ImplicitModuleMaps) 1696 return nullptr; 1697 // For frameworks, the preferred spelling is Modules/module.modulemap, but 1698 // module.map at the framework root is also accepted. 1699 SmallString<128> ModuleMapFileName(Dir->getName()); 1700 if (IsFramework) 1701 llvm::sys::path::append(ModuleMapFileName, "Modules"); 1702 llvm::sys::path::append(ModuleMapFileName, "module.modulemap"); 1703 if (auto F = FileMgr.getFile(ModuleMapFileName)) 1704 return *F; 1705 1706 // Continue to allow module.map 1707 ModuleMapFileName = Dir->getName(); 1708 llvm::sys::path::append(ModuleMapFileName, "module.map"); 1709 if (auto F = FileMgr.getFile(ModuleMapFileName)) 1710 return *F; 1711 1712 // For frameworks, allow to have a private module map with a preferred 1713 // spelling when a public module map is absent. 1714 if (IsFramework) { 1715 ModuleMapFileName = Dir->getName(); 1716 llvm::sys::path::append(ModuleMapFileName, "Modules", 1717 "module.private.modulemap"); 1718 if (auto F = FileMgr.getFile(ModuleMapFileName)) 1719 return *F; 1720 } 1721 return nullptr; 1722 } 1723 1724 Module *HeaderSearch::loadFrameworkModule(StringRef Name, 1725 const DirectoryEntry *Dir, 1726 bool IsSystem) { 1727 if (Module *Module = ModMap.findModule(Name)) 1728 return Module; 1729 1730 // Try to load a module map file. 1731 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) { 1732 case LMM_InvalidModuleMap: 1733 // Try to infer a module map from the framework directory. 1734 if (HSOpts->ImplicitModuleMaps) 1735 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr); 1736 break; 1737 1738 case LMM_AlreadyLoaded: 1739 case LMM_NoDirectory: 1740 return nullptr; 1741 1742 case LMM_NewlyLoaded: 1743 break; 1744 } 1745 1746 return ModMap.findModule(Name); 1747 } 1748 1749 HeaderSearch::LoadModuleMapResult 1750 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem, 1751 bool IsFramework) { 1752 if (auto Dir = FileMgr.getDirectory(DirName)) 1753 return loadModuleMapFile(*Dir, IsSystem, IsFramework); 1754 1755 return LMM_NoDirectory; 1756 } 1757 1758 HeaderSearch::LoadModuleMapResult 1759 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem, 1760 bool IsFramework) { 1761 auto KnownDir = DirectoryHasModuleMap.find(Dir); 1762 if (KnownDir != DirectoryHasModuleMap.end()) 1763 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap; 1764 1765 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) { 1766 LoadModuleMapResult Result = 1767 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir); 1768 // Add Dir explicitly in case ModuleMapFile is in a subdirectory. 1769 // E.g. Foo.framework/Modules/module.modulemap 1770 // ^Dir ^ModuleMapFile 1771 if (Result == LMM_NewlyLoaded) 1772 DirectoryHasModuleMap[Dir] = true; 1773 else if (Result == LMM_InvalidModuleMap) 1774 DirectoryHasModuleMap[Dir] = false; 1775 return Result; 1776 } 1777 return LMM_InvalidModuleMap; 1778 } 1779 1780 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) { 1781 Modules.clear(); 1782 1783 if (HSOpts->ImplicitModuleMaps) { 1784 // Load module maps for each of the header search directories. 1785 for (DirectoryLookup &DL : search_dir_range()) { 1786 bool IsSystem = DL.isSystemHeaderDirectory(); 1787 if (DL.isFramework()) { 1788 std::error_code EC; 1789 SmallString<128> DirNative; 1790 llvm::sys::path::native(DL.getFrameworkDir()->getName(), DirNative); 1791 1792 // Search each of the ".framework" directories to load them as modules. 1793 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem(); 1794 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), 1795 DirEnd; 1796 Dir != DirEnd && !EC; Dir.increment(EC)) { 1797 if (llvm::sys::path::extension(Dir->path()) != ".framework") 1798 continue; 1799 1800 auto FrameworkDir = 1801 FileMgr.getDirectory(Dir->path()); 1802 if (!FrameworkDir) 1803 continue; 1804 1805 // Load this framework module. 1806 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir, 1807 IsSystem); 1808 } 1809 continue; 1810 } 1811 1812 // FIXME: Deal with header maps. 1813 if (DL.isHeaderMap()) 1814 continue; 1815 1816 // Try to load a module map file for the search directory. 1817 loadModuleMapFile(DL.getDir(), IsSystem, /*IsFramework*/ false); 1818 1819 // Try to load module map files for immediate subdirectories of this 1820 // search directory. 1821 loadSubdirectoryModuleMaps(DL); 1822 } 1823 } 1824 1825 // Populate the list of modules. 1826 llvm::transform(ModMap.modules(), std::back_inserter(Modules), 1827 [](const auto &NameAndMod) { return NameAndMod.second; }); 1828 } 1829 1830 void HeaderSearch::loadTopLevelSystemModules() { 1831 if (!HSOpts->ImplicitModuleMaps) 1832 return; 1833 1834 // Load module maps for each of the header search directories. 1835 for (const DirectoryLookup &DL : search_dir_range()) { 1836 // We only care about normal header directories. 1837 if (!DL.isNormalDir()) 1838 continue; 1839 1840 // Try to load a module map file for the search directory. 1841 loadModuleMapFile(DL.getDir(), DL.isSystemHeaderDirectory(), 1842 DL.isFramework()); 1843 } 1844 } 1845 1846 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) { 1847 assert(HSOpts->ImplicitModuleMaps && 1848 "Should not be loading subdirectory module maps"); 1849 1850 if (SearchDir.haveSearchedAllModuleMaps()) 1851 return; 1852 1853 std::error_code EC; 1854 SmallString<128> Dir = SearchDir.getDir()->getName(); 1855 FileMgr.makeAbsolutePath(Dir); 1856 SmallString<128> DirNative; 1857 llvm::sys::path::native(Dir, DirNative); 1858 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem(); 1859 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; 1860 Dir != DirEnd && !EC; Dir.increment(EC)) { 1861 bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework"; 1862 if (IsFramework == SearchDir.isFramework()) 1863 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(), 1864 SearchDir.isFramework()); 1865 } 1866 1867 SearchDir.setSearchedAllModuleMaps(true); 1868 } 1869 1870 std::string HeaderSearch::suggestPathToFileForDiagnostics( 1871 const FileEntry *File, llvm::StringRef MainFile, bool *IsSystem) { 1872 // FIXME: We assume that the path name currently cached in the FileEntry is 1873 // the most appropriate one for this analysis (and that it's spelled the 1874 // same way as the corresponding header search path). 1875 return suggestPathToFileForDiagnostics(File->getName(), /*WorkingDir=*/"", 1876 MainFile, IsSystem); 1877 } 1878 1879 std::string HeaderSearch::suggestPathToFileForDiagnostics( 1880 llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile, 1881 bool *IsSystem) { 1882 using namespace llvm::sys; 1883 1884 unsigned BestPrefixLength = 0; 1885 // Checks whether `Dir` is a strict path prefix of `File`. If so and that's 1886 // the longest prefix we've seen so for it, returns true and updates the 1887 // `BestPrefixLength` accordingly. 1888 auto CheckDir = [&](llvm::StringRef Dir) -> bool { 1889 llvm::SmallString<32> DirPath(Dir.begin(), Dir.end()); 1890 if (!WorkingDir.empty() && !path::is_absolute(Dir)) 1891 fs::make_absolute(WorkingDir, DirPath); 1892 path::remove_dots(DirPath, /*remove_dot_dot=*/true); 1893 Dir = DirPath; 1894 for (auto NI = path::begin(File), NE = path::end(File), 1895 DI = path::begin(Dir), DE = path::end(Dir); 1896 /*termination condition in loop*/; ++NI, ++DI) { 1897 // '.' components in File are ignored. 1898 while (NI != NE && *NI == ".") 1899 ++NI; 1900 if (NI == NE) 1901 break; 1902 1903 // '.' components in Dir are ignored. 1904 while (DI != DE && *DI == ".") 1905 ++DI; 1906 if (DI == DE) { 1907 // Dir is a prefix of File, up to '.' components and choice of path 1908 // separators. 1909 unsigned PrefixLength = NI - path::begin(File); 1910 if (PrefixLength > BestPrefixLength) { 1911 BestPrefixLength = PrefixLength; 1912 return true; 1913 } 1914 break; 1915 } 1916 1917 // Consider all path separators equal. 1918 if (NI->size() == 1 && DI->size() == 1 && 1919 path::is_separator(NI->front()) && path::is_separator(DI->front())) 1920 continue; 1921 1922 // Special case Apple .sdk folders since the search path is typically a 1923 // symlink like `iPhoneSimulator14.5.sdk` while the file is instead 1924 // located in `iPhoneSimulator.sdk` (the real folder). 1925 if (NI->endswith(".sdk") && DI->endswith(".sdk")) { 1926 StringRef NBasename = path::stem(*NI); 1927 StringRef DBasename = path::stem(*DI); 1928 if (DBasename.startswith(NBasename)) 1929 continue; 1930 } 1931 1932 if (*NI != *DI) 1933 break; 1934 } 1935 return false; 1936 }; 1937 1938 bool BestPrefixIsFramework = false; 1939 for (const DirectoryLookup &DL : search_dir_range()) { 1940 if (DL.isNormalDir()) { 1941 StringRef Dir = DL.getDir()->getName(); 1942 if (CheckDir(Dir)) { 1943 if (IsSystem) 1944 *IsSystem = BestPrefixLength && isSystem(DL.getDirCharacteristic()); 1945 BestPrefixIsFramework = false; 1946 } 1947 } else if (DL.isFramework()) { 1948 StringRef Dir = DL.getFrameworkDir()->getName(); 1949 if (CheckDir(Dir)) { 1950 if (IsSystem) 1951 *IsSystem = BestPrefixLength && isSystem(DL.getDirCharacteristic()); 1952 BestPrefixIsFramework = true; 1953 } 1954 } 1955 } 1956 1957 // Try to shorten include path using TUs directory, if we couldn't find any 1958 // suitable prefix in include search paths. 1959 if (!BestPrefixLength && CheckDir(path::parent_path(MainFile))) { 1960 if (IsSystem) 1961 *IsSystem = false; 1962 BestPrefixIsFramework = false; 1963 } 1964 1965 // Try resolving resulting filename via reverse search in header maps, 1966 // key from header name is user prefered name for the include file. 1967 StringRef Filename = File.drop_front(BestPrefixLength); 1968 for (const DirectoryLookup &DL : search_dir_range()) { 1969 if (!DL.isHeaderMap()) 1970 continue; 1971 1972 StringRef SpelledFilename = 1973 DL.getHeaderMap()->reverseLookupFilename(Filename); 1974 if (!SpelledFilename.empty()) { 1975 Filename = SpelledFilename; 1976 BestPrefixIsFramework = false; 1977 break; 1978 } 1979 } 1980 1981 // If the best prefix is a framework path, we need to compute the proper 1982 // include spelling for the framework header. 1983 bool IsPrivateHeader; 1984 SmallString<128> FrameworkName, IncludeSpelling; 1985 if (BestPrefixIsFramework && 1986 isFrameworkStylePath(Filename, IsPrivateHeader, FrameworkName, 1987 IncludeSpelling)) { 1988 Filename = IncludeSpelling; 1989 } 1990 return path::convert_to_slash(Filename); 1991 } 1992