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