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