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, 999 HeaderFileInfo &Result) const { 1000 if (FE->getUID() >= FileInfo.size()) 1001 return false; 1002 const HeaderFileInfo &HFI = FileInfo[FE->getUID()]; 1003 if (HFI.IsValid) { 1004 Result = HFI; 1005 return true; 1006 } 1007 return false; 1008 } 1009 1010 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) { 1011 // Check if we've ever seen this file as a header. 1012 if (File->getUID() >= FileInfo.size()) 1013 return false; 1014 1015 // Resolve header file info from the external source, if needed. 1016 HeaderFileInfo &HFI = FileInfo[File->getUID()]; 1017 if (ExternalSource && !HFI.Resolved) 1018 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File)); 1019 1020 return HFI.isPragmaOnce || HFI.isImport || 1021 HFI.ControllingMacro || HFI.ControllingMacroID; 1022 } 1023 1024 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE, 1025 ModuleMap::ModuleHeaderRole Role, 1026 bool isCompilingModuleHeader) { 1027 if (FE->getUID() >= FileInfo.size()) 1028 FileInfo.resize(FE->getUID()+1); 1029 1030 HeaderFileInfo &HFI = FileInfo[FE->getUID()]; 1031 HFI.isModuleHeader = true; 1032 HFI.isCompilingModuleHeader |= isCompilingModuleHeader; 1033 HFI.setHeaderRole(Role); 1034 } 1035 1036 bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP, 1037 const FileEntry *File, 1038 bool isImport, Module *M) { 1039 ++NumIncluded; // Count # of attempted #includes. 1040 1041 // Get information about this file. 1042 HeaderFileInfo &FileInfo = getFileInfo(File); 1043 1044 // If this is a #import directive, check that we have not already imported 1045 // this header. 1046 if (isImport) { 1047 // If this has already been imported, don't import it again. 1048 FileInfo.isImport = true; 1049 1050 // Has this already been #import'ed or #include'd? 1051 if (FileInfo.NumIncludes) return false; 1052 } else { 1053 // Otherwise, if this is a #include of a file that was previously #import'd 1054 // or if this is the second #include of a #pragma once file, ignore it. 1055 if (FileInfo.isImport) 1056 return false; 1057 } 1058 1059 // Next, check to see if the file is wrapped with #ifndef guards. If so, and 1060 // if the macro that guards it is defined, we know the #include has no effect. 1061 if (const IdentifierInfo *ControllingMacro 1062 = FileInfo.getControllingMacro(ExternalLookup)) { 1063 // If the header corresponds to a module, check whether the macro is already 1064 // defined in that module rather than checking in the current set of visible 1065 // modules. 1066 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M) 1067 : PP.isMacroDefined(ControllingMacro)) { 1068 ++NumMultiIncludeFileOptzn; 1069 return false; 1070 } 1071 } 1072 1073 // Increment the number of times this file has been included. 1074 ++FileInfo.NumIncludes; 1075 1076 return true; 1077 } 1078 1079 size_t HeaderSearch::getTotalMemory() const { 1080 return SearchDirs.capacity() 1081 + llvm::capacity_in_bytes(FileInfo) 1082 + llvm::capacity_in_bytes(HeaderMaps) 1083 + LookupFileCache.getAllocator().getTotalMemory() 1084 + FrameworkMap.getAllocator().getTotalMemory(); 1085 } 1086 1087 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) { 1088 return FrameworkNames.insert(Framework).first->first(); 1089 } 1090 1091 bool HeaderSearch::hasModuleMap(StringRef FileName, 1092 const DirectoryEntry *Root, 1093 bool IsSystem) { 1094 if (!HSOpts->ImplicitModuleMaps) 1095 return false; 1096 1097 SmallVector<const DirectoryEntry *, 2> FixUpDirectories; 1098 1099 StringRef DirName = FileName; 1100 do { 1101 // Get the parent directory name. 1102 DirName = llvm::sys::path::parent_path(DirName); 1103 if (DirName.empty()) 1104 return false; 1105 1106 // Determine whether this directory exists. 1107 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName); 1108 if (!Dir) 1109 return false; 1110 1111 // Try to load the module map file in this directory. 1112 switch (loadModuleMapFile(Dir, IsSystem, 1113 llvm::sys::path::extension(Dir->getName()) == 1114 ".framework")) { 1115 case LMM_NewlyLoaded: 1116 case LMM_AlreadyLoaded: 1117 // Success. All of the directories we stepped through inherit this module 1118 // map file. 1119 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I) 1120 DirectoryHasModuleMap[FixUpDirectories[I]] = true; 1121 return true; 1122 1123 case LMM_NoDirectory: 1124 case LMM_InvalidModuleMap: 1125 break; 1126 } 1127 1128 // If we hit the top of our search, we're done. 1129 if (Dir == Root) 1130 return false; 1131 1132 // Keep track of all of the directories we checked, so we can mark them as 1133 // having module maps if we eventually do find a module map. 1134 FixUpDirectories.push_back(Dir); 1135 } while (true); 1136 } 1137 1138 ModuleMap::KnownHeader 1139 HeaderSearch::findModuleForHeader(const FileEntry *File) const { 1140 if (ExternalSource) { 1141 // Make sure the external source has handled header info about this file, 1142 // which includes whether the file is part of a module. 1143 (void)getFileInfo(File); 1144 } 1145 return ModMap.findModuleForHeader(File); 1146 } 1147 1148 static const FileEntry *getPrivateModuleMap(const FileEntry *File, 1149 FileManager &FileMgr) { 1150 StringRef Filename = llvm::sys::path::filename(File->getName()); 1151 SmallString<128> PrivateFilename(File->getDir()->getName()); 1152 if (Filename == "module.map") 1153 llvm::sys::path::append(PrivateFilename, "module_private.map"); 1154 else if (Filename == "module.modulemap") 1155 llvm::sys::path::append(PrivateFilename, "module.private.modulemap"); 1156 else 1157 return nullptr; 1158 return FileMgr.getFile(PrivateFilename); 1159 } 1160 1161 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) { 1162 // Find the directory for the module. For frameworks, that may require going 1163 // up from the 'Modules' directory. 1164 const DirectoryEntry *Dir = nullptr; 1165 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) 1166 Dir = FileMgr.getDirectory("."); 1167 else { 1168 Dir = File->getDir(); 1169 StringRef DirName(Dir->getName()); 1170 if (llvm::sys::path::filename(DirName) == "Modules") { 1171 DirName = llvm::sys::path::parent_path(DirName); 1172 if (DirName.endswith(".framework")) 1173 Dir = FileMgr.getDirectory(DirName); 1174 // FIXME: This assert can fail if there's a race between the above check 1175 // and the removal of the directory. 1176 assert(Dir && "parent must exist"); 1177 } 1178 } 1179 1180 switch (loadModuleMapFileImpl(File, IsSystem, Dir)) { 1181 case LMM_AlreadyLoaded: 1182 case LMM_NewlyLoaded: 1183 return false; 1184 case LMM_NoDirectory: 1185 case LMM_InvalidModuleMap: 1186 return true; 1187 } 1188 llvm_unreachable("Unknown load module map result"); 1189 } 1190 1191 HeaderSearch::LoadModuleMapResult 1192 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem, 1193 const DirectoryEntry *Dir) { 1194 assert(File && "expected FileEntry"); 1195 1196 // Check whether we've already loaded this module map, and mark it as being 1197 // loaded in case we recursively try to load it from itself. 1198 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true)); 1199 if (!AddResult.second) 1200 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap; 1201 1202 if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) { 1203 LoadedModuleMaps[File] = false; 1204 return LMM_InvalidModuleMap; 1205 } 1206 1207 // Try to load a corresponding private module map. 1208 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) { 1209 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) { 1210 LoadedModuleMaps[File] = false; 1211 return LMM_InvalidModuleMap; 1212 } 1213 } 1214 1215 // This directory has a module map. 1216 return LMM_NewlyLoaded; 1217 } 1218 1219 const FileEntry * 1220 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) { 1221 if (!HSOpts->ImplicitModuleMaps) 1222 return nullptr; 1223 // For frameworks, the preferred spelling is Modules/module.modulemap, but 1224 // module.map at the framework root is also accepted. 1225 SmallString<128> ModuleMapFileName(Dir->getName()); 1226 if (IsFramework) 1227 llvm::sys::path::append(ModuleMapFileName, "Modules"); 1228 llvm::sys::path::append(ModuleMapFileName, "module.modulemap"); 1229 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName)) 1230 return F; 1231 1232 // Continue to allow module.map 1233 ModuleMapFileName = Dir->getName(); 1234 llvm::sys::path::append(ModuleMapFileName, "module.map"); 1235 return FileMgr.getFile(ModuleMapFileName); 1236 } 1237 1238 Module *HeaderSearch::loadFrameworkModule(StringRef Name, 1239 const DirectoryEntry *Dir, 1240 bool IsSystem) { 1241 if (Module *Module = ModMap.findModule(Name)) 1242 return Module; 1243 1244 // Try to load a module map file. 1245 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) { 1246 case LMM_InvalidModuleMap: 1247 // Try to infer a module map from the framework directory. 1248 if (HSOpts->ImplicitModuleMaps) 1249 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr); 1250 break; 1251 1252 case LMM_AlreadyLoaded: 1253 case LMM_NoDirectory: 1254 return nullptr; 1255 1256 case LMM_NewlyLoaded: 1257 break; 1258 } 1259 1260 return ModMap.findModule(Name); 1261 } 1262 1263 1264 HeaderSearch::LoadModuleMapResult 1265 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem, 1266 bool IsFramework) { 1267 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName)) 1268 return loadModuleMapFile(Dir, IsSystem, IsFramework); 1269 1270 return LMM_NoDirectory; 1271 } 1272 1273 HeaderSearch::LoadModuleMapResult 1274 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem, 1275 bool IsFramework) { 1276 auto KnownDir = DirectoryHasModuleMap.find(Dir); 1277 if (KnownDir != DirectoryHasModuleMap.end()) 1278 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap; 1279 1280 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) { 1281 LoadModuleMapResult Result = 1282 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir); 1283 // Add Dir explicitly in case ModuleMapFile is in a subdirectory. 1284 // E.g. Foo.framework/Modules/module.modulemap 1285 // ^Dir ^ModuleMapFile 1286 if (Result == LMM_NewlyLoaded) 1287 DirectoryHasModuleMap[Dir] = true; 1288 else if (Result == LMM_InvalidModuleMap) 1289 DirectoryHasModuleMap[Dir] = false; 1290 return Result; 1291 } 1292 return LMM_InvalidModuleMap; 1293 } 1294 1295 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) { 1296 Modules.clear(); 1297 1298 if (HSOpts->ImplicitModuleMaps) { 1299 // Load module maps for each of the header search directories. 1300 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) { 1301 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory(); 1302 if (SearchDirs[Idx].isFramework()) { 1303 std::error_code EC; 1304 SmallString<128> DirNative; 1305 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(), 1306 DirNative); 1307 1308 // Search each of the ".framework" directories to load them as modules. 1309 for (llvm::sys::fs::directory_iterator Dir(DirNative, EC), DirEnd; 1310 Dir != DirEnd && !EC; Dir.increment(EC)) { 1311 if (llvm::sys::path::extension(Dir->path()) != ".framework") 1312 continue; 1313 1314 const DirectoryEntry *FrameworkDir = 1315 FileMgr.getDirectory(Dir->path()); 1316 if (!FrameworkDir) 1317 continue; 1318 1319 // Load this framework module. 1320 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir, 1321 IsSystem); 1322 } 1323 continue; 1324 } 1325 1326 // FIXME: Deal with header maps. 1327 if (SearchDirs[Idx].isHeaderMap()) 1328 continue; 1329 1330 // Try to load a module map file for the search directory. 1331 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem, 1332 /*IsFramework*/ false); 1333 1334 // Try to load module map files for immediate subdirectories of this 1335 // search directory. 1336 loadSubdirectoryModuleMaps(SearchDirs[Idx]); 1337 } 1338 } 1339 1340 // Populate the list of modules. 1341 for (ModuleMap::module_iterator M = ModMap.module_begin(), 1342 MEnd = ModMap.module_end(); 1343 M != MEnd; ++M) { 1344 Modules.push_back(M->getValue()); 1345 } 1346 } 1347 1348 void HeaderSearch::loadTopLevelSystemModules() { 1349 if (!HSOpts->ImplicitModuleMaps) 1350 return; 1351 1352 // Load module maps for each of the header search directories. 1353 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) { 1354 // We only care about normal header directories. 1355 if (!SearchDirs[Idx].isNormalDir()) { 1356 continue; 1357 } 1358 1359 // Try to load a module map file for the search directory. 1360 loadModuleMapFile(SearchDirs[Idx].getDir(), 1361 SearchDirs[Idx].isSystemHeaderDirectory(), 1362 SearchDirs[Idx].isFramework()); 1363 } 1364 } 1365 1366 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) { 1367 assert(HSOpts->ImplicitModuleMaps && 1368 "Should not be loading subdirectory module maps"); 1369 1370 if (SearchDir.haveSearchedAllModuleMaps()) 1371 return; 1372 1373 std::error_code EC; 1374 SmallString<128> DirNative; 1375 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative); 1376 for (llvm::sys::fs::directory_iterator Dir(DirNative, EC), DirEnd; 1377 Dir != DirEnd && !EC; Dir.increment(EC)) { 1378 bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework"; 1379 if (IsFramework == SearchDir.isFramework()) 1380 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(), 1381 SearchDir.isFramework()); 1382 } 1383 1384 SearchDir.setSearchedAllModuleMaps(true); 1385 } 1386