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