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