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