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