1 //===- HeaderSearch.cpp - Resolve Header File Locations -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the DirectoryLookup and HeaderSearch interfaces. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Lex/HeaderSearch.h" 14 #include "clang/Basic/Diagnostic.h" 15 #include "clang/Basic/FileManager.h" 16 #include "clang/Basic/IdentifierTable.h" 17 #include "clang/Basic/Module.h" 18 #include "clang/Basic/SourceManager.h" 19 #include "clang/Lex/DirectoryLookup.h" 20 #include "clang/Lex/ExternalPreprocessorSource.h" 21 #include "clang/Lex/HeaderMap.h" 22 #include "clang/Lex/HeaderSearchOptions.h" 23 #include "clang/Lex/LexDiagnostic.h" 24 #include "clang/Lex/ModuleMap.h" 25 #include "clang/Lex/Preprocessor.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/Hashing.h" 28 #include "llvm/ADT/SmallString.h" 29 #include "llvm/ADT/SmallVector.h" 30 #include "llvm/ADT/Statistic.h" 31 #include "llvm/ADT/StringRef.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/Support/Allocator.h" 34 #include "llvm/Support/Capacity.h" 35 #include "llvm/Support/Errc.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/FileSystem.h" 38 #include "llvm/Support/Path.h" 39 #include "llvm/Support/VirtualFileSystem.h" 40 #include <algorithm> 41 #include <cassert> 42 #include <cstddef> 43 #include <cstdio> 44 #include <cstring> 45 #include <string> 46 #include <system_error> 47 #include <utility> 48 49 using namespace clang; 50 51 #define DEBUG_TYPE "file-search" 52 53 ALWAYS_ENABLED_STATISTIC(NumIncluded, "Number of attempted #includes."); 54 ALWAYS_ENABLED_STATISTIC( 55 NumMultiIncludeFileOptzn, 56 "Number of #includes skipped due to the multi-include optimization."); 57 ALWAYS_ENABLED_STATISTIC(NumFrameworkLookups, "Number of framework lookups."); 58 ALWAYS_ENABLED_STATISTIC(NumSubFrameworkLookups, 59 "Number of subframework lookups."); 60 61 const IdentifierInfo * 62 HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) { 63 if (ControllingMacro) { 64 if (ControllingMacro->isOutOfDate()) { 65 assert(External && "We must have an external source if we have a " 66 "controlling macro that is out of date."); 67 External->updateOutOfDateIdentifier( 68 *const_cast<IdentifierInfo *>(ControllingMacro)); 69 } 70 return ControllingMacro; 71 } 72 73 if (!ControllingMacroID || !External) 74 return nullptr; 75 76 ControllingMacro = External->GetIdentifier(ControllingMacroID); 77 return ControllingMacro; 78 } 79 80 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() = default; 81 82 HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts, 83 SourceManager &SourceMgr, DiagnosticsEngine &Diags, 84 const LangOptions &LangOpts, 85 const TargetInfo *Target) 86 : HSOpts(std::move(HSOpts)), Diags(Diags), 87 FileMgr(SourceMgr.getFileManager()), FrameworkMap(64), 88 ModMap(SourceMgr, Diags, LangOpts, Target, *this) {} 89 90 void HeaderSearch::PrintStats() { 91 llvm::errs() << "\n*** HeaderSearch Stats:\n" 92 << FileInfo.size() << " files tracked.\n"; 93 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0; 94 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) { 95 NumOnceOnlyFiles += (FileInfo[i].isPragmaOnce || FileInfo[i].isImport); 96 if (MaxNumIncludes < FileInfo[i].NumIncludes) 97 MaxNumIncludes = FileInfo[i].NumIncludes; 98 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1; 99 } 100 llvm::errs() << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n" 101 << " " << NumSingleIncludedFiles << " included exactly once.\n" 102 << " " << MaxNumIncludes << " max times a file is included.\n"; 103 104 llvm::errs() << " " << NumIncluded << " #include/#include_next/#import.\n" 105 << " " << NumMultiIncludeFileOptzn 106 << " #includes skipped due to the multi-include optimization.\n"; 107 108 llvm::errs() << NumFrameworkLookups << " framework lookups.\n" 109 << NumSubFrameworkLookups << " subframework lookups.\n"; 110 } 111 112 void HeaderSearch::SetSearchPaths( 113 std::vector<DirectoryLookup> dirs, unsigned int angledDirIdx, 114 unsigned int systemDirIdx, bool noCurDirSearch, 115 llvm::DenseMap<unsigned int, unsigned int> searchDirToHSEntry) { 116 assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() && 117 "Directory indices are unordered"); 118 SearchDirs = std::move(dirs); 119 SearchDirsUsage.assign(SearchDirs.size(), false); 120 AngledDirIdx = angledDirIdx; 121 SystemDirIdx = systemDirIdx; 122 NoCurDirSearch = noCurDirSearch; 123 SearchDirToHSEntry = std::move(searchDirToHSEntry); 124 //LookupFileCache.clear(); 125 } 126 127 void HeaderSearch::AddSearchPath(const DirectoryLookup &dir, bool isAngled) { 128 unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx; 129 SearchDirs.insert(SearchDirs.begin() + idx, dir); 130 SearchDirsUsage.insert(SearchDirsUsage.begin() + idx, false); 131 if (!isAngled) 132 AngledDirIdx++; 133 SystemDirIdx++; 134 } 135 136 std::vector<bool> HeaderSearch::computeUserEntryUsage() const { 137 std::vector<bool> UserEntryUsage(HSOpts->UserEntries.size()); 138 for (unsigned I = 0, E = SearchDirsUsage.size(); I < E; ++I) { 139 // Check whether this DirectoryLookup has been successfully used. 140 if (SearchDirsUsage[I]) { 141 auto UserEntryIdxIt = SearchDirToHSEntry.find(I); 142 // Check whether this DirectoryLookup maps to a HeaderSearch::UserEntry. 143 if (UserEntryIdxIt != SearchDirToHSEntry.end()) 144 UserEntryUsage[UserEntryIdxIt->second] = true; 145 } 146 } 147 return UserEntryUsage; 148 } 149 150 /// CreateHeaderMap - This method returns a HeaderMap for the specified 151 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure. 152 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) { 153 // We expect the number of headermaps to be small, and almost always empty. 154 // If it ever grows, use of a linear search should be re-evaluated. 155 if (!HeaderMaps.empty()) { 156 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i) 157 // Pointer equality comparison of FileEntries works because they are 158 // already uniqued by inode. 159 if (HeaderMaps[i].first == FE) 160 return HeaderMaps[i].second.get(); 161 } 162 163 if (std::unique_ptr<HeaderMap> HM = HeaderMap::Create(FE, FileMgr)) { 164 HeaderMaps.emplace_back(FE, std::move(HM)); 165 return HeaderMaps.back().second.get(); 166 } 167 168 return nullptr; 169 } 170 171 /// Get filenames for all registered header maps. 172 void HeaderSearch::getHeaderMapFileNames( 173 SmallVectorImpl<std::string> &Names) const { 174 for (auto &HM : HeaderMaps) 175 Names.push_back(std::string(HM.first->getName())); 176 } 177 178 std::string HeaderSearch::getCachedModuleFileName(Module *Module) { 179 const FileEntry *ModuleMap = 180 getModuleMap().getModuleMapFileForUniquing(Module); 181 return getCachedModuleFileName(Module->Name, ModuleMap->getName()); 182 } 183 184 std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName, 185 bool FileMapOnly) { 186 // First check the module name to pcm file map. 187 auto i(HSOpts->PrebuiltModuleFiles.find(ModuleName)); 188 if (i != HSOpts->PrebuiltModuleFiles.end()) 189 return i->second; 190 191 if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty()) 192 return {}; 193 194 // Then go through each prebuilt module directory and try to find the pcm 195 // file. 196 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) { 197 SmallString<256> Result(Dir); 198 llvm::sys::fs::make_absolute(Result); 199 llvm::sys::path::append(Result, ModuleName + ".pcm"); 200 if (getFileMgr().getFile(Result.str())) 201 return std::string(Result); 202 } 203 return {}; 204 } 205 206 std::string HeaderSearch::getPrebuiltImplicitModuleFileName(Module *Module) { 207 const FileEntry *ModuleMap = 208 getModuleMap().getModuleMapFileForUniquing(Module); 209 StringRef ModuleName = Module->Name; 210 StringRef ModuleMapPath = ModuleMap->getName(); 211 StringRef ModuleCacheHash = HSOpts->DisableModuleHash ? "" : getModuleHash(); 212 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) { 213 SmallString<256> CachePath(Dir); 214 llvm::sys::fs::make_absolute(CachePath); 215 llvm::sys::path::append(CachePath, ModuleCacheHash); 216 std::string FileName = 217 getCachedModuleFileNameImpl(ModuleName, ModuleMapPath, CachePath); 218 if (!FileName.empty() && getFileMgr().getFile(FileName)) 219 return FileName; 220 } 221 return {}; 222 } 223 224 std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName, 225 StringRef ModuleMapPath) { 226 return getCachedModuleFileNameImpl(ModuleName, ModuleMapPath, 227 getModuleCachePath()); 228 } 229 230 std::string HeaderSearch::getCachedModuleFileNameImpl(StringRef ModuleName, 231 StringRef ModuleMapPath, 232 StringRef CachePath) { 233 // If we don't have a module cache path or aren't supposed to use one, we 234 // can't do anything. 235 if (CachePath.empty()) 236 return {}; 237 238 SmallString<256> Result(CachePath); 239 llvm::sys::fs::make_absolute(Result); 240 241 if (HSOpts->DisableModuleHash) { 242 llvm::sys::path::append(Result, ModuleName + ".pcm"); 243 } else { 244 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should 245 // ideally be globally unique to this particular module. Name collisions 246 // in the hash are safe (because any translation unit can only import one 247 // module with each name), but result in a loss of caching. 248 // 249 // To avoid false-negatives, we form as canonical a path as we can, and map 250 // to lower-case in case we're on a case-insensitive file system. 251 std::string Parent = 252 std::string(llvm::sys::path::parent_path(ModuleMapPath)); 253 if (Parent.empty()) 254 Parent = "."; 255 auto Dir = FileMgr.getDirectory(Parent); 256 if (!Dir) 257 return {}; 258 auto DirName = FileMgr.getCanonicalName(*Dir); 259 auto FileName = llvm::sys::path::filename(ModuleMapPath); 260 261 llvm::hash_code Hash = 262 llvm::hash_combine(DirName.lower(), FileName.lower()); 263 264 SmallString<128> HashStr; 265 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36); 266 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm"); 267 } 268 return Result.str().str(); 269 } 270 271 Module *HeaderSearch::lookupModule(StringRef ModuleName, 272 SourceLocation ImportLoc, bool AllowSearch, 273 bool AllowExtraModuleMapSearch) { 274 // Look in the module map to determine if there is a module by this name. 275 Module *Module = ModMap.findModule(ModuleName); 276 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps) 277 return Module; 278 279 StringRef SearchName = ModuleName; 280 Module = lookupModule(ModuleName, SearchName, ImportLoc, 281 AllowExtraModuleMapSearch); 282 283 // The facility for "private modules" -- adjacent, optional module maps named 284 // module.private.modulemap that are supposed to define private submodules -- 285 // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private. 286 // 287 // Foo.Private is now deprecated in favor of Foo_Private. Users of FooPrivate 288 // should also rename to Foo_Private. Representing private as submodules 289 // could force building unwanted dependencies into the parent module and cause 290 // dependency cycles. 291 if (!Module && SearchName.consume_back("_Private")) 292 Module = lookupModule(ModuleName, SearchName, ImportLoc, 293 AllowExtraModuleMapSearch); 294 if (!Module && SearchName.consume_back("Private")) 295 Module = lookupModule(ModuleName, SearchName, ImportLoc, 296 AllowExtraModuleMapSearch); 297 return Module; 298 } 299 300 Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName, 301 SourceLocation ImportLoc, 302 bool AllowExtraModuleMapSearch) { 303 Module *Module = nullptr; 304 unsigned Idx; 305 306 // Look through the various header search paths to load any available module 307 // maps, searching for a module map that describes this module. 308 for (Idx = 0; Idx != SearchDirs.size(); ++Idx) { 309 if (SearchDirs[Idx].isFramework()) { 310 // Search for or infer a module map for a framework. Here we use 311 // SearchName rather than ModuleName, to permit finding private modules 312 // named FooPrivate in buggy frameworks named Foo. 313 SmallString<128> FrameworkDirName; 314 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName(); 315 llvm::sys::path::append(FrameworkDirName, SearchName + ".framework"); 316 if (auto FrameworkDir = FileMgr.getDirectory(FrameworkDirName)) { 317 bool IsSystem 318 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User; 319 Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem); 320 if (Module) 321 break; 322 } 323 } 324 325 // FIXME: Figure out how header maps and module maps will work together. 326 327 // Only deal with normal search directories. 328 if (!SearchDirs[Idx].isNormalDir()) 329 continue; 330 331 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory(); 332 // Search for a module map file in this directory. 333 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem, 334 /*IsFramework*/false) == LMM_NewlyLoaded) { 335 // We just loaded a module map file; check whether the module is 336 // available now. 337 Module = ModMap.findModule(ModuleName); 338 if (Module) 339 break; 340 } 341 342 // Search for a module map in a subdirectory with the same name as the 343 // module. 344 SmallString<128> NestedModuleMapDirName; 345 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName(); 346 llvm::sys::path::append(NestedModuleMapDirName, ModuleName); 347 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem, 348 /*IsFramework*/false) == LMM_NewlyLoaded){ 349 // If we just loaded a module map file, look for the module again. 350 Module = ModMap.findModule(ModuleName); 351 if (Module) 352 break; 353 } 354 355 // If we've already performed the exhaustive search for module maps in this 356 // search directory, don't do it again. 357 if (SearchDirs[Idx].haveSearchedAllModuleMaps()) 358 continue; 359 360 // Load all module maps in the immediate subdirectories of this search 361 // directory if ModuleName was from @import. 362 if (AllowExtraModuleMapSearch) 363 loadSubdirectoryModuleMaps(SearchDirs[Idx]); 364 365 // Look again for the module. 366 Module = ModMap.findModule(ModuleName); 367 if (Module) 368 break; 369 } 370 371 if (Module) 372 noteLookupUsage(Idx, ImportLoc); 373 374 return Module; 375 } 376 377 //===----------------------------------------------------------------------===// 378 // File lookup within a DirectoryLookup scope 379 //===----------------------------------------------------------------------===// 380 381 /// getName - Return the directory or filename corresponding to this lookup 382 /// object. 383 StringRef DirectoryLookup::getName() const { 384 // FIXME: Use the name from \c DirectoryEntryRef. 385 if (isNormalDir()) 386 return getDir()->getName(); 387 if (isFramework()) 388 return getFrameworkDir()->getName(); 389 assert(isHeaderMap() && "Unknown DirectoryLookup"); 390 return getHeaderMap()->getFileName(); 391 } 392 393 Optional<FileEntryRef> HeaderSearch::getFileAndSuggestModule( 394 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir, 395 bool IsSystemHeaderDir, Module *RequestingModule, 396 ModuleMap::KnownHeader *SuggestedModule) { 397 // If we have a module map that might map this header, load it and 398 // check whether we'll have a suggestion for a module. 399 auto File = getFileMgr().getFileRef(FileName, /*OpenFile=*/true); 400 if (!File) { 401 // For rare, surprising errors (e.g. "out of file handles"), diag the EC 402 // message. 403 std::error_code EC = llvm::errorToErrorCode(File.takeError()); 404 if (EC != llvm::errc::no_such_file_or_directory && 405 EC != llvm::errc::invalid_argument && 406 EC != llvm::errc::is_a_directory && EC != llvm::errc::not_a_directory) { 407 Diags.Report(IncludeLoc, diag::err_cannot_open_file) 408 << FileName << EC.message(); 409 } 410 return None; 411 } 412 413 // If there is a module that corresponds to this header, suggest it. 414 if (!findUsableModuleForHeader( 415 &File->getFileEntry(), Dir ? Dir : File->getFileEntry().getDir(), 416 RequestingModule, SuggestedModule, IsSystemHeaderDir)) 417 return None; 418 419 return *File; 420 } 421 422 /// LookupFile - Lookup the specified file in this search path, returning it 423 /// if it exists or returning null if not. 424 Optional<FileEntryRef> DirectoryLookup::LookupFile( 425 StringRef &Filename, HeaderSearch &HS, SourceLocation IncludeLoc, 426 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, 427 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule, 428 bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound, 429 bool &IsInHeaderMap, SmallVectorImpl<char> &MappedName) const { 430 InUserSpecifiedSystemFramework = false; 431 IsInHeaderMap = false; 432 MappedName.clear(); 433 434 SmallString<1024> TmpDir; 435 if (isNormalDir()) { 436 // Concatenate the requested file onto the directory. 437 TmpDir = getDir()->getName(); 438 llvm::sys::path::append(TmpDir, Filename); 439 if (SearchPath) { 440 StringRef SearchPathRef(getDir()->getName()); 441 SearchPath->clear(); 442 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); 443 } 444 if (RelativePath) { 445 RelativePath->clear(); 446 RelativePath->append(Filename.begin(), Filename.end()); 447 } 448 449 return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(), 450 isSystemHeaderDirectory(), 451 RequestingModule, SuggestedModule); 452 } 453 454 if (isFramework()) 455 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath, 456 RequestingModule, SuggestedModule, 457 InUserSpecifiedSystemFramework, IsFrameworkFound); 458 459 assert(isHeaderMap() && "Unknown directory lookup"); 460 const HeaderMap *HM = getHeaderMap(); 461 SmallString<1024> Path; 462 StringRef Dest = HM->lookupFilename(Filename, Path); 463 if (Dest.empty()) 464 return None; 465 466 IsInHeaderMap = true; 467 468 auto FixupSearchPath = [&]() { 469 if (SearchPath) { 470 StringRef SearchPathRef(getName()); 471 SearchPath->clear(); 472 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); 473 } 474 if (RelativePath) { 475 RelativePath->clear(); 476 RelativePath->append(Filename.begin(), Filename.end()); 477 } 478 }; 479 480 // Check if the headermap maps the filename to a framework include 481 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the 482 // framework include. 483 if (llvm::sys::path::is_relative(Dest)) { 484 MappedName.append(Dest.begin(), Dest.end()); 485 Filename = StringRef(MappedName.begin(), MappedName.size()); 486 Dest = HM->lookupFilename(Filename, Path); 487 } 488 489 if (auto Res = HS.getFileMgr().getOptionalFileRef(Dest)) { 490 FixupSearchPath(); 491 return *Res; 492 } 493 494 // Header maps need to be marked as used whenever the filename matches. 495 // The case where the target file **exists** is handled by callee of this 496 // function as part of the regular logic that applies to include search paths. 497 // The case where the target file **does not exist** is handled here: 498 HS.noteLookupUsage(*HS.searchDirIdx(*this), IncludeLoc); 499 return None; 500 } 501 502 /// Given a framework directory, find the top-most framework directory. 503 /// 504 /// \param FileMgr The file manager to use for directory lookups. 505 /// \param DirName The name of the framework directory. 506 /// \param SubmodulePath Will be populated with the submodule path from the 507 /// returned top-level module to the originally named framework. 508 static const DirectoryEntry * 509 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName, 510 SmallVectorImpl<std::string> &SubmodulePath) { 511 assert(llvm::sys::path::extension(DirName) == ".framework" && 512 "Not a framework directory"); 513 514 // Note: as an egregious but useful hack we use the real path here, because 515 // frameworks moving between top-level frameworks to embedded frameworks tend 516 // to be symlinked, and we base the logical structure of modules on the 517 // physical layout. In particular, we need to deal with crazy includes like 518 // 519 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h> 520 // 521 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework 522 // which one should access with, e.g., 523 // 524 // #include <Bar/Wibble.h> 525 // 526 // Similar issues occur when a top-level framework has moved into an 527 // embedded framework. 528 const DirectoryEntry *TopFrameworkDir = nullptr; 529 if (auto TopFrameworkDirOrErr = FileMgr.getDirectory(DirName)) 530 TopFrameworkDir = *TopFrameworkDirOrErr; 531 532 if (TopFrameworkDir) 533 DirName = FileMgr.getCanonicalName(TopFrameworkDir); 534 do { 535 // Get the parent directory name. 536 DirName = llvm::sys::path::parent_path(DirName); 537 if (DirName.empty()) 538 break; 539 540 // Determine whether this directory exists. 541 auto Dir = FileMgr.getDirectory(DirName); 542 if (!Dir) 543 break; 544 545 // If this is a framework directory, then we're a subframework of this 546 // framework. 547 if (llvm::sys::path::extension(DirName) == ".framework") { 548 SubmodulePath.push_back(std::string(llvm::sys::path::stem(DirName))); 549 TopFrameworkDir = *Dir; 550 } 551 } while (true); 552 553 return TopFrameworkDir; 554 } 555 556 static bool needModuleLookup(Module *RequestingModule, 557 bool HasSuggestedModule) { 558 return HasSuggestedModule || 559 (RequestingModule && RequestingModule->NoUndeclaredIncludes); 560 } 561 562 /// DoFrameworkLookup - Do a lookup of the specified file in the current 563 /// DirectoryLookup, which is a framework directory. 564 Optional<FileEntryRef> DirectoryLookup::DoFrameworkLookup( 565 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath, 566 SmallVectorImpl<char> *RelativePath, Module *RequestingModule, 567 ModuleMap::KnownHeader *SuggestedModule, 568 bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound) const { 569 FileManager &FileMgr = HS.getFileMgr(); 570 571 // Framework names must have a '/' in the filename. 572 size_t SlashPos = Filename.find('/'); 573 if (SlashPos == StringRef::npos) 574 return None; 575 576 // Find out if this is the home for the specified framework, by checking 577 // HeaderSearch. Possible answers are yes/no and unknown. 578 FrameworkCacheEntry &CacheEntry = 579 HS.LookupFrameworkCache(Filename.substr(0, SlashPos)); 580 581 // If it is known and in some other directory, fail. 582 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir()) 583 return None; 584 585 // Otherwise, construct the path to this framework dir. 586 587 // FrameworkName = "/System/Library/Frameworks/" 588 SmallString<1024> FrameworkName; 589 FrameworkName += getFrameworkDirRef()->getName(); 590 if (FrameworkName.empty() || FrameworkName.back() != '/') 591 FrameworkName.push_back('/'); 592 593 // FrameworkName = "/System/Library/Frameworks/Cocoa" 594 StringRef ModuleName(Filename.begin(), SlashPos); 595 FrameworkName += ModuleName; 596 597 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/" 598 FrameworkName += ".framework/"; 599 600 // If the cache entry was unresolved, populate it now. 601 if (!CacheEntry.Directory) { 602 ++NumFrameworkLookups; 603 604 // If the framework dir doesn't exist, we fail. 605 auto Dir = FileMgr.getDirectory(FrameworkName); 606 if (!Dir) 607 return None; 608 609 // Otherwise, if it does, remember that this is the right direntry for this 610 // framework. 611 CacheEntry.Directory = getFrameworkDir(); 612 613 // If this is a user search directory, check if the framework has been 614 // user-specified as a system framework. 615 if (getDirCharacteristic() == SrcMgr::C_User) { 616 SmallString<1024> SystemFrameworkMarker(FrameworkName); 617 SystemFrameworkMarker += ".system_framework"; 618 if (llvm::sys::fs::exists(SystemFrameworkMarker)) { 619 CacheEntry.IsUserSpecifiedSystemFramework = true; 620 } 621 } 622 } 623 624 // Set out flags. 625 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework; 626 IsFrameworkFound = CacheEntry.Directory; 627 628 if (RelativePath) { 629 RelativePath->clear(); 630 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end()); 631 } 632 633 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h" 634 unsigned OrigSize = FrameworkName.size(); 635 636 FrameworkName += "Headers/"; 637 638 if (SearchPath) { 639 SearchPath->clear(); 640 // Without trailing '/'. 641 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1); 642 } 643 644 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end()); 645 646 auto File = 647 FileMgr.getOptionalFileRef(FrameworkName, /*OpenFile=*/!SuggestedModule); 648 if (!File) { 649 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h" 650 const char *Private = "Private"; 651 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private, 652 Private+strlen(Private)); 653 if (SearchPath) 654 SearchPath->insert(SearchPath->begin()+OrigSize, Private, 655 Private+strlen(Private)); 656 657 File = FileMgr.getOptionalFileRef(FrameworkName, 658 /*OpenFile=*/!SuggestedModule); 659 } 660 661 // If we found the header and are allowed to suggest a module, do so now. 662 if (File && needModuleLookup(RequestingModule, SuggestedModule)) { 663 // Find the framework in which this header occurs. 664 StringRef FrameworkPath = File->getFileEntry().getDir()->getName(); 665 bool FoundFramework = false; 666 do { 667 // Determine whether this directory exists. 668 auto Dir = FileMgr.getDirectory(FrameworkPath); 669 if (!Dir) 670 break; 671 672 // If this is a framework directory, then we're a subframework of this 673 // framework. 674 if (llvm::sys::path::extension(FrameworkPath) == ".framework") { 675 FoundFramework = true; 676 break; 677 } 678 679 // Get the parent directory name. 680 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath); 681 if (FrameworkPath.empty()) 682 break; 683 } while (true); 684 685 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User; 686 if (FoundFramework) { 687 if (!HS.findUsableModuleForFrameworkHeader( 688 &File->getFileEntry(), FrameworkPath, RequestingModule, 689 SuggestedModule, IsSystem)) 690 return None; 691 } else { 692 if (!HS.findUsableModuleForHeader(&File->getFileEntry(), getDir(), 693 RequestingModule, SuggestedModule, 694 IsSystem)) 695 return None; 696 } 697 } 698 if (File) 699 return *File; 700 return None; 701 } 702 703 void HeaderSearch::cacheLookupSuccess(LookupFileCacheInfo &CacheLookup, 704 unsigned HitIdx, SourceLocation Loc) { 705 CacheLookup.HitIdx = HitIdx; 706 noteLookupUsage(HitIdx, Loc); 707 } 708 709 void HeaderSearch::noteLookupUsage(unsigned HitIdx, SourceLocation Loc) { 710 SearchDirsUsage[HitIdx] = true; 711 712 auto UserEntryIdxIt = SearchDirToHSEntry.find(HitIdx); 713 if (UserEntryIdxIt != SearchDirToHSEntry.end()) 714 Diags.Report(Loc, diag::remark_pp_search_path_usage) 715 << HSOpts->UserEntries[UserEntryIdxIt->second].Path; 716 } 717 718 void HeaderSearch::setTarget(const TargetInfo &Target) { 719 ModMap.setTarget(Target); 720 } 721 722 //===----------------------------------------------------------------------===// 723 // Header File Location. 724 //===----------------------------------------------------------------------===// 725 726 /// Return true with a diagnostic if the file that MSVC would have found 727 /// fails to match the one that Clang would have found with MSVC header search 728 /// disabled. 729 static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags, 730 const FileEntry *MSFE, const FileEntry *FE, 731 SourceLocation IncludeLoc) { 732 if (MSFE && FE != MSFE) { 733 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName(); 734 return true; 735 } 736 return false; 737 } 738 739 static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) { 740 assert(!Str.empty()); 741 char *CopyStr = Alloc.Allocate<char>(Str.size()+1); 742 std::copy(Str.begin(), Str.end(), CopyStr); 743 CopyStr[Str.size()] = '\0'; 744 return CopyStr; 745 } 746 747 static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader, 748 SmallVectorImpl<char> &FrameworkName) { 749 using namespace llvm::sys; 750 path::const_iterator I = path::begin(Path); 751 path::const_iterator E = path::end(Path); 752 IsPrivateHeader = false; 753 754 // Detect different types of framework style paths: 755 // 756 // ...Foo.framework/{Headers,PrivateHeaders} 757 // ...Foo.framework/Versions/{A,Current}/{Headers,PrivateHeaders} 758 // ...Foo.framework/Frameworks/Nested.framework/{Headers,PrivateHeaders} 759 // ...<other variations with 'Versions' like in the above path> 760 // 761 // and some other variations among these lines. 762 int FoundComp = 0; 763 while (I != E) { 764 if (*I == "Headers") 765 ++FoundComp; 766 if (I->endswith(".framework")) { 767 FrameworkName.append(I->begin(), I->end()); 768 ++FoundComp; 769 } 770 if (*I == "PrivateHeaders") { 771 ++FoundComp; 772 IsPrivateHeader = true; 773 } 774 ++I; 775 } 776 777 return !FrameworkName.empty() && FoundComp >= 2; 778 } 779 780 static void 781 diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc, 782 StringRef Includer, StringRef IncludeFilename, 783 const FileEntry *IncludeFE, bool isAngled = false, 784 bool FoundByHeaderMap = false) { 785 bool IsIncluderPrivateHeader = false; 786 SmallString<128> FromFramework, ToFramework; 787 if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework)) 788 return; 789 bool IsIncludeePrivateHeader = false; 790 bool IsIncludeeInFramework = isFrameworkStylePath( 791 IncludeFE->getName(), IsIncludeePrivateHeader, ToFramework); 792 793 if (!isAngled && !FoundByHeaderMap) { 794 SmallString<128> NewInclude("<"); 795 if (IsIncludeeInFramework) { 796 NewInclude += ToFramework.str().drop_back(10); // drop .framework 797 NewInclude += "/"; 798 } 799 NewInclude += IncludeFilename; 800 NewInclude += ">"; 801 Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header) 802 << IncludeFilename 803 << FixItHint::CreateReplacement(IncludeLoc, NewInclude); 804 } 805 806 // Headers in Foo.framework/Headers should not include headers 807 // from Foo.framework/PrivateHeaders, since this violates public/private 808 // API boundaries and can cause modular dependency cycles. 809 if (!IsIncluderPrivateHeader && IsIncludeeInFramework && 810 IsIncludeePrivateHeader && FromFramework == ToFramework) 811 Diags.Report(IncludeLoc, diag::warn_framework_include_private_from_public) 812 << IncludeFilename; 813 } 814 815 /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file, 816 /// return null on failure. isAngled indicates whether the file reference is 817 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if 818 /// non-empty, indicates where the \#including file(s) are, in case a relative 819 /// search is needed. Microsoft mode will pass all \#including files. 820 Optional<FileEntryRef> HeaderSearch::LookupFile( 821 StringRef Filename, SourceLocation IncludeLoc, bool isAngled, 822 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir, 823 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers, 824 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, 825 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule, 826 bool *IsMapped, bool *IsFrameworkFound, bool SkipCache, 827 bool BuildSystemModule) { 828 if (IsMapped) 829 *IsMapped = false; 830 831 if (IsFrameworkFound) 832 *IsFrameworkFound = false; 833 834 if (SuggestedModule) 835 *SuggestedModule = ModuleMap::KnownHeader(); 836 837 // If 'Filename' is absolute, check to see if it exists and no searching. 838 if (llvm::sys::path::is_absolute(Filename)) { 839 CurDir = nullptr; 840 841 // If this was an #include_next "/absolute/file", fail. 842 if (FromDir) 843 return None; 844 845 if (SearchPath) 846 SearchPath->clear(); 847 if (RelativePath) { 848 RelativePath->clear(); 849 RelativePath->append(Filename.begin(), Filename.end()); 850 } 851 // Otherwise, just return the file. 852 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr, 853 /*IsSystemHeaderDir*/false, 854 RequestingModule, SuggestedModule); 855 } 856 857 // This is the header that MSVC's header search would have found. 858 ModuleMap::KnownHeader MSSuggestedModule; 859 Optional<FileEntryRef> MSFE; 860 861 // Unless disabled, check to see if the file is in the #includer's 862 // directory. This cannot be based on CurDir, because each includer could be 863 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent 864 // include of "baz.h" should resolve to "whatever/foo/baz.h". 865 // This search is not done for <> headers. 866 if (!Includers.empty() && !isAngled && !NoCurDirSearch) { 867 SmallString<1024> TmpDir; 868 bool First = true; 869 for (const auto &IncluderAndDir : Includers) { 870 const FileEntry *Includer = IncluderAndDir.first; 871 872 // Concatenate the requested file onto the directory. 873 // FIXME: Portability. Filename concatenation should be in sys::Path. 874 TmpDir = IncluderAndDir.second->getName(); 875 TmpDir.push_back('/'); 876 TmpDir.append(Filename.begin(), Filename.end()); 877 878 // FIXME: We don't cache the result of getFileInfo across the call to 879 // getFileAndSuggestModule, because it's a reference to an element of 880 // a container that could be reallocated across this call. 881 // 882 // If we have no includer, that means we're processing a #include 883 // from a module build. We should treat this as a system header if we're 884 // building a [system] module. 885 bool IncluderIsSystemHeader = 886 Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User : 887 BuildSystemModule; 888 if (Optional<FileEntryRef> FE = getFileAndSuggestModule( 889 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader, 890 RequestingModule, SuggestedModule)) { 891 if (!Includer) { 892 assert(First && "only first includer can have no file"); 893 return FE; 894 } 895 896 // Leave CurDir unset. 897 // This file is a system header or C++ unfriendly if the old file is. 898 // 899 // Note that we only use one of FromHFI/ToHFI at once, due to potential 900 // reallocation of the underlying vector potentially making the first 901 // reference binding dangling. 902 HeaderFileInfo &FromHFI = getFileInfo(Includer); 903 unsigned DirInfo = FromHFI.DirInfo; 904 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader; 905 StringRef Framework = FromHFI.Framework; 906 907 HeaderFileInfo &ToHFI = getFileInfo(&FE->getFileEntry()); 908 ToHFI.DirInfo = DirInfo; 909 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader; 910 ToHFI.Framework = Framework; 911 912 if (SearchPath) { 913 StringRef SearchPathRef(IncluderAndDir.second->getName()); 914 SearchPath->clear(); 915 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); 916 } 917 if (RelativePath) { 918 RelativePath->clear(); 919 RelativePath->append(Filename.begin(), Filename.end()); 920 } 921 if (First) { 922 diagnoseFrameworkInclude(Diags, IncludeLoc, 923 IncluderAndDir.second->getName(), Filename, 924 &FE->getFileEntry()); 925 return FE; 926 } 927 928 // Otherwise, we found the path via MSVC header search rules. If 929 // -Wmsvc-include is enabled, we have to keep searching to see if we 930 // would've found this header in -I or -isystem directories. 931 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) { 932 return FE; 933 } else { 934 MSFE = FE; 935 if (SuggestedModule) { 936 MSSuggestedModule = *SuggestedModule; 937 *SuggestedModule = ModuleMap::KnownHeader(); 938 } 939 break; 940 } 941 } 942 First = false; 943 } 944 } 945 946 CurDir = nullptr; 947 948 // If this is a system #include, ignore the user #include locs. 949 unsigned i = isAngled ? AngledDirIdx : 0; 950 951 // If this is a #include_next request, start searching after the directory the 952 // file was found in. 953 if (FromDir) 954 i = FromDir-&SearchDirs[0]; 955 956 // Cache all of the lookups performed by this method. Many headers are 957 // multiply included, and the "pragma once" optimization prevents them from 958 // being relex/pp'd, but they would still have to search through a 959 // (potentially huge) series of SearchDirs to find it. 960 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename]; 961 962 // If the entry has been previously looked up, the first value will be 963 // non-zero. If the value is equal to i (the start point of our search), then 964 // this is a matching hit. 965 if (!SkipCache && CacheLookup.StartIdx == i+1) { 966 // Skip querying potentially lots of directories for this lookup. 967 i = CacheLookup.HitIdx; 968 if (CacheLookup.MappedName) { 969 Filename = CacheLookup.MappedName; 970 if (IsMapped) 971 *IsMapped = true; 972 } 973 } else { 974 // Otherwise, this is the first query, or the previous query didn't match 975 // our search start. We will fill in our found location below, so prime the 976 // start point value. 977 CacheLookup.reset(/*StartIdx=*/i+1); 978 } 979 980 SmallString<64> MappedName; 981 982 // Check each directory in sequence to see if it contains this file. 983 for (; i != SearchDirs.size(); ++i) { 984 bool InUserSpecifiedSystemFramework = false; 985 bool IsInHeaderMap = false; 986 bool IsFrameworkFoundInDir = false; 987 Optional<FileEntryRef> File = SearchDirs[i].LookupFile( 988 Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule, 989 SuggestedModule, InUserSpecifiedSystemFramework, IsFrameworkFoundInDir, 990 IsInHeaderMap, MappedName); 991 if (!MappedName.empty()) { 992 assert(IsInHeaderMap && "MappedName should come from a header map"); 993 CacheLookup.MappedName = 994 copyString(MappedName, LookupFileCache.getAllocator()); 995 } 996 if (IsMapped) 997 // A filename is mapped when a header map remapped it to a relative path 998 // used in subsequent header search or to an absolute path pointing to an 999 // existing file. 1000 *IsMapped |= (!MappedName.empty() || (IsInHeaderMap && File)); 1001 if (IsFrameworkFound) 1002 // Because we keep a filename remapped for subsequent search directory 1003 // lookups, ignore IsFrameworkFoundInDir after the first remapping and not 1004 // just for remapping in a current search directory. 1005 *IsFrameworkFound |= (IsFrameworkFoundInDir && !CacheLookup.MappedName); 1006 if (!File) 1007 continue; 1008 1009 CurDir = &SearchDirs[i]; 1010 1011 // This file is a system header or C++ unfriendly if the dir is. 1012 HeaderFileInfo &HFI = getFileInfo(&File->getFileEntry()); 1013 HFI.DirInfo = CurDir->getDirCharacteristic(); 1014 1015 // If the directory characteristic is User but this framework was 1016 // user-specified to be treated as a system framework, promote the 1017 // characteristic. 1018 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework) 1019 HFI.DirInfo = SrcMgr::C_System; 1020 1021 // If the filename matches a known system header prefix, override 1022 // whether the file is a system header. 1023 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) { 1024 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) { 1025 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System 1026 : SrcMgr::C_User; 1027 break; 1028 } 1029 } 1030 1031 // If this file is found in a header map and uses the framework style of 1032 // includes, then this header is part of a framework we're building. 1033 if (CurDir->isHeaderMap() && isAngled) { 1034 size_t SlashPos = Filename.find('/'); 1035 if (SlashPos != StringRef::npos) 1036 HFI.Framework = 1037 getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos)); 1038 if (CurDir->isIndexHeaderMap()) 1039 HFI.IndexHeaderMapHeader = 1; 1040 } 1041 1042 if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr, 1043 &File->getFileEntry(), IncludeLoc)) { 1044 if (SuggestedModule) 1045 *SuggestedModule = MSSuggestedModule; 1046 return MSFE; 1047 } 1048 1049 bool FoundByHeaderMap = !IsMapped ? false : *IsMapped; 1050 if (!Includers.empty()) 1051 diagnoseFrameworkInclude( 1052 Diags, IncludeLoc, Includers.front().second->getName(), Filename, 1053 &File->getFileEntry(), isAngled, FoundByHeaderMap); 1054 1055 // Remember this location for the next lookup we do. 1056 cacheLookupSuccess(CacheLookup, i, IncludeLoc); 1057 return File; 1058 } 1059 1060 // If we are including a file with a quoted include "foo.h" from inside 1061 // a header in a framework that is currently being built, and we couldn't 1062 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where 1063 // "Foo" is the name of the framework in which the including header was found. 1064 if (!Includers.empty() && Includers.front().first && !isAngled && 1065 !Filename.contains('/')) { 1066 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first); 1067 if (IncludingHFI.IndexHeaderMapHeader) { 1068 SmallString<128> ScratchFilename; 1069 ScratchFilename += IncludingHFI.Framework; 1070 ScratchFilename += '/'; 1071 ScratchFilename += Filename; 1072 1073 Optional<FileEntryRef> File = LookupFile( 1074 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir, 1075 Includers.front(), SearchPath, RelativePath, RequestingModule, 1076 SuggestedModule, IsMapped, /*IsFrameworkFound=*/nullptr); 1077 1078 if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr, 1079 File ? &File->getFileEntry() : nullptr, 1080 IncludeLoc)) { 1081 if (SuggestedModule) 1082 *SuggestedModule = MSSuggestedModule; 1083 return MSFE; 1084 } 1085 1086 cacheLookupSuccess(LookupFileCache[Filename], 1087 LookupFileCache[ScratchFilename].HitIdx, IncludeLoc); 1088 // FIXME: SuggestedModule. 1089 return File; 1090 } 1091 } 1092 1093 if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr, 1094 nullptr, IncludeLoc)) { 1095 if (SuggestedModule) 1096 *SuggestedModule = MSSuggestedModule; 1097 return MSFE; 1098 } 1099 1100 // Otherwise, didn't find it. Remember we didn't find this. 1101 CacheLookup.HitIdx = SearchDirs.size(); 1102 return None; 1103 } 1104 1105 /// LookupSubframeworkHeader - Look up a subframework for the specified 1106 /// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from 1107 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox 1108 /// is a subframework within Carbon.framework. If so, return the FileEntry 1109 /// for the designated file, otherwise return null. 1110 Optional<FileEntryRef> HeaderSearch::LookupSubframeworkHeader( 1111 StringRef Filename, const FileEntry *ContextFileEnt, 1112 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, 1113 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule) { 1114 assert(ContextFileEnt && "No context file?"); 1115 1116 // Framework names must have a '/' in the filename. Find it. 1117 // FIXME: Should we permit '\' on Windows? 1118 size_t SlashPos = Filename.find('/'); 1119 if (SlashPos == StringRef::npos) 1120 return None; 1121 1122 // Look up the base framework name of the ContextFileEnt. 1123 StringRef ContextName = ContextFileEnt->getName(); 1124 1125 // If the context info wasn't a framework, couldn't be a subframework. 1126 const unsigned DotFrameworkLen = 10; 1127 auto FrameworkPos = ContextName.find(".framework"); 1128 if (FrameworkPos == StringRef::npos || 1129 (ContextName[FrameworkPos + DotFrameworkLen] != '/' && 1130 ContextName[FrameworkPos + DotFrameworkLen] != '\\')) 1131 return None; 1132 1133 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() + 1134 FrameworkPos + 1135 DotFrameworkLen + 1); 1136 1137 // Append Frameworks/HIToolbox.framework/ 1138 FrameworkName += "Frameworks/"; 1139 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos); 1140 FrameworkName += ".framework/"; 1141 1142 auto &CacheLookup = 1143 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos), 1144 FrameworkCacheEntry())).first; 1145 1146 // Some other location? 1147 if (CacheLookup.second.Directory && 1148 CacheLookup.first().size() == FrameworkName.size() && 1149 memcmp(CacheLookup.first().data(), &FrameworkName[0], 1150 CacheLookup.first().size()) != 0) 1151 return None; 1152 1153 // Cache subframework. 1154 if (!CacheLookup.second.Directory) { 1155 ++NumSubFrameworkLookups; 1156 1157 // If the framework dir doesn't exist, we fail. 1158 auto Dir = FileMgr.getDirectory(FrameworkName); 1159 if (!Dir) 1160 return None; 1161 1162 // Otherwise, if it does, remember that this is the right direntry for this 1163 // framework. 1164 CacheLookup.second.Directory = *Dir; 1165 } 1166 1167 1168 if (RelativePath) { 1169 RelativePath->clear(); 1170 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end()); 1171 } 1172 1173 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h" 1174 SmallString<1024> HeadersFilename(FrameworkName); 1175 HeadersFilename += "Headers/"; 1176 if (SearchPath) { 1177 SearchPath->clear(); 1178 // Without trailing '/'. 1179 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1); 1180 } 1181 1182 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end()); 1183 auto File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true); 1184 if (!File) { 1185 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h" 1186 HeadersFilename = FrameworkName; 1187 HeadersFilename += "PrivateHeaders/"; 1188 if (SearchPath) { 1189 SearchPath->clear(); 1190 // Without trailing '/'. 1191 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1); 1192 } 1193 1194 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end()); 1195 File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true); 1196 1197 if (!File) 1198 return None; 1199 } 1200 1201 // This file is a system header or C++ unfriendly if the old file is. 1202 // 1203 // Note that the temporary 'DirInfo' is required here, as either call to 1204 // getFileInfo could resize the vector and we don't want to rely on order 1205 // of evaluation. 1206 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo; 1207 getFileInfo(&File->getFileEntry()).DirInfo = DirInfo; 1208 1209 FrameworkName.pop_back(); // remove the trailing '/' 1210 if (!findUsableModuleForFrameworkHeader(&File->getFileEntry(), FrameworkName, 1211 RequestingModule, SuggestedModule, 1212 /*IsSystem*/ false)) 1213 return None; 1214 1215 return *File; 1216 } 1217 1218 //===----------------------------------------------------------------------===// 1219 // File Info Management. 1220 //===----------------------------------------------------------------------===// 1221 1222 /// Merge the header file info provided by \p OtherHFI into the current 1223 /// header file info (\p HFI) 1224 static void mergeHeaderFileInfo(HeaderFileInfo &HFI, 1225 const HeaderFileInfo &OtherHFI) { 1226 assert(OtherHFI.External && "expected to merge external HFI"); 1227 1228 HFI.isImport |= OtherHFI.isImport; 1229 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce; 1230 HFI.isModuleHeader |= OtherHFI.isModuleHeader; 1231 HFI.NumIncludes += OtherHFI.NumIncludes; 1232 1233 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) { 1234 HFI.ControllingMacro = OtherHFI.ControllingMacro; 1235 HFI.ControllingMacroID = OtherHFI.ControllingMacroID; 1236 } 1237 1238 HFI.DirInfo = OtherHFI.DirInfo; 1239 HFI.External = (!HFI.IsValid || HFI.External); 1240 HFI.IsValid = true; 1241 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader; 1242 1243 if (HFI.Framework.empty()) 1244 HFI.Framework = OtherHFI.Framework; 1245 } 1246 1247 /// getFileInfo - Return the HeaderFileInfo structure for the specified 1248 /// FileEntry. 1249 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) { 1250 if (FE->getUID() >= FileInfo.size()) 1251 FileInfo.resize(FE->getUID() + 1); 1252 1253 HeaderFileInfo *HFI = &FileInfo[FE->getUID()]; 1254 // FIXME: Use a generation count to check whether this is really up to date. 1255 if (ExternalSource && !HFI->Resolved) { 1256 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE); 1257 if (ExternalHFI.IsValid) { 1258 HFI->Resolved = true; 1259 if (ExternalHFI.External) 1260 mergeHeaderFileInfo(*HFI, ExternalHFI); 1261 } 1262 } 1263 1264 HFI->IsValid = true; 1265 // We have local information about this header file, so it's no longer 1266 // strictly external. 1267 HFI->External = false; 1268 return *HFI; 1269 } 1270 1271 const HeaderFileInfo * 1272 HeaderSearch::getExistingFileInfo(const FileEntry *FE, 1273 bool WantExternal) const { 1274 // If we have an external source, ensure we have the latest information. 1275 // FIXME: Use a generation count to check whether this is really up to date. 1276 HeaderFileInfo *HFI; 1277 if (ExternalSource) { 1278 if (FE->getUID() >= FileInfo.size()) { 1279 if (!WantExternal) 1280 return nullptr; 1281 FileInfo.resize(FE->getUID() + 1); 1282 } 1283 1284 HFI = &FileInfo[FE->getUID()]; 1285 if (!WantExternal && (!HFI->IsValid || HFI->External)) 1286 return nullptr; 1287 if (!HFI->Resolved) { 1288 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE); 1289 if (ExternalHFI.IsValid) { 1290 HFI->Resolved = true; 1291 if (ExternalHFI.External) 1292 mergeHeaderFileInfo(*HFI, ExternalHFI); 1293 } 1294 } 1295 } else if (FE->getUID() >= FileInfo.size()) { 1296 return nullptr; 1297 } else { 1298 HFI = &FileInfo[FE->getUID()]; 1299 } 1300 1301 if (!HFI->IsValid || (HFI->External && !WantExternal)) 1302 return nullptr; 1303 1304 return HFI; 1305 } 1306 1307 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) { 1308 // Check if we've entered this file and found an include guard or #pragma 1309 // once. Note that we dor't check for #import, because that's not a property 1310 // of the file itself. 1311 if (auto *HFI = getExistingFileInfo(File)) 1312 return HFI->isPragmaOnce || HFI->ControllingMacro || 1313 HFI->ControllingMacroID; 1314 return false; 1315 } 1316 1317 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE, 1318 ModuleMap::ModuleHeaderRole Role, 1319 bool isCompilingModuleHeader) { 1320 bool isModularHeader = !(Role & ModuleMap::TextualHeader); 1321 1322 // Don't mark the file info as non-external if there's nothing to change. 1323 if (!isCompilingModuleHeader) { 1324 if (!isModularHeader) 1325 return; 1326 auto *HFI = getExistingFileInfo(FE); 1327 if (HFI && HFI->isModuleHeader) 1328 return; 1329 } 1330 1331 auto &HFI = getFileInfo(FE); 1332 HFI.isModuleHeader |= isModularHeader; 1333 HFI.isCompilingModuleHeader |= isCompilingModuleHeader; 1334 } 1335 1336 bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP, 1337 const FileEntry *File, bool isImport, 1338 bool ModulesEnabled, Module *M, 1339 bool &IsFirstIncludeOfFile) { 1340 ++NumIncluded; // Count # of attempted #includes. 1341 1342 IsFirstIncludeOfFile = false; 1343 1344 // Get information about this file. 1345 HeaderFileInfo &FileInfo = getFileInfo(File); 1346 1347 // FIXME: this is a workaround for the lack of proper modules-aware support 1348 // for #import / #pragma once 1349 auto TryEnterImported = [&]() -> bool { 1350 if (!ModulesEnabled) 1351 return false; 1352 // Ensure FileInfo bits are up to date. 1353 ModMap.resolveHeaderDirectives(File); 1354 // Modules with builtins are special; multiple modules use builtins as 1355 // modular headers, example: 1356 // 1357 // module stddef { header "stddef.h" export * } 1358 // 1359 // After module map parsing, this expands to: 1360 // 1361 // module stddef { 1362 // header "/path_to_builtin_dirs/stddef.h" 1363 // textual "stddef.h" 1364 // } 1365 // 1366 // It's common that libc++ and system modules will both define such 1367 // submodules. Make sure cached results for a builtin header won't 1368 // prevent other builtin modules from potentially entering the builtin 1369 // header. Note that builtins are header guarded and the decision to 1370 // actually enter them is postponed to the controlling macros logic below. 1371 bool TryEnterHdr = false; 1372 if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader) 1373 TryEnterHdr = ModMap.isBuiltinHeader(File); 1374 1375 // Textual headers can be #imported from different modules. Since ObjC 1376 // headers find in the wild might rely only on #import and do not contain 1377 // controlling macros, be conservative and only try to enter textual headers 1378 // if such macro is present. 1379 if (!FileInfo.isModuleHeader && 1380 FileInfo.getControllingMacro(ExternalLookup)) 1381 TryEnterHdr = true; 1382 return TryEnterHdr; 1383 }; 1384 1385 // If this is a #import directive, check that we have not already imported 1386 // this header. 1387 if (isImport) { 1388 // If this has already been imported, don't import it again. 1389 FileInfo.isImport = true; 1390 1391 // Has this already been #import'ed or #include'd? 1392 if (FileInfo.NumIncludes && !TryEnterImported()) 1393 return false; 1394 } else { 1395 // Otherwise, if this is a #include of a file that was previously #import'd 1396 // or if this is the second #include of a #pragma once file, ignore it. 1397 if ((FileInfo.isPragmaOnce || FileInfo.isImport) && !TryEnterImported()) 1398 return false; 1399 } 1400 1401 // Next, check to see if the file is wrapped with #ifndef guards. If so, and 1402 // if the macro that guards it is defined, we know the #include has no effect. 1403 if (const IdentifierInfo *ControllingMacro 1404 = FileInfo.getControllingMacro(ExternalLookup)) { 1405 // If the header corresponds to a module, check whether the macro is already 1406 // defined in that module rather than checking in the current set of visible 1407 // modules. 1408 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M) 1409 : PP.isMacroDefined(ControllingMacro)) { 1410 ++NumMultiIncludeFileOptzn; 1411 return false; 1412 } 1413 } 1414 1415 // Increment the number of times this file has been included. 1416 ++FileInfo.NumIncludes; 1417 1418 IsFirstIncludeOfFile = FileInfo.NumIncludes == 1; 1419 1420 return true; 1421 } 1422 1423 size_t HeaderSearch::getTotalMemory() const { 1424 return SearchDirs.capacity() 1425 + llvm::capacity_in_bytes(FileInfo) 1426 + llvm::capacity_in_bytes(HeaderMaps) 1427 + LookupFileCache.getAllocator().getTotalMemory() 1428 + FrameworkMap.getAllocator().getTotalMemory(); 1429 } 1430 1431 Optional<unsigned> HeaderSearch::searchDirIdx(const DirectoryLookup &DL) const { 1432 for (unsigned I = 0; I < SearchDirs.size(); ++I) 1433 if (&SearchDirs[I] == &DL) 1434 return I; 1435 return None; 1436 } 1437 1438 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) { 1439 return FrameworkNames.insert(Framework).first->first(); 1440 } 1441 1442 bool HeaderSearch::hasModuleMap(StringRef FileName, 1443 const DirectoryEntry *Root, 1444 bool IsSystem) { 1445 if (!HSOpts->ImplicitModuleMaps) 1446 return false; 1447 1448 SmallVector<const DirectoryEntry *, 2> FixUpDirectories; 1449 1450 StringRef DirName = FileName; 1451 do { 1452 // Get the parent directory name. 1453 DirName = llvm::sys::path::parent_path(DirName); 1454 if (DirName.empty()) 1455 return false; 1456 1457 // Determine whether this directory exists. 1458 auto Dir = FileMgr.getDirectory(DirName); 1459 if (!Dir) 1460 return false; 1461 1462 // Try to load the module map file in this directory. 1463 switch (loadModuleMapFile(*Dir, IsSystem, 1464 llvm::sys::path::extension((*Dir)->getName()) == 1465 ".framework")) { 1466 case LMM_NewlyLoaded: 1467 case LMM_AlreadyLoaded: 1468 // Success. All of the directories we stepped through inherit this module 1469 // map file. 1470 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I) 1471 DirectoryHasModuleMap[FixUpDirectories[I]] = true; 1472 return true; 1473 1474 case LMM_NoDirectory: 1475 case LMM_InvalidModuleMap: 1476 break; 1477 } 1478 1479 // If we hit the top of our search, we're done. 1480 if (*Dir == Root) 1481 return false; 1482 1483 // Keep track of all of the directories we checked, so we can mark them as 1484 // having module maps if we eventually do find a module map. 1485 FixUpDirectories.push_back(*Dir); 1486 } while (true); 1487 } 1488 1489 ModuleMap::KnownHeader 1490 HeaderSearch::findModuleForHeader(const FileEntry *File, 1491 bool AllowTextual) const { 1492 if (ExternalSource) { 1493 // Make sure the external source has handled header info about this file, 1494 // which includes whether the file is part of a module. 1495 (void)getExistingFileInfo(File); 1496 } 1497 return ModMap.findModuleForHeader(File, AllowTextual); 1498 } 1499 1500 ArrayRef<ModuleMap::KnownHeader> 1501 HeaderSearch::findAllModulesForHeader(const FileEntry *File) const { 1502 if (ExternalSource) { 1503 // Make sure the external source has handled header info about this file, 1504 // which includes whether the file is part of a module. 1505 (void)getExistingFileInfo(File); 1506 } 1507 return ModMap.findAllModulesForHeader(File); 1508 } 1509 1510 static bool suggestModule(HeaderSearch &HS, const FileEntry *File, 1511 Module *RequestingModule, 1512 ModuleMap::KnownHeader *SuggestedModule) { 1513 ModuleMap::KnownHeader Module = 1514 HS.findModuleForHeader(File, /*AllowTextual*/true); 1515 1516 // If this module specifies [no_undeclared_includes], we cannot find any 1517 // file that's in a non-dependency module. 1518 if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) { 1519 HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/ false); 1520 if (!RequestingModule->directlyUses(Module.getModule())) { 1521 // Builtin headers are a special case. Multiple modules can use the same 1522 // builtin as a modular header (see also comment in 1523 // ShouldEnterIncludeFile()), so the builtin header may have been 1524 // "claimed" by an unrelated module. This shouldn't prevent us from 1525 // including the builtin header textually in this module. 1526 if (HS.getModuleMap().isBuiltinHeader(File)) { 1527 if (SuggestedModule) 1528 *SuggestedModule = ModuleMap::KnownHeader(); 1529 return true; 1530 } 1531 return false; 1532 } 1533 } 1534 1535 if (SuggestedModule) 1536 *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader) 1537 ? ModuleMap::KnownHeader() 1538 : Module; 1539 1540 return true; 1541 } 1542 1543 bool HeaderSearch::findUsableModuleForHeader( 1544 const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule, 1545 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) { 1546 if (File && needModuleLookup(RequestingModule, SuggestedModule)) { 1547 // If there is a module that corresponds to this header, suggest it. 1548 hasModuleMap(File->getName(), Root, IsSystemHeaderDir); 1549 return suggestModule(*this, File, RequestingModule, SuggestedModule); 1550 } 1551 return true; 1552 } 1553 1554 bool HeaderSearch::findUsableModuleForFrameworkHeader( 1555 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule, 1556 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) { 1557 // If we're supposed to suggest a module, look for one now. 1558 if (needModuleLookup(RequestingModule, SuggestedModule)) { 1559 // Find the top-level framework based on this framework. 1560 SmallVector<std::string, 4> SubmodulePath; 1561 const DirectoryEntry *TopFrameworkDir 1562 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath); 1563 1564 // Determine the name of the top-level framework. 1565 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName()); 1566 1567 // Load this framework module. If that succeeds, find the suggested module 1568 // for this header, if any. 1569 loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework); 1570 1571 // FIXME: This can find a module not part of ModuleName, which is 1572 // important so that we're consistent about whether this header 1573 // corresponds to a module. Possibly we should lock down framework modules 1574 // so that this is not possible. 1575 return suggestModule(*this, File, RequestingModule, SuggestedModule); 1576 } 1577 return true; 1578 } 1579 1580 static const FileEntry *getPrivateModuleMap(const FileEntry *File, 1581 FileManager &FileMgr) { 1582 StringRef Filename = llvm::sys::path::filename(File->getName()); 1583 SmallString<128> PrivateFilename(File->getDir()->getName()); 1584 if (Filename == "module.map") 1585 llvm::sys::path::append(PrivateFilename, "module_private.map"); 1586 else if (Filename == "module.modulemap") 1587 llvm::sys::path::append(PrivateFilename, "module.private.modulemap"); 1588 else 1589 return nullptr; 1590 if (auto File = FileMgr.getFile(PrivateFilename)) 1591 return *File; 1592 return nullptr; 1593 } 1594 1595 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem, 1596 FileID ID, unsigned *Offset, 1597 StringRef OriginalModuleMapFile) { 1598 // Find the directory for the module. For frameworks, that may require going 1599 // up from the 'Modules' directory. 1600 const DirectoryEntry *Dir = nullptr; 1601 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) { 1602 if (auto DirOrErr = FileMgr.getDirectory(".")) 1603 Dir = *DirOrErr; 1604 } else { 1605 if (!OriginalModuleMapFile.empty()) { 1606 // We're building a preprocessed module map. Find or invent the directory 1607 // that it originally occupied. 1608 auto DirOrErr = FileMgr.getDirectory( 1609 llvm::sys::path::parent_path(OriginalModuleMapFile)); 1610 if (DirOrErr) { 1611 Dir = *DirOrErr; 1612 } else { 1613 auto *FakeFile = FileMgr.getVirtualFile(OriginalModuleMapFile, 0, 0); 1614 Dir = FakeFile->getDir(); 1615 } 1616 } else { 1617 Dir = File->getDir(); 1618 } 1619 1620 StringRef DirName(Dir->getName()); 1621 if (llvm::sys::path::filename(DirName) == "Modules") { 1622 DirName = llvm::sys::path::parent_path(DirName); 1623 if (DirName.endswith(".framework")) 1624 if (auto DirOrErr = FileMgr.getDirectory(DirName)) 1625 Dir = *DirOrErr; 1626 // FIXME: This assert can fail if there's a race between the above check 1627 // and the removal of the directory. 1628 assert(Dir && "parent must exist"); 1629 } 1630 } 1631 1632 switch (loadModuleMapFileImpl(File, IsSystem, Dir, ID, Offset)) { 1633 case LMM_AlreadyLoaded: 1634 case LMM_NewlyLoaded: 1635 return false; 1636 case LMM_NoDirectory: 1637 case LMM_InvalidModuleMap: 1638 return true; 1639 } 1640 llvm_unreachable("Unknown load module map result"); 1641 } 1642 1643 HeaderSearch::LoadModuleMapResult 1644 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem, 1645 const DirectoryEntry *Dir, FileID ID, 1646 unsigned *Offset) { 1647 assert(File && "expected FileEntry"); 1648 1649 // Check whether we've already loaded this module map, and mark it as being 1650 // loaded in case we recursively try to load it from itself. 1651 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true)); 1652 if (!AddResult.second) 1653 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap; 1654 1655 if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) { 1656 LoadedModuleMaps[File] = false; 1657 return LMM_InvalidModuleMap; 1658 } 1659 1660 // Try to load a corresponding private module map. 1661 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) { 1662 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) { 1663 LoadedModuleMaps[File] = false; 1664 return LMM_InvalidModuleMap; 1665 } 1666 } 1667 1668 // This directory has a module map. 1669 return LMM_NewlyLoaded; 1670 } 1671 1672 const FileEntry * 1673 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) { 1674 if (!HSOpts->ImplicitModuleMaps) 1675 return nullptr; 1676 // For frameworks, the preferred spelling is Modules/module.modulemap, but 1677 // module.map at the framework root is also accepted. 1678 SmallString<128> ModuleMapFileName(Dir->getName()); 1679 if (IsFramework) 1680 llvm::sys::path::append(ModuleMapFileName, "Modules"); 1681 llvm::sys::path::append(ModuleMapFileName, "module.modulemap"); 1682 if (auto F = FileMgr.getFile(ModuleMapFileName)) 1683 return *F; 1684 1685 // Continue to allow module.map 1686 ModuleMapFileName = Dir->getName(); 1687 llvm::sys::path::append(ModuleMapFileName, "module.map"); 1688 if (auto F = FileMgr.getFile(ModuleMapFileName)) 1689 return *F; 1690 1691 // For frameworks, allow to have a private module map with a preferred 1692 // spelling when a public module map is absent. 1693 if (IsFramework) { 1694 ModuleMapFileName = Dir->getName(); 1695 llvm::sys::path::append(ModuleMapFileName, "Modules", 1696 "module.private.modulemap"); 1697 if (auto F = FileMgr.getFile(ModuleMapFileName)) 1698 return *F; 1699 } 1700 return nullptr; 1701 } 1702 1703 Module *HeaderSearch::loadFrameworkModule(StringRef Name, 1704 const DirectoryEntry *Dir, 1705 bool IsSystem) { 1706 if (Module *Module = ModMap.findModule(Name)) 1707 return Module; 1708 1709 // Try to load a module map file. 1710 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) { 1711 case LMM_InvalidModuleMap: 1712 // Try to infer a module map from the framework directory. 1713 if (HSOpts->ImplicitModuleMaps) 1714 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr); 1715 break; 1716 1717 case LMM_AlreadyLoaded: 1718 case LMM_NoDirectory: 1719 return nullptr; 1720 1721 case LMM_NewlyLoaded: 1722 break; 1723 } 1724 1725 return ModMap.findModule(Name); 1726 } 1727 1728 HeaderSearch::LoadModuleMapResult 1729 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem, 1730 bool IsFramework) { 1731 if (auto Dir = FileMgr.getDirectory(DirName)) 1732 return loadModuleMapFile(*Dir, IsSystem, IsFramework); 1733 1734 return LMM_NoDirectory; 1735 } 1736 1737 HeaderSearch::LoadModuleMapResult 1738 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem, 1739 bool IsFramework) { 1740 auto KnownDir = DirectoryHasModuleMap.find(Dir); 1741 if (KnownDir != DirectoryHasModuleMap.end()) 1742 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap; 1743 1744 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) { 1745 LoadModuleMapResult Result = 1746 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir); 1747 // Add Dir explicitly in case ModuleMapFile is in a subdirectory. 1748 // E.g. Foo.framework/Modules/module.modulemap 1749 // ^Dir ^ModuleMapFile 1750 if (Result == LMM_NewlyLoaded) 1751 DirectoryHasModuleMap[Dir] = true; 1752 else if (Result == LMM_InvalidModuleMap) 1753 DirectoryHasModuleMap[Dir] = false; 1754 return Result; 1755 } 1756 return LMM_InvalidModuleMap; 1757 } 1758 1759 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) { 1760 Modules.clear(); 1761 1762 if (HSOpts->ImplicitModuleMaps) { 1763 // Load module maps for each of the header search directories. 1764 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) { 1765 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory(); 1766 if (SearchDirs[Idx].isFramework()) { 1767 std::error_code EC; 1768 SmallString<128> DirNative; 1769 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(), 1770 DirNative); 1771 1772 // Search each of the ".framework" directories to load them as modules. 1773 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem(); 1774 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), 1775 DirEnd; 1776 Dir != DirEnd && !EC; Dir.increment(EC)) { 1777 if (llvm::sys::path::extension(Dir->path()) != ".framework") 1778 continue; 1779 1780 auto FrameworkDir = 1781 FileMgr.getDirectory(Dir->path()); 1782 if (!FrameworkDir) 1783 continue; 1784 1785 // Load this framework module. 1786 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir, 1787 IsSystem); 1788 } 1789 continue; 1790 } 1791 1792 // FIXME: Deal with header maps. 1793 if (SearchDirs[Idx].isHeaderMap()) 1794 continue; 1795 1796 // Try to load a module map file for the search directory. 1797 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem, 1798 /*IsFramework*/ false); 1799 1800 // Try to load module map files for immediate subdirectories of this 1801 // search directory. 1802 loadSubdirectoryModuleMaps(SearchDirs[Idx]); 1803 } 1804 } 1805 1806 // Populate the list of modules. 1807 llvm::transform(ModMap.modules(), std::back_inserter(Modules), 1808 [](const auto &NameAndMod) { return NameAndMod.second; }); 1809 } 1810 1811 void HeaderSearch::loadTopLevelSystemModules() { 1812 if (!HSOpts->ImplicitModuleMaps) 1813 return; 1814 1815 // Load module maps for each of the header search directories. 1816 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) { 1817 // We only care about normal header directories. 1818 if (!SearchDirs[Idx].isNormalDir()) { 1819 continue; 1820 } 1821 1822 // Try to load a module map file for the search directory. 1823 loadModuleMapFile(SearchDirs[Idx].getDir(), 1824 SearchDirs[Idx].isSystemHeaderDirectory(), 1825 SearchDirs[Idx].isFramework()); 1826 } 1827 } 1828 1829 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) { 1830 assert(HSOpts->ImplicitModuleMaps && 1831 "Should not be loading subdirectory module maps"); 1832 1833 if (SearchDir.haveSearchedAllModuleMaps()) 1834 return; 1835 1836 std::error_code EC; 1837 SmallString<128> Dir = SearchDir.getDir()->getName(); 1838 FileMgr.makeAbsolutePath(Dir); 1839 SmallString<128> DirNative; 1840 llvm::sys::path::native(Dir, DirNative); 1841 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem(); 1842 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; 1843 Dir != DirEnd && !EC; Dir.increment(EC)) { 1844 bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework"; 1845 if (IsFramework == SearchDir.isFramework()) 1846 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(), 1847 SearchDir.isFramework()); 1848 } 1849 1850 SearchDir.setSearchedAllModuleMaps(true); 1851 } 1852 1853 std::string HeaderSearch::suggestPathToFileForDiagnostics( 1854 const FileEntry *File, llvm::StringRef MainFile, bool *IsSystem) { 1855 // FIXME: We assume that the path name currently cached in the FileEntry is 1856 // the most appropriate one for this analysis (and that it's spelled the 1857 // same way as the corresponding header search path). 1858 return suggestPathToFileForDiagnostics(File->getName(), /*WorkingDir=*/"", 1859 MainFile, IsSystem); 1860 } 1861 1862 std::string HeaderSearch::suggestPathToFileForDiagnostics( 1863 llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile, 1864 bool *IsSystem) { 1865 using namespace llvm::sys; 1866 1867 unsigned BestPrefixLength = 0; 1868 // Checks whether Dir and File shares a common prefix, if they do and that's 1869 // the longest prefix we've seen so for it returns true and updates the 1870 // BestPrefixLength accordingly. 1871 auto CheckDir = [&](llvm::StringRef Dir) -> bool { 1872 llvm::SmallString<32> DirPath(Dir.begin(), Dir.end()); 1873 if (!WorkingDir.empty() && !path::is_absolute(Dir)) 1874 fs::make_absolute(WorkingDir, DirPath); 1875 path::remove_dots(DirPath, /*remove_dot_dot=*/true); 1876 Dir = DirPath; 1877 for (auto NI = path::begin(File), NE = path::end(File), 1878 DI = path::begin(Dir), DE = path::end(Dir); 1879 /*termination condition in loop*/; ++NI, ++DI) { 1880 // '.' components in File are ignored. 1881 while (NI != NE && *NI == ".") 1882 ++NI; 1883 if (NI == NE) 1884 break; 1885 1886 // '.' components in Dir are ignored. 1887 while (DI != DE && *DI == ".") 1888 ++DI; 1889 if (DI == DE) { 1890 // Dir is a prefix of File, up to '.' components and choice of path 1891 // separators. 1892 unsigned PrefixLength = NI - path::begin(File); 1893 if (PrefixLength > BestPrefixLength) { 1894 BestPrefixLength = PrefixLength; 1895 return true; 1896 } 1897 break; 1898 } 1899 1900 // Consider all path separators equal. 1901 if (NI->size() == 1 && DI->size() == 1 && 1902 path::is_separator(NI->front()) && path::is_separator(DI->front())) 1903 continue; 1904 1905 if (*NI != *DI) 1906 break; 1907 } 1908 return false; 1909 }; 1910 1911 for (unsigned I = 0; I != SearchDirs.size(); ++I) { 1912 // FIXME: Support this search within frameworks. 1913 if (!SearchDirs[I].isNormalDir()) 1914 continue; 1915 1916 StringRef Dir = SearchDirs[I].getDir()->getName(); 1917 if (CheckDir(Dir) && IsSystem) 1918 *IsSystem = BestPrefixLength ? I >= SystemDirIdx : false; 1919 } 1920 1921 // Try to shorten include path using TUs directory, if we couldn't find any 1922 // suitable prefix in include search paths. 1923 if (!BestPrefixLength && CheckDir(path::parent_path(MainFile)) && IsSystem) 1924 *IsSystem = false; 1925 1926 // Try resolving resulting filename via reverse search in header maps, 1927 // key from header name is user prefered name for the include file. 1928 StringRef Filename = File.drop_front(BestPrefixLength); 1929 for (unsigned I = 0; I != SearchDirs.size(); ++I) { 1930 if (!SearchDirs[I].isHeaderMap()) 1931 continue; 1932 1933 StringRef SpelledFilename = 1934 SearchDirs[I].getHeaderMap()->reverseLookupFilename(Filename); 1935 if (!SpelledFilename.empty()) { 1936 Filename = SpelledFilename; 1937 break; 1938 } 1939 } 1940 return path::convert_to_slash(Filename); 1941 } 1942