1 //===--- HeaderSearch.cpp - Resolve Header File Locations ---===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the DirectoryLookup and HeaderSearch interfaces. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Lex/HeaderSearch.h" 15 #include "clang/Basic/FileManager.h" 16 #include "clang/Basic/IdentifierTable.h" 17 #include "clang/Lex/ExternalPreprocessorSource.h" 18 #include "clang/Lex/HeaderMap.h" 19 #include "clang/Lex/HeaderSearchOptions.h" 20 #include "clang/Lex/LexDiagnostic.h" 21 #include "clang/Lex/Lexer.h" 22 #include "clang/Lex/Preprocessor.h" 23 #include "llvm/ADT/APInt.h" 24 #include "llvm/ADT/Hashing.h" 25 #include "llvm/ADT/SmallString.h" 26 #include "llvm/Support/Capacity.h" 27 #include "llvm/Support/FileSystem.h" 28 #include "llvm/Support/Path.h" 29 #include "llvm/Support/raw_ostream.h" 30 #include <cstdio> 31 #if defined(LLVM_ON_UNIX) 32 #include <limits.h> 33 #endif 34 using namespace clang; 35 36 const IdentifierInfo * 37 HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) { 38 if (ControllingMacro) { 39 if (ControllingMacro->isOutOfDate()) 40 External->updateOutOfDateIdentifier( 41 *const_cast<IdentifierInfo *>(ControllingMacro)); 42 return ControllingMacro; 43 } 44 45 if (!ControllingMacroID || !External) 46 return nullptr; 47 48 ControllingMacro = External->GetIdentifier(ControllingMacroID); 49 return ControllingMacro; 50 } 51 52 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {} 53 54 HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts, 55 SourceManager &SourceMgr, DiagnosticsEngine &Diags, 56 const LangOptions &LangOpts, 57 const TargetInfo *Target) 58 : HSOpts(HSOpts), Diags(Diags), FileMgr(SourceMgr.getFileManager()), 59 FrameworkMap(64), ModMap(SourceMgr, Diags, LangOpts, Target, *this), 60 LangOpts(LangOpts) { 61 AngledDirIdx = 0; 62 SystemDirIdx = 0; 63 NoCurDirSearch = false; 64 65 ExternalLookup = nullptr; 66 ExternalSource = nullptr; 67 NumIncluded = 0; 68 NumMultiIncludeFileOptzn = 0; 69 NumFrameworkLookups = NumSubFrameworkLookups = 0; 70 } 71 72 HeaderSearch::~HeaderSearch() { 73 // Delete headermaps. 74 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i) 75 delete HeaderMaps[i].second; 76 } 77 78 void HeaderSearch::PrintStats() { 79 fprintf(stderr, "\n*** HeaderSearch Stats:\n"); 80 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size()); 81 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0; 82 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) { 83 NumOnceOnlyFiles += FileInfo[i].isImport; 84 if (MaxNumIncludes < FileInfo[i].NumIncludes) 85 MaxNumIncludes = FileInfo[i].NumIncludes; 86 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1; 87 } 88 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles); 89 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles); 90 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes); 91 92 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded); 93 fprintf(stderr, " %d #includes skipped due to" 94 " the multi-include optimization.\n", NumMultiIncludeFileOptzn); 95 96 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups); 97 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups); 98 } 99 100 /// CreateHeaderMap - This method returns a HeaderMap for the specified 101 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure. 102 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) { 103 // We expect the number of headermaps to be small, and almost always empty. 104 // If it ever grows, use of a linear search should be re-evaluated. 105 if (!HeaderMaps.empty()) { 106 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i) 107 // Pointer equality comparison of FileEntries works because they are 108 // already uniqued by inode. 109 if (HeaderMaps[i].first == FE) 110 return HeaderMaps[i].second; 111 } 112 113 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) { 114 HeaderMaps.push_back(std::make_pair(FE, HM)); 115 return HM; 116 } 117 118 return nullptr; 119 } 120 121 std::string HeaderSearch::getModuleFileName(Module *Module) { 122 const FileEntry *ModuleMap = 123 getModuleMap().getModuleMapFileForUniquing(Module); 124 return getModuleFileName(Module->Name, ModuleMap->getName()); 125 } 126 127 std::string HeaderSearch::getModuleFileName(StringRef ModuleName, 128 StringRef ModuleMapPath) { 129 // If we don't have a module cache path, we can't do anything. 130 if (ModuleCachePath.empty()) 131 return std::string(); 132 133 SmallString<256> Result(ModuleCachePath); 134 llvm::sys::fs::make_absolute(Result); 135 136 if (HSOpts->DisableModuleHash) { 137 llvm::sys::path::append(Result, ModuleName + ".pcm"); 138 } else { 139 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should 140 // ideally be globally unique to this particular module. Name collisions 141 // in the hash are safe (because any translation unit can only import one 142 // module with each name), but result in a loss of caching. 143 // 144 // To avoid false-negatives, we form as canonical a path as we can, and map 145 // to lower-case in case we're on a case-insensitive file system. 146 auto *Dir = 147 FileMgr.getDirectory(llvm::sys::path::parent_path(ModuleMapPath)); 148 if (!Dir) 149 return std::string(); 150 auto DirName = FileMgr.getCanonicalName(Dir); 151 auto FileName = llvm::sys::path::filename(ModuleMapPath); 152 153 llvm::hash_code Hash = 154 llvm::hash_combine(DirName.lower(), FileName.lower()); 155 156 SmallString<128> HashStr; 157 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36); 158 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm"); 159 } 160 return Result.str().str(); 161 } 162 163 Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) { 164 // Look in the module map to determine if there is a module by this name. 165 Module *Module = ModMap.findModule(ModuleName); 166 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps) 167 return Module; 168 169 // Look through the various header search paths to load any available module 170 // maps, searching for a module map that describes this module. 171 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) { 172 if (SearchDirs[Idx].isFramework()) { 173 // Search for or infer a module map for a framework. 174 SmallString<128> FrameworkDirName; 175 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName(); 176 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework"); 177 if (const DirectoryEntry *FrameworkDir 178 = FileMgr.getDirectory(FrameworkDirName)) { 179 bool IsSystem 180 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User; 181 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem); 182 if (Module) 183 break; 184 } 185 } 186 187 // FIXME: Figure out how header maps and module maps will work together. 188 189 // Only deal with normal search directories. 190 if (!SearchDirs[Idx].isNormalDir()) 191 continue; 192 193 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory(); 194 // Search for a module map file in this directory. 195 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem, 196 /*IsFramework*/false) == LMM_NewlyLoaded) { 197 // We just loaded a module map file; check whether the module is 198 // available now. 199 Module = ModMap.findModule(ModuleName); 200 if (Module) 201 break; 202 } 203 204 // Search for a module map in a subdirectory with the same name as the 205 // module. 206 SmallString<128> NestedModuleMapDirName; 207 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName(); 208 llvm::sys::path::append(NestedModuleMapDirName, ModuleName); 209 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem, 210 /*IsFramework*/false) == LMM_NewlyLoaded){ 211 // If we just loaded a module map file, look for the module again. 212 Module = ModMap.findModule(ModuleName); 213 if (Module) 214 break; 215 } 216 217 // If we've already performed the exhaustive search for module maps in this 218 // search directory, don't do it again. 219 if (SearchDirs[Idx].haveSearchedAllModuleMaps()) 220 continue; 221 222 // Load all module maps in the immediate subdirectories of this search 223 // directory. 224 loadSubdirectoryModuleMaps(SearchDirs[Idx]); 225 226 // Look again for the module. 227 Module = ModMap.findModule(ModuleName); 228 if (Module) 229 break; 230 } 231 232 return Module; 233 } 234 235 //===----------------------------------------------------------------------===// 236 // File lookup within a DirectoryLookup scope 237 //===----------------------------------------------------------------------===// 238 239 /// getName - Return the directory or filename corresponding to this lookup 240 /// object. 241 const char *DirectoryLookup::getName() const { 242 if (isNormalDir()) 243 return getDir()->getName(); 244 if (isFramework()) 245 return getFrameworkDir()->getName(); 246 assert(isHeaderMap() && "Unknown DirectoryLookup"); 247 return getHeaderMap()->getFileName(); 248 } 249 250 static const FileEntry * 251 getFileAndSuggestModule(HeaderSearch &HS, StringRef FileName, 252 const DirectoryEntry *Dir, bool IsSystemHeaderDir, 253 ModuleMap::KnownHeader *SuggestedModule) { 254 // If we have a module map that might map this header, load it and 255 // check whether we'll have a suggestion for a module. 256 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir); 257 if (SuggestedModule) { 258 const FileEntry *File = HS.getFileMgr().getFile(FileName, 259 /*OpenFile=*/false); 260 if (File) { 261 // If there is a module that corresponds to this header, suggest it. 262 *SuggestedModule = HS.findModuleForHeader(File); 263 264 // FIXME: This appears to be a no-op. We loaded the module map for this 265 // directory at the start of this function. 266 if (!SuggestedModule->getModule() && 267 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir)) 268 *SuggestedModule = HS.findModuleForHeader(File); 269 } 270 271 return File; 272 } 273 274 return HS.getFileMgr().getFile(FileName, /*openFile=*/true); 275 } 276 277 /// LookupFile - Lookup the specified file in this search path, returning it 278 /// if it exists or returning null if not. 279 const FileEntry *DirectoryLookup::LookupFile( 280 StringRef &Filename, 281 HeaderSearch &HS, 282 SmallVectorImpl<char> *SearchPath, 283 SmallVectorImpl<char> *RelativePath, 284 ModuleMap::KnownHeader *SuggestedModule, 285 bool &InUserSpecifiedSystemFramework, 286 bool &HasBeenMapped, 287 SmallVectorImpl<char> &MappedName) const { 288 InUserSpecifiedSystemFramework = false; 289 HasBeenMapped = false; 290 291 SmallString<1024> TmpDir; 292 if (isNormalDir()) { 293 // Concatenate the requested file onto the directory. 294 TmpDir = getDir()->getName(); 295 llvm::sys::path::append(TmpDir, Filename); 296 if (SearchPath) { 297 StringRef SearchPathRef(getDir()->getName()); 298 SearchPath->clear(); 299 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); 300 } 301 if (RelativePath) { 302 RelativePath->clear(); 303 RelativePath->append(Filename.begin(), Filename.end()); 304 } 305 306 return getFileAndSuggestModule(HS, TmpDir, getDir(), 307 isSystemHeaderDirectory(), 308 SuggestedModule); 309 } 310 311 if (isFramework()) 312 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath, 313 SuggestedModule, InUserSpecifiedSystemFramework); 314 315 assert(isHeaderMap() && "Unknown directory lookup"); 316 const HeaderMap *HM = getHeaderMap(); 317 SmallString<1024> Path; 318 StringRef Dest = HM->lookupFilename(Filename, Path); 319 if (Dest.empty()) 320 return nullptr; 321 322 const FileEntry *Result; 323 324 // Check if the headermap maps the filename to a framework include 325 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the 326 // framework include. 327 if (llvm::sys::path::is_relative(Dest)) { 328 MappedName.clear(); 329 MappedName.append(Dest.begin(), Dest.end()); 330 Filename = StringRef(MappedName.begin(), MappedName.size()); 331 HasBeenMapped = true; 332 Result = HM->LookupFile(Filename, HS.getFileMgr()); 333 334 } else { 335 Result = HS.getFileMgr().getFile(Dest); 336 } 337 338 if (Result) { 339 if (SearchPath) { 340 StringRef SearchPathRef(getName()); 341 SearchPath->clear(); 342 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); 343 } 344 if (RelativePath) { 345 RelativePath->clear(); 346 RelativePath->append(Filename.begin(), Filename.end()); 347 } 348 } 349 return Result; 350 } 351 352 /// \brief Given a framework directory, find the top-most framework directory. 353 /// 354 /// \param FileMgr The file manager to use for directory lookups. 355 /// \param DirName The name of the framework directory. 356 /// \param SubmodulePath Will be populated with the submodule path from the 357 /// returned top-level module to the originally named framework. 358 static const DirectoryEntry * 359 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName, 360 SmallVectorImpl<std::string> &SubmodulePath) { 361 assert(llvm::sys::path::extension(DirName) == ".framework" && 362 "Not a framework directory"); 363 364 // Note: as an egregious but useful hack we use the real path here, because 365 // frameworks moving between top-level frameworks to embedded frameworks tend 366 // to be symlinked, and we base the logical structure of modules on the 367 // physical layout. In particular, we need to deal with crazy includes like 368 // 369 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h> 370 // 371 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework 372 // which one should access with, e.g., 373 // 374 // #include <Bar/Wibble.h> 375 // 376 // Similar issues occur when a top-level framework has moved into an 377 // embedded framework. 378 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName); 379 DirName = FileMgr.getCanonicalName(TopFrameworkDir); 380 do { 381 // Get the parent directory name. 382 DirName = llvm::sys::path::parent_path(DirName); 383 if (DirName.empty()) 384 break; 385 386 // Determine whether this directory exists. 387 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName); 388 if (!Dir) 389 break; 390 391 // If this is a framework directory, then we're a subframework of this 392 // framework. 393 if (llvm::sys::path::extension(DirName) == ".framework") { 394 SubmodulePath.push_back(llvm::sys::path::stem(DirName)); 395 TopFrameworkDir = Dir; 396 } 397 } while (true); 398 399 return TopFrameworkDir; 400 } 401 402 /// DoFrameworkLookup - Do a lookup of the specified file in the current 403 /// DirectoryLookup, which is a framework directory. 404 const FileEntry *DirectoryLookup::DoFrameworkLookup( 405 StringRef Filename, 406 HeaderSearch &HS, 407 SmallVectorImpl<char> *SearchPath, 408 SmallVectorImpl<char> *RelativePath, 409 ModuleMap::KnownHeader *SuggestedModule, 410 bool &InUserSpecifiedSystemFramework) const 411 { 412 FileManager &FileMgr = HS.getFileMgr(); 413 414 // Framework names must have a '/' in the filename. 415 size_t SlashPos = Filename.find('/'); 416 if (SlashPos == StringRef::npos) return nullptr; 417 418 // Find out if this is the home for the specified framework, by checking 419 // HeaderSearch. Possible answers are yes/no and unknown. 420 HeaderSearch::FrameworkCacheEntry &CacheEntry = 421 HS.LookupFrameworkCache(Filename.substr(0, SlashPos)); 422 423 // If it is known and in some other directory, fail. 424 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir()) 425 return nullptr; 426 427 // Otherwise, construct the path to this framework dir. 428 429 // FrameworkName = "/System/Library/Frameworks/" 430 SmallString<1024> FrameworkName; 431 FrameworkName += getFrameworkDir()->getName(); 432 if (FrameworkName.empty() || FrameworkName.back() != '/') 433 FrameworkName.push_back('/'); 434 435 // FrameworkName = "/System/Library/Frameworks/Cocoa" 436 StringRef ModuleName(Filename.begin(), SlashPos); 437 FrameworkName += ModuleName; 438 439 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/" 440 FrameworkName += ".framework/"; 441 442 // If the cache entry was unresolved, populate it now. 443 if (!CacheEntry.Directory) { 444 HS.IncrementFrameworkLookupCount(); 445 446 // If the framework dir doesn't exist, we fail. 447 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName); 448 if (!Dir) return nullptr; 449 450 // Otherwise, if it does, remember that this is the right direntry for this 451 // framework. 452 CacheEntry.Directory = getFrameworkDir(); 453 454 // If this is a user search directory, check if the framework has been 455 // user-specified as a system framework. 456 if (getDirCharacteristic() == SrcMgr::C_User) { 457 SmallString<1024> SystemFrameworkMarker(FrameworkName); 458 SystemFrameworkMarker += ".system_framework"; 459 if (llvm::sys::fs::exists(SystemFrameworkMarker)) { 460 CacheEntry.IsUserSpecifiedSystemFramework = true; 461 } 462 } 463 } 464 465 // Set the 'user-specified system framework' flag. 466 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework; 467 468 if (RelativePath) { 469 RelativePath->clear(); 470 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end()); 471 } 472 473 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h" 474 unsigned OrigSize = FrameworkName.size(); 475 476 FrameworkName += "Headers/"; 477 478 if (SearchPath) { 479 SearchPath->clear(); 480 // Without trailing '/'. 481 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1); 482 } 483 484 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end()); 485 const FileEntry *FE = FileMgr.getFile(FrameworkName, 486 /*openFile=*/!SuggestedModule); 487 if (!FE) { 488 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h" 489 const char *Private = "Private"; 490 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private, 491 Private+strlen(Private)); 492 if (SearchPath) 493 SearchPath->insert(SearchPath->begin()+OrigSize, Private, 494 Private+strlen(Private)); 495 496 FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule); 497 } 498 499 // If we found the header and are allowed to suggest a module, do so now. 500 if (FE && SuggestedModule) { 501 // Find the framework in which this header occurs. 502 StringRef FrameworkPath = FE->getDir()->getName(); 503 bool FoundFramework = false; 504 do { 505 // Determine whether this directory exists. 506 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath); 507 if (!Dir) 508 break; 509 510 // If this is a framework directory, then we're a subframework of this 511 // framework. 512 if (llvm::sys::path::extension(FrameworkPath) == ".framework") { 513 FoundFramework = true; 514 break; 515 } 516 517 // Get the parent directory name. 518 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath); 519 if (FrameworkPath.empty()) 520 break; 521 } while (true); 522 523 if (FoundFramework) { 524 // Find the top-level framework based on this framework. 525 SmallVector<std::string, 4> SubmodulePath; 526 const DirectoryEntry *TopFrameworkDir 527 = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath); 528 529 // Determine the name of the top-level framework. 530 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName()); 531 532 // Load this framework module. If that succeeds, find the suggested module 533 // for this header, if any. 534 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User; 535 HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem); 536 537 // FIXME: This can find a module not part of ModuleName, which is 538 // important so that we're consistent about whether this header 539 // corresponds to a module. Possibly we should lock down framework modules 540 // so that this is not possible. 541 *SuggestedModule = HS.findModuleForHeader(FE); 542 } else { 543 *SuggestedModule = HS.findModuleForHeader(FE); 544 } 545 } 546 return FE; 547 } 548 549 void HeaderSearch::setTarget(const TargetInfo &Target) { 550 ModMap.setTarget(Target); 551 } 552 553 554 //===----------------------------------------------------------------------===// 555 // Header File Location. 556 //===----------------------------------------------------------------------===// 557 558 /// \brief Return true with a diagnostic if the file that MSVC would have found 559 /// fails to match the one that Clang would have found with MSVC header search 560 /// disabled. 561 static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags, 562 const FileEntry *MSFE, const FileEntry *FE, 563 SourceLocation IncludeLoc) { 564 if (MSFE && FE != MSFE) { 565 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName(); 566 return true; 567 } 568 return false; 569 } 570 571 static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) { 572 assert(!Str.empty()); 573 char *CopyStr = Alloc.Allocate<char>(Str.size()+1); 574 std::copy(Str.begin(), Str.end(), CopyStr); 575 CopyStr[Str.size()] = '\0'; 576 return CopyStr; 577 } 578 579 /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file, 580 /// return null on failure. isAngled indicates whether the file reference is 581 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if 582 /// non-empty, indicates where the \#including file(s) are, in case a relative 583 /// search is needed. Microsoft mode will pass all \#including files. 584 const FileEntry *HeaderSearch::LookupFile( 585 StringRef Filename, SourceLocation IncludeLoc, bool isAngled, 586 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir, 587 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers, 588 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, 589 ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) { 590 if (SuggestedModule) 591 *SuggestedModule = ModuleMap::KnownHeader(); 592 593 // If 'Filename' is absolute, check to see if it exists and no searching. 594 if (llvm::sys::path::is_absolute(Filename)) { 595 CurDir = nullptr; 596 597 // If this was an #include_next "/absolute/file", fail. 598 if (FromDir) return nullptr; 599 600 if (SearchPath) 601 SearchPath->clear(); 602 if (RelativePath) { 603 RelativePath->clear(); 604 RelativePath->append(Filename.begin(), Filename.end()); 605 } 606 // Otherwise, just return the file. 607 const FileEntry *File = FileMgr.getFile(Filename, /*openFile=*/true); 608 if (File && SuggestedModule) { 609 // If there is a module that corresponds to this header, suggest it. 610 hasModuleMap(Filename, File->getDir(), /*SystemHeaderDir*/false); 611 *SuggestedModule = findModuleForHeader(File); 612 } 613 return File; 614 } 615 616 // This is the header that MSVC's header search would have found. 617 const FileEntry *MSFE = nullptr; 618 ModuleMap::KnownHeader MSSuggestedModule; 619 620 // Unless disabled, check to see if the file is in the #includer's 621 // directory. This cannot be based on CurDir, because each includer could be 622 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent 623 // include of "baz.h" should resolve to "whatever/foo/baz.h". 624 // This search is not done for <> headers. 625 if (!Includers.empty() && !isAngled && !NoCurDirSearch) { 626 SmallString<1024> TmpDir; 627 bool First = true; 628 for (const auto &IncluderAndDir : Includers) { 629 const FileEntry *Includer = IncluderAndDir.first; 630 631 // Concatenate the requested file onto the directory. 632 // FIXME: Portability. Filename concatenation should be in sys::Path. 633 TmpDir = IncluderAndDir.second->getName(); 634 TmpDir.push_back('/'); 635 TmpDir.append(Filename.begin(), Filename.end()); 636 637 // FIXME: We don't cache the result of getFileInfo across the call to 638 // getFileAndSuggestModule, because it's a reference to an element of 639 // a container that could be reallocated across this call. 640 // 641 // FIXME: If we have no includer, that means we're processing a #include 642 // from a module build. We should treat this as a system header if we're 643 // building a [system] module. 644 bool IncluderIsSystemHeader = 645 Includer && getFileInfo(Includer).DirInfo != SrcMgr::C_User; 646 if (const FileEntry *FE = getFileAndSuggestModule( 647 *this, TmpDir, IncluderAndDir.second, 648 IncluderIsSystemHeader, SuggestedModule)) { 649 if (!Includer) { 650 assert(First && "only first includer can have no file"); 651 return FE; 652 } 653 654 // Leave CurDir unset. 655 // This file is a system header or C++ unfriendly if the old file is. 656 // 657 // Note that we only use one of FromHFI/ToHFI at once, due to potential 658 // reallocation of the underlying vector potentially making the first 659 // reference binding dangling. 660 HeaderFileInfo &FromHFI = getFileInfo(Includer); 661 unsigned DirInfo = FromHFI.DirInfo; 662 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader; 663 StringRef Framework = FromHFI.Framework; 664 665 HeaderFileInfo &ToHFI = getFileInfo(FE); 666 ToHFI.DirInfo = DirInfo; 667 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader; 668 ToHFI.Framework = Framework; 669 670 if (SearchPath) { 671 StringRef SearchPathRef(IncluderAndDir.second->getName()); 672 SearchPath->clear(); 673 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); 674 } 675 if (RelativePath) { 676 RelativePath->clear(); 677 RelativePath->append(Filename.begin(), Filename.end()); 678 } 679 if (First) 680 return FE; 681 682 // Otherwise, we found the path via MSVC header search rules. If 683 // -Wmsvc-include is enabled, we have to keep searching to see if we 684 // would've found this header in -I or -isystem directories. 685 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) { 686 return FE; 687 } else { 688 MSFE = FE; 689 if (SuggestedModule) { 690 MSSuggestedModule = *SuggestedModule; 691 *SuggestedModule = ModuleMap::KnownHeader(); 692 } 693 break; 694 } 695 } 696 First = false; 697 } 698 } 699 700 CurDir = nullptr; 701 702 // If this is a system #include, ignore the user #include locs. 703 unsigned i = isAngled ? AngledDirIdx : 0; 704 705 // If this is a #include_next request, start searching after the directory the 706 // file was found in. 707 if (FromDir) 708 i = FromDir-&SearchDirs[0]; 709 710 // Cache all of the lookups performed by this method. Many headers are 711 // multiply included, and the "pragma once" optimization prevents them from 712 // being relex/pp'd, but they would still have to search through a 713 // (potentially huge) series of SearchDirs to find it. 714 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename]; 715 716 // If the entry has been previously looked up, the first value will be 717 // non-zero. If the value is equal to i (the start point of our search), then 718 // this is a matching hit. 719 if (!SkipCache && CacheLookup.StartIdx == i+1) { 720 // Skip querying potentially lots of directories for this lookup. 721 i = CacheLookup.HitIdx; 722 if (CacheLookup.MappedName) 723 Filename = CacheLookup.MappedName; 724 } else { 725 // Otherwise, this is the first query, or the previous query didn't match 726 // our search start. We will fill in our found location below, so prime the 727 // start point value. 728 CacheLookup.reset(/*StartIdx=*/i+1); 729 } 730 731 SmallString<64> MappedName; 732 733 // Check each directory in sequence to see if it contains this file. 734 for (; i != SearchDirs.size(); ++i) { 735 bool InUserSpecifiedSystemFramework = false; 736 bool HasBeenMapped = false; 737 const FileEntry *FE = 738 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath, 739 SuggestedModule, InUserSpecifiedSystemFramework, 740 HasBeenMapped, MappedName); 741 if (HasBeenMapped) { 742 CacheLookup.MappedName = 743 copyString(Filename, LookupFileCache.getAllocator()); 744 } 745 if (!FE) continue; 746 747 CurDir = &SearchDirs[i]; 748 749 // This file is a system header or C++ unfriendly if the dir is. 750 HeaderFileInfo &HFI = getFileInfo(FE); 751 HFI.DirInfo = CurDir->getDirCharacteristic(); 752 753 // If the directory characteristic is User but this framework was 754 // user-specified to be treated as a system framework, promote the 755 // characteristic. 756 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework) 757 HFI.DirInfo = SrcMgr::C_System; 758 759 // If the filename matches a known system header prefix, override 760 // whether the file is a system header. 761 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) { 762 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) { 763 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System 764 : SrcMgr::C_User; 765 break; 766 } 767 } 768 769 // If this file is found in a header map and uses the framework style of 770 // includes, then this header is part of a framework we're building. 771 if (CurDir->isIndexHeaderMap()) { 772 size_t SlashPos = Filename.find('/'); 773 if (SlashPos != StringRef::npos) { 774 HFI.IndexHeaderMapHeader = 1; 775 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(), 776 SlashPos)); 777 } 778 } 779 780 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) { 781 if (SuggestedModule) 782 *SuggestedModule = MSSuggestedModule; 783 return MSFE; 784 } 785 786 // Remember this location for the next lookup we do. 787 CacheLookup.HitIdx = i; 788 return FE; 789 } 790 791 // If we are including a file with a quoted include "foo.h" from inside 792 // a header in a framework that is currently being built, and we couldn't 793 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where 794 // "Foo" is the name of the framework in which the including header was found. 795 if (!Includers.empty() && Includers.front().first && !isAngled && 796 Filename.find('/') == StringRef::npos) { 797 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first); 798 if (IncludingHFI.IndexHeaderMapHeader) { 799 SmallString<128> ScratchFilename; 800 ScratchFilename += IncludingHFI.Framework; 801 ScratchFilename += '/'; 802 ScratchFilename += Filename; 803 804 const FileEntry *FE = LookupFile( 805 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir, 806 Includers.front(), SearchPath, RelativePath, SuggestedModule); 807 808 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) { 809 if (SuggestedModule) 810 *SuggestedModule = MSSuggestedModule; 811 return MSFE; 812 } 813 814 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename]; 815 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx; 816 // FIXME: SuggestedModule. 817 return FE; 818 } 819 } 820 821 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) { 822 if (SuggestedModule) 823 *SuggestedModule = MSSuggestedModule; 824 return MSFE; 825 } 826 827 // Otherwise, didn't find it. Remember we didn't find this. 828 CacheLookup.HitIdx = SearchDirs.size(); 829 return nullptr; 830 } 831 832 /// LookupSubframeworkHeader - Look up a subframework for the specified 833 /// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from 834 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox 835 /// is a subframework within Carbon.framework. If so, return the FileEntry 836 /// for the designated file, otherwise return null. 837 const FileEntry *HeaderSearch:: 838 LookupSubframeworkHeader(StringRef Filename, 839 const FileEntry *ContextFileEnt, 840 SmallVectorImpl<char> *SearchPath, 841 SmallVectorImpl<char> *RelativePath, 842 ModuleMap::KnownHeader *SuggestedModule) { 843 assert(ContextFileEnt && "No context file?"); 844 845 // Framework names must have a '/' in the filename. Find it. 846 // FIXME: Should we permit '\' on Windows? 847 size_t SlashPos = Filename.find('/'); 848 if (SlashPos == StringRef::npos) return nullptr; 849 850 // Look up the base framework name of the ContextFileEnt. 851 const char *ContextName = ContextFileEnt->getName(); 852 853 // If the context info wasn't a framework, couldn't be a subframework. 854 const unsigned DotFrameworkLen = 10; 855 const char *FrameworkPos = strstr(ContextName, ".framework"); 856 if (FrameworkPos == nullptr || 857 (FrameworkPos[DotFrameworkLen] != '/' && 858 FrameworkPos[DotFrameworkLen] != '\\')) 859 return nullptr; 860 861 SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1); 862 863 // Append Frameworks/HIToolbox.framework/ 864 FrameworkName += "Frameworks/"; 865 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos); 866 FrameworkName += ".framework/"; 867 868 auto &CacheLookup = 869 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos), 870 FrameworkCacheEntry())).first; 871 872 // Some other location? 873 if (CacheLookup.second.Directory && 874 CacheLookup.first().size() == FrameworkName.size() && 875 memcmp(CacheLookup.first().data(), &FrameworkName[0], 876 CacheLookup.first().size()) != 0) 877 return nullptr; 878 879 // Cache subframework. 880 if (!CacheLookup.second.Directory) { 881 ++NumSubFrameworkLookups; 882 883 // If the framework dir doesn't exist, we fail. 884 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName); 885 if (!Dir) return nullptr; 886 887 // Otherwise, if it does, remember that this is the right direntry for this 888 // framework. 889 CacheLookup.second.Directory = Dir; 890 } 891 892 const FileEntry *FE = nullptr; 893 894 if (RelativePath) { 895 RelativePath->clear(); 896 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end()); 897 } 898 899 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h" 900 SmallString<1024> HeadersFilename(FrameworkName); 901 HeadersFilename += "Headers/"; 902 if (SearchPath) { 903 SearchPath->clear(); 904 // Without trailing '/'. 905 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1); 906 } 907 908 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end()); 909 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) { 910 911 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h" 912 HeadersFilename = FrameworkName; 913 HeadersFilename += "PrivateHeaders/"; 914 if (SearchPath) { 915 SearchPath->clear(); 916 // Without trailing '/'. 917 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1); 918 } 919 920 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end()); 921 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) 922 return nullptr; 923 } 924 925 // This file is a system header or C++ unfriendly if the old file is. 926 // 927 // Note that the temporary 'DirInfo' is required here, as either call to 928 // getFileInfo could resize the vector and we don't want to rely on order 929 // of evaluation. 930 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo; 931 getFileInfo(FE).DirInfo = DirInfo; 932 933 // If we're supposed to suggest a module, look for one now. 934 if (SuggestedModule) { 935 // Find the top-level framework based on this framework. 936 FrameworkName.pop_back(); // remove the trailing '/' 937 SmallVector<std::string, 4> SubmodulePath; 938 const DirectoryEntry *TopFrameworkDir 939 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath); 940 941 // Determine the name of the top-level framework. 942 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName()); 943 944 // Load this framework module. If that succeeds, find the suggested module 945 // for this header, if any. 946 bool IsSystem = false; 947 if (loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) { 948 *SuggestedModule = findModuleForHeader(FE); 949 } 950 } 951 952 return FE; 953 } 954 955 //===----------------------------------------------------------------------===// 956 // File Info Management. 957 //===----------------------------------------------------------------------===// 958 959 /// \brief Merge the header file info provided by \p OtherHFI into the current 960 /// header file info (\p HFI) 961 static void mergeHeaderFileInfo(HeaderFileInfo &HFI, 962 const HeaderFileInfo &OtherHFI) { 963 HFI.isImport |= OtherHFI.isImport; 964 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce; 965 HFI.isModuleHeader |= OtherHFI.isModuleHeader; 966 HFI.NumIncludes += OtherHFI.NumIncludes; 967 968 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) { 969 HFI.ControllingMacro = OtherHFI.ControllingMacro; 970 HFI.ControllingMacroID = OtherHFI.ControllingMacroID; 971 } 972 973 if (OtherHFI.External) { 974 HFI.DirInfo = OtherHFI.DirInfo; 975 HFI.External = OtherHFI.External; 976 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader; 977 } 978 979 if (HFI.Framework.empty()) 980 HFI.Framework = OtherHFI.Framework; 981 982 HFI.Resolved = true; 983 } 984 985 /// getFileInfo - Return the HeaderFileInfo structure for the specified 986 /// FileEntry. 987 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) { 988 if (FE->getUID() >= FileInfo.size()) 989 FileInfo.resize(FE->getUID()+1); 990 991 HeaderFileInfo &HFI = FileInfo[FE->getUID()]; 992 if (ExternalSource && !HFI.Resolved) 993 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE)); 994 HFI.IsValid = 1; 995 return HFI; 996 } 997 998 bool HeaderSearch::tryGetFileInfo(const FileEntry *FE, HeaderFileInfo &Result) const { 999 if (FE->getUID() >= FileInfo.size()) 1000 return false; 1001 const HeaderFileInfo &HFI = FileInfo[FE->getUID()]; 1002 if (HFI.IsValid) { 1003 Result = HFI; 1004 return true; 1005 } 1006 return false; 1007 } 1008 1009 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) { 1010 // Check if we've ever seen this file as a header. 1011 if (File->getUID() >= FileInfo.size()) 1012 return false; 1013 1014 // Resolve header file info from the external source, if needed. 1015 HeaderFileInfo &HFI = FileInfo[File->getUID()]; 1016 if (ExternalSource && !HFI.Resolved) 1017 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File)); 1018 1019 return HFI.isPragmaOnce || HFI.isImport || 1020 HFI.ControllingMacro || HFI.ControllingMacroID; 1021 } 1022 1023 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE, 1024 ModuleMap::ModuleHeaderRole Role, 1025 bool isCompilingModuleHeader) { 1026 if (FE->getUID() >= FileInfo.size()) 1027 FileInfo.resize(FE->getUID()+1); 1028 1029 HeaderFileInfo &HFI = FileInfo[FE->getUID()]; 1030 HFI.isModuleHeader = true; 1031 HFI.isCompilingModuleHeader = isCompilingModuleHeader; 1032 HFI.setHeaderRole(Role); 1033 } 1034 1035 bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP, 1036 const FileEntry *File, 1037 bool isImport, Module *M) { 1038 ++NumIncluded; // Count # of attempted #includes. 1039 1040 // Get information about this file. 1041 HeaderFileInfo &FileInfo = getFileInfo(File); 1042 1043 // If this is a #import directive, check that we have not already imported 1044 // this header. 1045 if (isImport) { 1046 // If this has already been imported, don't import it again. 1047 FileInfo.isImport = true; 1048 1049 // Has this already been #import'ed or #include'd? 1050 if (FileInfo.NumIncludes) return false; 1051 } else { 1052 // Otherwise, if this is a #include of a file that was previously #import'd 1053 // or if this is the second #include of a #pragma once file, ignore it. 1054 if (FileInfo.isImport) 1055 return false; 1056 } 1057 1058 // Next, check to see if the file is wrapped with #ifndef guards. If so, and 1059 // if the macro that guards it is defined, we know the #include has no effect. 1060 if (const IdentifierInfo *ControllingMacro 1061 = FileInfo.getControllingMacro(ExternalLookup)) 1062 // If the include file is part of a module, and we already know what its 1063 // controlling macro is, then we've already parsed it and can safely just 1064 // make it visible. This saves us needing to switch into the visibility 1065 // state of the module just to check whether the macro is defined within it. 1066 if (M || PP.isMacroDefined(ControllingMacro)) { 1067 ++NumMultiIncludeFileOptzn; 1068 return false; 1069 } 1070 1071 // Increment the number of times this file has been included. 1072 ++FileInfo.NumIncludes; 1073 1074 return true; 1075 } 1076 1077 size_t HeaderSearch::getTotalMemory() const { 1078 return SearchDirs.capacity() 1079 + llvm::capacity_in_bytes(FileInfo) 1080 + llvm::capacity_in_bytes(HeaderMaps) 1081 + LookupFileCache.getAllocator().getTotalMemory() 1082 + FrameworkMap.getAllocator().getTotalMemory(); 1083 } 1084 1085 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) { 1086 return FrameworkNames.insert(Framework).first->first(); 1087 } 1088 1089 bool HeaderSearch::hasModuleMap(StringRef FileName, 1090 const DirectoryEntry *Root, 1091 bool IsSystem) { 1092 if (!HSOpts->ImplicitModuleMaps) 1093 return false; 1094 1095 SmallVector<const DirectoryEntry *, 2> FixUpDirectories; 1096 1097 StringRef DirName = FileName; 1098 do { 1099 // Get the parent directory name. 1100 DirName = llvm::sys::path::parent_path(DirName); 1101 if (DirName.empty()) 1102 return false; 1103 1104 // Determine whether this directory exists. 1105 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName); 1106 if (!Dir) 1107 return false; 1108 1109 // Try to load the module map file in this directory. 1110 switch (loadModuleMapFile(Dir, IsSystem, 1111 llvm::sys::path::extension(Dir->getName()) == 1112 ".framework")) { 1113 case LMM_NewlyLoaded: 1114 case LMM_AlreadyLoaded: 1115 // Success. All of the directories we stepped through inherit this module 1116 // map file. 1117 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I) 1118 DirectoryHasModuleMap[FixUpDirectories[I]] = true; 1119 return true; 1120 1121 case LMM_NoDirectory: 1122 case LMM_InvalidModuleMap: 1123 break; 1124 } 1125 1126 // If we hit the top of our search, we're done. 1127 if (Dir == Root) 1128 return false; 1129 1130 // Keep track of all of the directories we checked, so we can mark them as 1131 // having module maps if we eventually do find a module map. 1132 FixUpDirectories.push_back(Dir); 1133 } while (true); 1134 } 1135 1136 ModuleMap::KnownHeader 1137 HeaderSearch::findModuleForHeader(const FileEntry *File) const { 1138 if (ExternalSource) { 1139 // Make sure the external source has handled header info about this file, 1140 // which includes whether the file is part of a module. 1141 (void)getFileInfo(File); 1142 } 1143 return ModMap.findModuleForHeader(File); 1144 } 1145 1146 static const FileEntry *getPrivateModuleMap(const FileEntry *File, 1147 FileManager &FileMgr) { 1148 StringRef Filename = llvm::sys::path::filename(File->getName()); 1149 SmallString<128> PrivateFilename(File->getDir()->getName()); 1150 if (Filename == "module.map") 1151 llvm::sys::path::append(PrivateFilename, "module_private.map"); 1152 else if (Filename == "module.modulemap") 1153 llvm::sys::path::append(PrivateFilename, "module.private.modulemap"); 1154 else 1155 return nullptr; 1156 return FileMgr.getFile(PrivateFilename); 1157 } 1158 1159 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) { 1160 // Find the directory for the module. For frameworks, that may require going 1161 // up from the 'Modules' directory. 1162 const DirectoryEntry *Dir = nullptr; 1163 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) 1164 Dir = FileMgr.getDirectory("."); 1165 else { 1166 Dir = File->getDir(); 1167 StringRef DirName(Dir->getName()); 1168 if (llvm::sys::path::filename(DirName) == "Modules") { 1169 DirName = llvm::sys::path::parent_path(DirName); 1170 if (DirName.endswith(".framework")) 1171 Dir = FileMgr.getDirectory(DirName); 1172 // FIXME: This assert can fail if there's a race between the above check 1173 // and the removal of the directory. 1174 assert(Dir && "parent must exist"); 1175 } 1176 } 1177 1178 switch (loadModuleMapFileImpl(File, IsSystem, Dir)) { 1179 case LMM_AlreadyLoaded: 1180 case LMM_NewlyLoaded: 1181 return false; 1182 case LMM_NoDirectory: 1183 case LMM_InvalidModuleMap: 1184 return true; 1185 } 1186 llvm_unreachable("Unknown load module map result"); 1187 } 1188 1189 HeaderSearch::LoadModuleMapResult 1190 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem, 1191 const DirectoryEntry *Dir) { 1192 assert(File && "expected FileEntry"); 1193 1194 // Check whether we've already loaded this module map, and mark it as being 1195 // loaded in case we recursively try to load it from itself. 1196 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true)); 1197 if (!AddResult.second) 1198 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap; 1199 1200 if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) { 1201 LoadedModuleMaps[File] = false; 1202 return LMM_InvalidModuleMap; 1203 } 1204 1205 // Try to load a corresponding private module map. 1206 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) { 1207 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) { 1208 LoadedModuleMaps[File] = false; 1209 return LMM_InvalidModuleMap; 1210 } 1211 } 1212 1213 // This directory has a module map. 1214 return LMM_NewlyLoaded; 1215 } 1216 1217 const FileEntry * 1218 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) { 1219 if (!HSOpts->ImplicitModuleMaps) 1220 return nullptr; 1221 // For frameworks, the preferred spelling is Modules/module.modulemap, but 1222 // module.map at the framework root is also accepted. 1223 SmallString<128> ModuleMapFileName(Dir->getName()); 1224 if (IsFramework) 1225 llvm::sys::path::append(ModuleMapFileName, "Modules"); 1226 llvm::sys::path::append(ModuleMapFileName, "module.modulemap"); 1227 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName)) 1228 return F; 1229 1230 // Continue to allow module.map 1231 ModuleMapFileName = Dir->getName(); 1232 llvm::sys::path::append(ModuleMapFileName, "module.map"); 1233 return FileMgr.getFile(ModuleMapFileName); 1234 } 1235 1236 Module *HeaderSearch::loadFrameworkModule(StringRef Name, 1237 const DirectoryEntry *Dir, 1238 bool IsSystem) { 1239 if (Module *Module = ModMap.findModule(Name)) 1240 return Module; 1241 1242 // Try to load a module map file. 1243 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) { 1244 case LMM_InvalidModuleMap: 1245 // Try to infer a module map from the framework directory. 1246 if (HSOpts->ImplicitModuleMaps) 1247 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr); 1248 break; 1249 1250 case LMM_AlreadyLoaded: 1251 case LMM_NoDirectory: 1252 return nullptr; 1253 1254 case LMM_NewlyLoaded: 1255 break; 1256 } 1257 1258 return ModMap.findModule(Name); 1259 } 1260 1261 1262 HeaderSearch::LoadModuleMapResult 1263 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem, 1264 bool IsFramework) { 1265 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName)) 1266 return loadModuleMapFile(Dir, IsSystem, IsFramework); 1267 1268 return LMM_NoDirectory; 1269 } 1270 1271 HeaderSearch::LoadModuleMapResult 1272 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem, 1273 bool IsFramework) { 1274 auto KnownDir = DirectoryHasModuleMap.find(Dir); 1275 if (KnownDir != DirectoryHasModuleMap.end()) 1276 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap; 1277 1278 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) { 1279 LoadModuleMapResult Result = 1280 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir); 1281 // Add Dir explicitly in case ModuleMapFile is in a subdirectory. 1282 // E.g. Foo.framework/Modules/module.modulemap 1283 // ^Dir ^ModuleMapFile 1284 if (Result == LMM_NewlyLoaded) 1285 DirectoryHasModuleMap[Dir] = true; 1286 else if (Result == LMM_InvalidModuleMap) 1287 DirectoryHasModuleMap[Dir] = false; 1288 return Result; 1289 } 1290 return LMM_InvalidModuleMap; 1291 } 1292 1293 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) { 1294 Modules.clear(); 1295 1296 if (HSOpts->ImplicitModuleMaps) { 1297 // Load module maps for each of the header search directories. 1298 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) { 1299 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory(); 1300 if (SearchDirs[Idx].isFramework()) { 1301 std::error_code EC; 1302 SmallString<128> DirNative; 1303 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(), 1304 DirNative); 1305 1306 // Search each of the ".framework" directories to load them as modules. 1307 for (llvm::sys::fs::directory_iterator Dir(DirNative, EC), DirEnd; 1308 Dir != DirEnd && !EC; Dir.increment(EC)) { 1309 if (llvm::sys::path::extension(Dir->path()) != ".framework") 1310 continue; 1311 1312 const DirectoryEntry *FrameworkDir = 1313 FileMgr.getDirectory(Dir->path()); 1314 if (!FrameworkDir) 1315 continue; 1316 1317 // Load this framework module. 1318 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir, 1319 IsSystem); 1320 } 1321 continue; 1322 } 1323 1324 // FIXME: Deal with header maps. 1325 if (SearchDirs[Idx].isHeaderMap()) 1326 continue; 1327 1328 // Try to load a module map file for the search directory. 1329 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem, 1330 /*IsFramework*/ false); 1331 1332 // Try to load module map files for immediate subdirectories of this 1333 // search directory. 1334 loadSubdirectoryModuleMaps(SearchDirs[Idx]); 1335 } 1336 } 1337 1338 // Populate the list of modules. 1339 for (ModuleMap::module_iterator M = ModMap.module_begin(), 1340 MEnd = ModMap.module_end(); 1341 M != MEnd; ++M) { 1342 Modules.push_back(M->getValue()); 1343 } 1344 } 1345 1346 void HeaderSearch::loadTopLevelSystemModules() { 1347 if (!HSOpts->ImplicitModuleMaps) 1348 return; 1349 1350 // Load module maps for each of the header search directories. 1351 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) { 1352 // We only care about normal header directories. 1353 if (!SearchDirs[Idx].isNormalDir()) { 1354 continue; 1355 } 1356 1357 // Try to load a module map file for the search directory. 1358 loadModuleMapFile(SearchDirs[Idx].getDir(), 1359 SearchDirs[Idx].isSystemHeaderDirectory(), 1360 SearchDirs[Idx].isFramework()); 1361 } 1362 } 1363 1364 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) { 1365 assert(HSOpts->ImplicitModuleMaps && 1366 "Should not be loading subdirectory module maps"); 1367 1368 if (SearchDir.haveSearchedAllModuleMaps()) 1369 return; 1370 1371 std::error_code EC; 1372 SmallString<128> DirNative; 1373 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative); 1374 for (llvm::sys::fs::directory_iterator Dir(DirNative, EC), DirEnd; 1375 Dir != DirEnd && !EC; Dir.increment(EC)) { 1376 bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework"; 1377 if (IsFramework == SearchDir.isFramework()) 1378 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(), 1379 SearchDir.isFramework()); 1380 } 1381 1382 SearchDir.setSearchedAllModuleMaps(true); 1383 } 1384