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/Lex/HeaderMap.h"
16 #include "clang/Lex/Lexer.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/FileManager.h"
19 #include "clang/Basic/IdentifierTable.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/Support/Capacity.h"
24 #include <cstdio>
25 using namespace clang;
26 
27 const IdentifierInfo *
28 HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
29   if (ControllingMacro)
30     return ControllingMacro;
31 
32   if (!ControllingMacroID || !External)
33     return 0;
34 
35   ControllingMacro = External->GetIdentifier(ControllingMacroID);
36   return ControllingMacro;
37 }
38 
39 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
40 
41 HeaderSearch::HeaderSearch(FileManager &FM, DiagnosticsEngine &Diags,
42                            const LangOptions &LangOpts,
43                            const TargetInfo *Target)
44   : FileMgr(FM), Diags(Diags), FrameworkMap(64),
45     ModMap(FileMgr, *Diags.getClient(), LangOpts, Target)
46 {
47   AngledDirIdx = 0;
48   SystemDirIdx = 0;
49   NoCurDirSearch = false;
50 
51   ExternalLookup = 0;
52   ExternalSource = 0;
53   NumIncluded = 0;
54   NumMultiIncludeFileOptzn = 0;
55   NumFrameworkLookups = NumSubFrameworkLookups = 0;
56 }
57 
58 HeaderSearch::~HeaderSearch() {
59   // Delete headermaps.
60   for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
61     delete HeaderMaps[i].second;
62 }
63 
64 void HeaderSearch::PrintStats() {
65   fprintf(stderr, "\n*** HeaderSearch Stats:\n");
66   fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
67   unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
68   for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
69     NumOnceOnlyFiles += FileInfo[i].isImport;
70     if (MaxNumIncludes < FileInfo[i].NumIncludes)
71       MaxNumIncludes = FileInfo[i].NumIncludes;
72     NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
73   }
74   fprintf(stderr, "  %d #import/#pragma once files.\n", NumOnceOnlyFiles);
75   fprintf(stderr, "  %d included exactly once.\n", NumSingleIncludedFiles);
76   fprintf(stderr, "  %d max times a file is included.\n", MaxNumIncludes);
77 
78   fprintf(stderr, "  %d #include/#include_next/#import.\n", NumIncluded);
79   fprintf(stderr, "    %d #includes skipped due to"
80           " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
81 
82   fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
83   fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
84 }
85 
86 /// CreateHeaderMap - This method returns a HeaderMap for the specified
87 /// FileEntry, uniquing them through the the 'HeaderMaps' datastructure.
88 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
89   // We expect the number of headermaps to be small, and almost always empty.
90   // If it ever grows, use of a linear search should be re-evaluated.
91   if (!HeaderMaps.empty()) {
92     for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
93       // Pointer equality comparison of FileEntries works because they are
94       // already uniqued by inode.
95       if (HeaderMaps[i].first == FE)
96         return HeaderMaps[i].second;
97   }
98 
99   if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
100     HeaderMaps.push_back(std::make_pair(FE, HM));
101     return HM;
102   }
103 
104   return 0;
105 }
106 
107 std::string HeaderSearch::getModuleFileName(Module *Module) {
108   // If we don't have a module cache path, we can't do anything.
109   if (ModuleCachePath.empty())
110     return std::string();
111 
112 
113   SmallString<256> Result(ModuleCachePath);
114   llvm::sys::path::append(Result, Module->getTopLevelModule()->Name + ".pcm");
115   return Result.str().str();
116 }
117 
118 std::string HeaderSearch::getModuleFileName(StringRef ModuleName) {
119   // If we don't have a module cache path, we can't do anything.
120   if (ModuleCachePath.empty())
121     return std::string();
122 
123 
124   SmallString<256> Result(ModuleCachePath);
125   llvm::sys::path::append(Result, ModuleName + ".pcm");
126   return Result.str().str();
127 }
128 
129 Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
130   // Look in the module map to determine if there is a module by this name.
131   Module *Module = ModMap.findModule(ModuleName);
132   if (Module || !AllowSearch)
133     return Module;
134 
135   // Look through the various header search paths to load any avai;able module
136   // maps, searching for a module map that describes this module.
137   for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
138     if (SearchDirs[Idx].isFramework()) {
139       // Search for or infer a module map for a framework.
140       SmallString<128> FrameworkDirName;
141       FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
142       llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
143       if (const DirectoryEntry *FrameworkDir
144             = FileMgr.getDirectory(FrameworkDirName)) {
145         bool IsSystem
146           = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
147         Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
148         if (Module)
149           break;
150       }
151     }
152 
153     // FIXME: Figure out how header maps and module maps will work together.
154 
155     // Only deal with normal search directories.
156     if (!SearchDirs[Idx].isNormalDir())
157       continue;
158 
159     // Search for a module map file in this directory.
160     if (loadModuleMapFile(SearchDirs[Idx].getDir()) == LMM_NewlyLoaded) {
161       // We just loaded a module map file; check whether the module is
162       // available now.
163       Module = ModMap.findModule(ModuleName);
164       if (Module)
165         break;
166     }
167 
168     // Search for a module map in a subdirectory with the same name as the
169     // module.
170     SmallString<128> NestedModuleMapDirName;
171     NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
172     llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
173     if (loadModuleMapFile(NestedModuleMapDirName) == LMM_NewlyLoaded) {
174       // If we just loaded a module map file, look for the module again.
175       Module = ModMap.findModule(ModuleName);
176       if (Module)
177         break;
178     }
179   }
180 
181   return Module;
182 }
183 
184 //===----------------------------------------------------------------------===//
185 // File lookup within a DirectoryLookup scope
186 //===----------------------------------------------------------------------===//
187 
188 /// getName - Return the directory or filename corresponding to this lookup
189 /// object.
190 const char *DirectoryLookup::getName() const {
191   if (isNormalDir())
192     return getDir()->getName();
193   if (isFramework())
194     return getFrameworkDir()->getName();
195   assert(isHeaderMap() && "Unknown DirectoryLookup");
196   return getHeaderMap()->getFileName();
197 }
198 
199 
200 /// LookupFile - Lookup the specified file in this search path, returning it
201 /// if it exists or returning null if not.
202 const FileEntry *DirectoryLookup::LookupFile(
203     StringRef Filename,
204     HeaderSearch &HS,
205     SmallVectorImpl<char> *SearchPath,
206     SmallVectorImpl<char> *RelativePath,
207     Module **SuggestedModule) const {
208   SmallString<1024> TmpDir;
209   if (isNormalDir()) {
210     // Concatenate the requested file onto the directory.
211     TmpDir = getDir()->getName();
212     llvm::sys::path::append(TmpDir, Filename);
213     if (SearchPath != NULL) {
214       StringRef SearchPathRef(getDir()->getName());
215       SearchPath->clear();
216       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
217     }
218     if (RelativePath != NULL) {
219       RelativePath->clear();
220       RelativePath->append(Filename.begin(), Filename.end());
221     }
222 
223     // If we have a module map that might map this header, load it and
224     // check whether we'll have a suggestion for a module.
225     if (SuggestedModule && HS.hasModuleMap(TmpDir, getDir())) {
226       const FileEntry *File = HS.getFileMgr().getFile(TmpDir.str(),
227                                                       /*openFile=*/false);
228       if (!File)
229         return File;
230 
231       // If there is a module that corresponds to this header,
232       // suggest it.
233       *SuggestedModule = HS.findModuleForHeader(File);
234       return File;
235     }
236 
237     return HS.getFileMgr().getFile(TmpDir.str(), /*openFile=*/true);
238   }
239 
240   if (isFramework())
241     return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
242                              SuggestedModule);
243 
244   assert(isHeaderMap() && "Unknown directory lookup");
245   const FileEntry * const Result = getHeaderMap()->LookupFile(
246       Filename, HS.getFileMgr());
247   if (Result) {
248     if (SearchPath != NULL) {
249       StringRef SearchPathRef(getName());
250       SearchPath->clear();
251       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
252     }
253     if (RelativePath != NULL) {
254       RelativePath->clear();
255       RelativePath->append(Filename.begin(), Filename.end());
256     }
257   }
258   return Result;
259 }
260 
261 
262 /// DoFrameworkLookup - Do a lookup of the specified file in the current
263 /// DirectoryLookup, which is a framework directory.
264 const FileEntry *DirectoryLookup::DoFrameworkLookup(
265     StringRef Filename,
266     HeaderSearch &HS,
267     SmallVectorImpl<char> *SearchPath,
268     SmallVectorImpl<char> *RelativePath,
269     Module **SuggestedModule) const
270 {
271   FileManager &FileMgr = HS.getFileMgr();
272 
273   // Framework names must have a '/' in the filename.
274   size_t SlashPos = Filename.find('/');
275   if (SlashPos == StringRef::npos) return 0;
276 
277   // Find out if this is the home for the specified framework, by checking
278   // HeaderSearch.  Possible answer are yes/no and unknown.
279   const DirectoryEntry *&FrameworkDirCache =
280     HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
281 
282   // If it is known and in some other directory, fail.
283   if (FrameworkDirCache && FrameworkDirCache != getFrameworkDir())
284     return 0;
285 
286   // Otherwise, construct the path to this framework dir.
287 
288   // FrameworkName = "/System/Library/Frameworks/"
289   SmallString<1024> FrameworkName;
290   FrameworkName += getFrameworkDir()->getName();
291   if (FrameworkName.empty() || FrameworkName.back() != '/')
292     FrameworkName.push_back('/');
293 
294   // FrameworkName = "/System/Library/Frameworks/Cocoa"
295   StringRef ModuleName(Filename.begin(), SlashPos);
296   FrameworkName += ModuleName;
297 
298   // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
299   FrameworkName += ".framework/";
300 
301   // If the cache entry is still unresolved, query to see if the cache entry is
302   // still unresolved.  If so, check its existence now.
303   if (FrameworkDirCache == 0) {
304     HS.IncrementFrameworkLookupCount();
305 
306     // If the framework dir doesn't exist, we fail.
307     // FIXME: It's probably more efficient to query this with FileMgr.getDir.
308     bool Exists;
309     if (llvm::sys::fs::exists(FrameworkName.str(), Exists) || !Exists)
310       return 0;
311 
312     // Otherwise, if it does, remember that this is the right direntry for this
313     // framework.
314     FrameworkDirCache = getFrameworkDir();
315   }
316 
317   if (RelativePath != NULL) {
318     RelativePath->clear();
319     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
320   }
321 
322   // If we're allowed to look for modules, try to load or create the module
323   // corresponding to this framework.
324   Module *Module = 0;
325   if (SuggestedModule) {
326     if (const DirectoryEntry *FrameworkDir
327                                         = FileMgr.getDirectory(FrameworkName)) {
328       bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
329       Module = HS.loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
330     }
331   }
332 
333   // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
334   unsigned OrigSize = FrameworkName.size();
335 
336   FrameworkName += "Headers/";
337 
338   if (SearchPath != NULL) {
339     SearchPath->clear();
340     // Without trailing '/'.
341     SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
342   }
343 
344   // Determine whether this is the module we're building or not.
345   bool AutomaticImport = Module;
346   FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
347   if (const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
348                                             /*openFile=*/!AutomaticImport)) {
349     if (AutomaticImport)
350       *SuggestedModule = HS.findModuleForHeader(FE);
351     return FE;
352   }
353 
354   // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
355   const char *Private = "Private";
356   FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
357                        Private+strlen(Private));
358   if (SearchPath != NULL)
359     SearchPath->insert(SearchPath->begin()+OrigSize, Private,
360                        Private+strlen(Private));
361 
362   const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
363                                         /*openFile=*/!AutomaticImport);
364   if (FE && AutomaticImport)
365     *SuggestedModule = HS.findModuleForHeader(FE);
366   return FE;
367 }
368 
369 void HeaderSearch::setTarget(const TargetInfo &Target) {
370   ModMap.setTarget(Target);
371 }
372 
373 
374 //===----------------------------------------------------------------------===//
375 // Header File Location.
376 //===----------------------------------------------------------------------===//
377 
378 
379 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
380 /// return null on failure.  isAngled indicates whether the file reference is
381 /// for system #include's or not (i.e. using <> instead of "").  CurFileEnt, if
382 /// non-null, indicates where the #including file is, in case a relative search
383 /// is needed.
384 const FileEntry *HeaderSearch::LookupFile(
385     StringRef Filename,
386     bool isAngled,
387     const DirectoryLookup *FromDir,
388     const DirectoryLookup *&CurDir,
389     const FileEntry *CurFileEnt,
390     SmallVectorImpl<char> *SearchPath,
391     SmallVectorImpl<char> *RelativePath,
392     Module **SuggestedModule,
393     bool SkipCache)
394 {
395   if (SuggestedModule)
396     *SuggestedModule = 0;
397 
398   // If 'Filename' is absolute, check to see if it exists and no searching.
399   if (llvm::sys::path::is_absolute(Filename)) {
400     CurDir = 0;
401 
402     // If this was an #include_next "/absolute/file", fail.
403     if (FromDir) return 0;
404 
405     if (SearchPath != NULL)
406       SearchPath->clear();
407     if (RelativePath != NULL) {
408       RelativePath->clear();
409       RelativePath->append(Filename.begin(), Filename.end());
410     }
411     // Otherwise, just return the file.
412     return FileMgr.getFile(Filename, /*openFile=*/true);
413   }
414 
415   // Unless disabled, check to see if the file is in the #includer's
416   // directory.  This has to be based on CurFileEnt, not CurDir, because
417   // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
418   // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
419   // This search is not done for <> headers.
420   if (CurFileEnt && !isAngled && !NoCurDirSearch) {
421     SmallString<1024> TmpDir;
422     // Concatenate the requested file onto the directory.
423     // FIXME: Portability.  Filename concatenation should be in sys::Path.
424     TmpDir += CurFileEnt->getDir()->getName();
425     TmpDir.push_back('/');
426     TmpDir.append(Filename.begin(), Filename.end());
427     if (const FileEntry *FE = FileMgr.getFile(TmpDir.str(),/*openFile=*/true)) {
428       // Leave CurDir unset.
429       // This file is a system header or C++ unfriendly if the old file is.
430       //
431       // Note that the temporary 'DirInfo' is required here, as either call to
432       // getFileInfo could resize the vector and we don't want to rely on order
433       // of evaluation.
434       unsigned DirInfo = getFileInfo(CurFileEnt).DirInfo;
435       getFileInfo(FE).DirInfo = DirInfo;
436       if (SearchPath != NULL) {
437         StringRef SearchPathRef(CurFileEnt->getDir()->getName());
438         SearchPath->clear();
439         SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
440       }
441       if (RelativePath != NULL) {
442         RelativePath->clear();
443         RelativePath->append(Filename.begin(), Filename.end());
444       }
445       return FE;
446     }
447   }
448 
449   CurDir = 0;
450 
451   // If this is a system #include, ignore the user #include locs.
452   unsigned i = isAngled ? AngledDirIdx : 0;
453 
454   // If this is a #include_next request, start searching after the directory the
455   // file was found in.
456   if (FromDir)
457     i = FromDir-&SearchDirs[0];
458 
459   // Cache all of the lookups performed by this method.  Many headers are
460   // multiply included, and the "pragma once" optimization prevents them from
461   // being relex/pp'd, but they would still have to search through a
462   // (potentially huge) series of SearchDirs to find it.
463   std::pair<unsigned, unsigned> &CacheLookup =
464     LookupFileCache.GetOrCreateValue(Filename).getValue();
465 
466   // If the entry has been previously looked up, the first value will be
467   // non-zero.  If the value is equal to i (the start point of our search), then
468   // this is a matching hit.
469   if (!SkipCache && CacheLookup.first == i+1) {
470     // Skip querying potentially lots of directories for this lookup.
471     i = CacheLookup.second;
472   } else {
473     // Otherwise, this is the first query, or the previous query didn't match
474     // our search start.  We will fill in our found location below, so prime the
475     // start point value.
476     CacheLookup.first = i+1;
477   }
478 
479   // Check each directory in sequence to see if it contains this file.
480   for (; i != SearchDirs.size(); ++i) {
481     const FileEntry *FE =
482       SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
483                                SuggestedModule);
484     if (!FE) continue;
485 
486     CurDir = &SearchDirs[i];
487 
488     // This file is a system header or C++ unfriendly if the dir is.
489     HeaderFileInfo &HFI = getFileInfo(FE);
490     HFI.DirInfo = CurDir->getDirCharacteristic();
491 
492     // If this file is found in a header map and uses the framework style of
493     // includes, then this header is part of a framework we're building.
494     if (CurDir->isIndexHeaderMap()) {
495       size_t SlashPos = Filename.find('/');
496       if (SlashPos != StringRef::npos) {
497         HFI.IndexHeaderMapHeader = 1;
498         HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
499                                                          SlashPos));
500       }
501     }
502 
503     // Remember this location for the next lookup we do.
504     CacheLookup.second = i;
505     return FE;
506   }
507 
508   // If we are including a file with a quoted include "foo.h" from inside
509   // a header in a framework that is currently being built, and we couldn't
510   // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
511   // "Foo" is the name of the framework in which the including header was found.
512   if (CurFileEnt && !isAngled && Filename.find('/') == StringRef::npos) {
513     HeaderFileInfo &IncludingHFI = getFileInfo(CurFileEnt);
514     if (IncludingHFI.IndexHeaderMapHeader) {
515       SmallString<128> ScratchFilename;
516       ScratchFilename += IncludingHFI.Framework;
517       ScratchFilename += '/';
518       ScratchFilename += Filename;
519 
520       const FileEntry *Result = LookupFile(ScratchFilename, /*isAngled=*/true,
521                                            FromDir, CurDir, CurFileEnt,
522                                            SearchPath, RelativePath,
523                                            SuggestedModule);
524       std::pair<unsigned, unsigned> &CacheLookup
525         = LookupFileCache.GetOrCreateValue(Filename).getValue();
526       CacheLookup.second
527         = LookupFileCache.GetOrCreateValue(ScratchFilename).getValue().second;
528       return Result;
529     }
530   }
531 
532   // Otherwise, didn't find it. Remember we didn't find this.
533   CacheLookup.second = SearchDirs.size();
534   return 0;
535 }
536 
537 /// LookupSubframeworkHeader - Look up a subframework for the specified
538 /// #include file.  For example, if #include'ing <HIToolbox/HIToolbox.h> from
539 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
540 /// is a subframework within Carbon.framework.  If so, return the FileEntry
541 /// for the designated file, otherwise return null.
542 const FileEntry *HeaderSearch::
543 LookupSubframeworkHeader(StringRef Filename,
544                          const FileEntry *ContextFileEnt,
545                          SmallVectorImpl<char> *SearchPath,
546                          SmallVectorImpl<char> *RelativePath) {
547   assert(ContextFileEnt && "No context file?");
548 
549   // Framework names must have a '/' in the filename.  Find it.
550   // FIXME: Should we permit '\' on Windows?
551   size_t SlashPos = Filename.find('/');
552   if (SlashPos == StringRef::npos) return 0;
553 
554   // Look up the base framework name of the ContextFileEnt.
555   const char *ContextName = ContextFileEnt->getName();
556 
557   // If the context info wasn't a framework, couldn't be a subframework.
558   const unsigned DotFrameworkLen = 10;
559   const char *FrameworkPos = strstr(ContextName, ".framework");
560   if (FrameworkPos == 0 ||
561       (FrameworkPos[DotFrameworkLen] != '/' &&
562        FrameworkPos[DotFrameworkLen] != '\\'))
563     return 0;
564 
565   SmallString<1024> FrameworkName(ContextName,
566                                         FrameworkPos+DotFrameworkLen+1);
567 
568   // Append Frameworks/HIToolbox.framework/
569   FrameworkName += "Frameworks/";
570   FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
571   FrameworkName += ".framework/";
572 
573   llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
574     FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
575 
576   // Some other location?
577   if (CacheLookup.getValue() &&
578       CacheLookup.getKeyLength() == FrameworkName.size() &&
579       memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
580              CacheLookup.getKeyLength()) != 0)
581     return 0;
582 
583   // Cache subframework.
584   if (CacheLookup.getValue() == 0) {
585     ++NumSubFrameworkLookups;
586 
587     // If the framework dir doesn't exist, we fail.
588     const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
589     if (Dir == 0) return 0;
590 
591     // Otherwise, if it does, remember that this is the right direntry for this
592     // framework.
593     CacheLookup.setValue(Dir);
594   }
595 
596   const FileEntry *FE = 0;
597 
598   if (RelativePath != NULL) {
599     RelativePath->clear();
600     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
601   }
602 
603   // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
604   SmallString<1024> HeadersFilename(FrameworkName);
605   HeadersFilename += "Headers/";
606   if (SearchPath != NULL) {
607     SearchPath->clear();
608     // Without trailing '/'.
609     SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
610   }
611 
612   HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
613   if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
614 
615     // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
616     HeadersFilename = FrameworkName;
617     HeadersFilename += "PrivateHeaders/";
618     if (SearchPath != NULL) {
619       SearchPath->clear();
620       // Without trailing '/'.
621       SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
622     }
623 
624     HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
625     if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
626       return 0;
627   }
628 
629   // This file is a system header or C++ unfriendly if the old file is.
630   //
631   // Note that the temporary 'DirInfo' is required here, as either call to
632   // getFileInfo could resize the vector and we don't want to rely on order
633   // of evaluation.
634   unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
635   getFileInfo(FE).DirInfo = DirInfo;
636   return FE;
637 }
638 
639 /// \brief Helper static function to normalize a path for injection into
640 /// a synthetic header.
641 /*static*/ std::string
642 HeaderSearch::NormalizeDashIncludePath(StringRef File, FileManager &FileMgr) {
643   // Implicit include paths should be resolved relative to the current
644   // working directory first, and then use the regular header search
645   // mechanism. The proper way to handle this is to have the
646   // predefines buffer located at the current working directory, but
647   // it has no file entry. For now, workaround this by using an
648   // absolute path if we find the file here, and otherwise letting
649   // header search handle it.
650   SmallString<128> Path(File);
651   llvm::sys::fs::make_absolute(Path);
652   bool exists;
653   if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
654     Path = File;
655   else if (exists)
656     FileMgr.getFile(File);
657 
658   return Lexer::Stringify(Path.str());
659 }
660 
661 //===----------------------------------------------------------------------===//
662 // File Info Management.
663 //===----------------------------------------------------------------------===//
664 
665 /// \brief Merge the header file info provided by \p OtherHFI into the current
666 /// header file info (\p HFI)
667 static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
668                                 const HeaderFileInfo &OtherHFI) {
669   HFI.isImport |= OtherHFI.isImport;
670   HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
671   HFI.NumIncludes += OtherHFI.NumIncludes;
672 
673   if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
674     HFI.ControllingMacro = OtherHFI.ControllingMacro;
675     HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
676   }
677 
678   if (OtherHFI.External) {
679     HFI.DirInfo = OtherHFI.DirInfo;
680     HFI.External = OtherHFI.External;
681     HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
682   }
683 
684   if (HFI.Framework.empty())
685     HFI.Framework = OtherHFI.Framework;
686 
687   HFI.Resolved = true;
688 }
689 
690 /// getFileInfo - Return the HeaderFileInfo structure for the specified
691 /// FileEntry.
692 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
693   if (FE->getUID() >= FileInfo.size())
694     FileInfo.resize(FE->getUID()+1);
695 
696   HeaderFileInfo &HFI = FileInfo[FE->getUID()];
697   if (ExternalSource && !HFI.Resolved)
698     mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
699   return HFI;
700 }
701 
702 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
703   // Check if we've ever seen this file as a header.
704   if (File->getUID() >= FileInfo.size())
705     return false;
706 
707   // Resolve header file info from the external source, if needed.
708   HeaderFileInfo &HFI = FileInfo[File->getUID()];
709   if (ExternalSource && !HFI.Resolved)
710     mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
711 
712   return HFI.isPragmaOnce || HFI.ControllingMacro || HFI.ControllingMacroID;
713 }
714 
715 void HeaderSearch::setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID) {
716   if (UID >= FileInfo.size())
717     FileInfo.resize(UID+1);
718   HFI.Resolved = true;
719   FileInfo[UID] = HFI;
720 }
721 
722 /// ShouldEnterIncludeFile - Mark the specified file as a target of of a
723 /// #include, #include_next, or #import directive.  Return false if #including
724 /// the file will have no effect or true if we should include it.
725 bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
726   ++NumIncluded; // Count # of attempted #includes.
727 
728   // Get information about this file.
729   HeaderFileInfo &FileInfo = getFileInfo(File);
730 
731   // If this is a #import directive, check that we have not already imported
732   // this header.
733   if (isImport) {
734     // If this has already been imported, don't import it again.
735     FileInfo.isImport = true;
736 
737     // Has this already been #import'ed or #include'd?
738     if (FileInfo.NumIncludes) return false;
739   } else {
740     // Otherwise, if this is a #include of a file that was previously #import'd
741     // or if this is the second #include of a #pragma once file, ignore it.
742     if (FileInfo.isImport)
743       return false;
744   }
745 
746   // Next, check to see if the file is wrapped with #ifndef guards.  If so, and
747   // if the macro that guards it is defined, we know the #include has no effect.
748   if (const IdentifierInfo *ControllingMacro
749       = FileInfo.getControllingMacro(ExternalLookup))
750     if (ControllingMacro->hasMacroDefinition()) {
751       ++NumMultiIncludeFileOptzn;
752       return false;
753     }
754 
755   // Increment the number of times this file has been included.
756   ++FileInfo.NumIncludes;
757 
758   return true;
759 }
760 
761 size_t HeaderSearch::getTotalMemory() const {
762   return SearchDirs.capacity()
763     + llvm::capacity_in_bytes(FileInfo)
764     + llvm::capacity_in_bytes(HeaderMaps)
765     + LookupFileCache.getAllocator().getTotalMemory()
766     + FrameworkMap.getAllocator().getTotalMemory();
767 }
768 
769 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
770   return FrameworkNames.GetOrCreateValue(Framework).getKey();
771 }
772 
773 bool HeaderSearch::hasModuleMap(StringRef FileName,
774                                 const DirectoryEntry *Root) {
775   llvm::SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
776 
777   StringRef DirName = FileName;
778   do {
779     // Get the parent directory name.
780     DirName = llvm::sys::path::parent_path(DirName);
781     if (DirName.empty())
782       return false;
783 
784     // Determine whether this directory exists.
785     const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
786     if (!Dir)
787       return false;
788 
789     // Try to load the module map file in this directory.
790     switch (loadModuleMapFile(Dir)) {
791     case LMM_NewlyLoaded:
792     case LMM_AlreadyLoaded:
793       // Success. All of the directories we stepped through inherit this module
794       // map file.
795       for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
796         DirectoryHasModuleMap[FixUpDirectories[I]] = true;
797 
798       return true;
799 
800     case LMM_NoDirectory:
801     case LMM_InvalidModuleMap:
802       break;
803     }
804 
805     // If we hit the top of our search, we're done.
806     if (Dir == Root)
807       return false;
808 
809     // Keep track of all of the directories we checked, so we can mark them as
810     // having module maps if we eventually do find a module map.
811     FixUpDirectories.push_back(Dir);
812   } while (true);
813 }
814 
815 Module *HeaderSearch::findModuleForHeader(const FileEntry *File) {
816   if (Module *Mod = ModMap.findModuleForHeader(File))
817     return Mod;
818 
819   return 0;
820 }
821 
822 bool HeaderSearch::loadModuleMapFile(const FileEntry *File) {
823   const DirectoryEntry *Dir = File->getDir();
824 
825   llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
826     = DirectoryHasModuleMap.find(Dir);
827   if (KnownDir != DirectoryHasModuleMap.end())
828     return !KnownDir->second;
829 
830   bool Result = ModMap.parseModuleMapFile(File);
831   if (!Result && llvm::sys::path::filename(File->getName()) == "module.map") {
832     // If the file we loaded was a module.map, look for the corresponding
833     // module_private.map.
834     SmallString<128> PrivateFilename(Dir->getName());
835     llvm::sys::path::append(PrivateFilename, "module_private.map");
836     if (const FileEntry *PrivateFile = FileMgr.getFile(PrivateFilename))
837       Result = ModMap.parseModuleMapFile(PrivateFile);
838   }
839 
840   DirectoryHasModuleMap[Dir] = !Result;
841   return Result;
842 }
843 
844 Module *HeaderSearch::loadFrameworkModule(StringRef Name,
845                                           const DirectoryEntry *Dir,
846                                           bool IsSystem) {
847   if (Module *Module = ModMap.findModule(Name))
848     return Module;
849 
850   // Try to load a module map file.
851   switch (loadModuleMapFile(Dir)) {
852   case LMM_InvalidModuleMap:
853     break;
854 
855   case LMM_AlreadyLoaded:
856   case LMM_NoDirectory:
857     return 0;
858 
859   case LMM_NewlyLoaded:
860     return ModMap.findModule(Name);
861   }
862 
863   // The top-level framework directory, from which we'll infer a framework
864   // module.
865   const DirectoryEntry *TopFrameworkDir = Dir;
866 
867   // The path from the module we're actually looking for back to the top-level
868   // framework name.
869   llvm::SmallVector<StringRef, 2> SubmodulePath;
870   SubmodulePath.push_back(Name);
871 
872   // Walk the directory structure to find any enclosing frameworks.
873   StringRef DirName = Dir->getName();
874   do {
875     // Get the parent directory name.
876     DirName = llvm::sys::path::parent_path(DirName);
877     if (DirName.empty())
878       break;
879 
880     // Determine whether this directory exists.
881     Dir = FileMgr.getDirectory(DirName);
882     if (!Dir)
883       break;
884 
885     // If this is a framework directory, then we're a subframework of this
886     // framework.
887     if (llvm::sys::path::extension(DirName) == ".framework") {
888       SubmodulePath.push_back(llvm::sys::path::stem(DirName));
889       TopFrameworkDir = Dir;
890     }
891   } while (true);
892 
893   // Try to infer a module map from the top-level framework directory.
894   Module *Result = ModMap.inferFrameworkModule(SubmodulePath.back(),
895                                                TopFrameworkDir,
896                                                IsSystem,
897                                                /*Parent=*/0);
898 
899   // Follow the submodule path to find the requested (sub)framework module
900   // within the top-level framework module.
901   SubmodulePath.pop_back();
902   while (!SubmodulePath.empty() && Result) {
903     Result = ModMap.lookupModuleQualified(SubmodulePath.back(), Result);
904     SubmodulePath.pop_back();
905   }
906   return Result;
907 }
908 
909 
910 HeaderSearch::LoadModuleMapResult
911 HeaderSearch::loadModuleMapFile(StringRef DirName) {
912   if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
913     return loadModuleMapFile(Dir);
914 
915   return LMM_NoDirectory;
916 }
917 
918 HeaderSearch::LoadModuleMapResult
919 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir) {
920   llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
921     = DirectoryHasModuleMap.find(Dir);
922   if (KnownDir != DirectoryHasModuleMap.end())
923     return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
924 
925   SmallString<128> ModuleMapFileName;
926   ModuleMapFileName += Dir->getName();
927   unsigned ModuleMapDirNameLen = ModuleMapFileName.size();
928   llvm::sys::path::append(ModuleMapFileName, "module.map");
929   if (const FileEntry *ModuleMapFile = FileMgr.getFile(ModuleMapFileName)) {
930     // We have found a module map file. Try to parse it.
931     if (ModMap.parseModuleMapFile(ModuleMapFile)) {
932       // No suitable module map.
933       DirectoryHasModuleMap[Dir] = false;
934       return LMM_InvalidModuleMap;
935     }
936 
937     // This directory has a module map.
938     DirectoryHasModuleMap[Dir] = true;
939 
940     // Check whether there is a private module map that we need to load as well.
941     ModuleMapFileName.erase(ModuleMapFileName.begin() + ModuleMapDirNameLen,
942                             ModuleMapFileName.end());
943     llvm::sys::path::append(ModuleMapFileName, "module_private.map");
944     if (const FileEntry *PrivateModuleMapFile
945                                         = FileMgr.getFile(ModuleMapFileName)) {
946       if (ModMap.parseModuleMapFile(PrivateModuleMapFile)) {
947         // No suitable module map.
948         DirectoryHasModuleMap[Dir] = false;
949         return LMM_InvalidModuleMap;
950       }
951     }
952 
953     return LMM_NewlyLoaded;
954   }
955 
956   // No suitable module map.
957   DirectoryHasModuleMap[Dir] = false;
958   return LMM_InvalidModuleMap;
959 }
960 
961 void HeaderSearch::collectAllModules(llvm::SmallVectorImpl<Module *> &Modules) {
962   Modules.clear();
963 
964   // Load module maps for each of the header search directories.
965   for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
966     if (SearchDirs[Idx].isFramework()) {
967       llvm::error_code EC;
968       SmallString<128> DirNative;
969       llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
970                               DirNative);
971 
972       // Search each of the ".framework" directories to load them as modules.
973       bool IsSystem = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
974       for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
975            Dir != DirEnd && !EC; Dir.increment(EC)) {
976         if (llvm::sys::path::extension(Dir->path()) != ".framework")
977           continue;
978 
979         const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(Dir->path());
980         if (!FrameworkDir)
981           continue;
982 
983         // Load this framework module.
984         loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
985                             IsSystem);
986       }
987       continue;
988     }
989 
990     // FIXME: Deal with header maps.
991     if (SearchDirs[Idx].isHeaderMap())
992       continue;
993 
994     // Try to load a module map file for the search directory.
995     loadModuleMapFile(SearchDirs[Idx].getDir());
996 
997     // Try to load module map files for immediate subdirectories of this search
998     // directory.
999     llvm::error_code EC;
1000     SmallString<128> DirNative;
1001     llvm::sys::path::native(SearchDirs[Idx].getDir()->getName(), DirNative);
1002     for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1003          Dir != DirEnd && !EC; Dir.increment(EC)) {
1004       loadModuleMapFile(Dir->path());
1005     }
1006   }
1007 
1008   // Populate the list of modules.
1009   for (ModuleMap::module_iterator M = ModMap.module_begin(),
1010                                MEnd = ModMap.module_end();
1011        M != MEnd; ++M) {
1012     Modules.push_back(M->getValue());
1013   }
1014 }
1015 
1016