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