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