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