clang API Documentation

HeaderSearch.cpp
Go to the documentation of this file.
00001 //===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements the DirectoryLookup and HeaderSearch interfaces.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Lex/HeaderSearch.h"
00015 #include "clang/Lex/HeaderMap.h"
00016 #include "clang/Lex/Lexer.h"
00017 #include "clang/Basic/Diagnostic.h"
00018 #include "clang/Basic/FileManager.h"
00019 #include "clang/Basic/IdentifierTable.h"
00020 #include "llvm/Support/FileSystem.h"
00021 #include "llvm/Support/Path.h"
00022 #include "llvm/ADT/SmallString.h"
00023 #include "llvm/Support/Capacity.h"
00024 #include <cstdio>
00025 using namespace clang;
00026 
00027 const IdentifierInfo *
00028 HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
00029   if (ControllingMacro)
00030     return ControllingMacro;
00031 
00032   if (!ControllingMacroID || !External)
00033     return 0;
00034 
00035   ControllingMacro = External->GetIdentifier(ControllingMacroID);
00036   return ControllingMacro;
00037 }
00038 
00039 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
00040 
00041 HeaderSearch::HeaderSearch(FileManager &FM, DiagnosticsEngine &Diags,
00042                            const LangOptions &LangOpts, 
00043                            const TargetInfo *Target)
00044   : FileMgr(FM), Diags(Diags), FrameworkMap(64), 
00045     ModMap(FileMgr, *Diags.getClient(), LangOpts, Target)
00046 {
00047   AngledDirIdx = 0;
00048   SystemDirIdx = 0;
00049   NoCurDirSearch = false;
00050 
00051   ExternalLookup = 0;
00052   ExternalSource = 0;
00053   NumIncluded = 0;
00054   NumMultiIncludeFileOptzn = 0;
00055   NumFrameworkLookups = NumSubFrameworkLookups = 0;
00056 }
00057 
00058 HeaderSearch::~HeaderSearch() {
00059   // Delete headermaps.
00060   for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
00061     delete HeaderMaps[i].second;
00062 }
00063 
00064 void HeaderSearch::PrintStats() {
00065   fprintf(stderr, "\n*** HeaderSearch Stats:\n");
00066   fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
00067   unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
00068   for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
00069     NumOnceOnlyFiles += FileInfo[i].isImport;
00070     if (MaxNumIncludes < FileInfo[i].NumIncludes)
00071       MaxNumIncludes = FileInfo[i].NumIncludes;
00072     NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
00073   }
00074   fprintf(stderr, "  %d #import/#pragma once files.\n", NumOnceOnlyFiles);
00075   fprintf(stderr, "  %d included exactly once.\n", NumSingleIncludedFiles);
00076   fprintf(stderr, "  %d max times a file is included.\n", MaxNumIncludes);
00077 
00078   fprintf(stderr, "  %d #include/#include_next/#import.\n", NumIncluded);
00079   fprintf(stderr, "    %d #includes skipped due to"
00080           " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
00081 
00082   fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
00083   fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
00084 }
00085 
00086 /// CreateHeaderMap - This method returns a HeaderMap for the specified
00087 /// FileEntry, uniquing them through the the 'HeaderMaps' datastructure.
00088 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
00089   // We expect the number of headermaps to be small, and almost always empty.
00090   // If it ever grows, use of a linear search should be re-evaluated.
00091   if (!HeaderMaps.empty()) {
00092     for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
00093       // Pointer equality comparison of FileEntries works because they are
00094       // already uniqued by inode.
00095       if (HeaderMaps[i].first == FE)
00096         return HeaderMaps[i].second;
00097   }
00098 
00099   if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
00100     HeaderMaps.push_back(std::make_pair(FE, HM));
00101     return HM;
00102   }
00103 
00104   return 0;
00105 }
00106 
00107 std::string HeaderSearch::getModuleFileName(Module *Module) {
00108   // If we don't have a module cache path, we can't do anything.
00109   if (ModuleCachePath.empty()) 
00110     return std::string();
00111 
00112 
00113   SmallString<256> Result(ModuleCachePath);
00114   llvm::sys::path::append(Result, Module->getTopLevelModule()->Name + ".pcm");
00115   return Result.str().str();
00116 }
00117 
00118 std::string HeaderSearch::getModuleFileName(StringRef ModuleName) {
00119   // If we don't have a module cache path, we can't do anything.
00120   if (ModuleCachePath.empty()) 
00121     return std::string();
00122   
00123   
00124   SmallString<256> Result(ModuleCachePath);
00125   llvm::sys::path::append(Result, ModuleName + ".pcm");
00126   return Result.str().str();
00127 }
00128 
00129 Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
00130   // Look in the module map to determine if there is a module by this name.
00131   Module *Module = ModMap.findModule(ModuleName);
00132   if (Module || !AllowSearch)
00133     return Module;
00134   
00135   // Look through the various header search paths to load any avai;able module 
00136   // maps, searching for a module map that describes this module.
00137   for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
00138     if (SearchDirs[Idx].isFramework()) {
00139       // Search for or infer a module map for a framework.
00140       SmallString<128> FrameworkDirName;
00141       FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
00142       llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
00143       if (const DirectoryEntry *FrameworkDir 
00144             = FileMgr.getDirectory(FrameworkDirName)) {
00145         bool IsSystem
00146           = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
00147         Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
00148         if (Module)
00149           break;
00150       }
00151     }
00152     
00153     // FIXME: Figure out how header maps and module maps will work together.
00154     
00155     // Only deal with normal search directories.
00156     if (!SearchDirs[Idx].isNormalDir())
00157       continue;
00158     
00159     // Search for a module map file in this directory.
00160     if (loadModuleMapFile(SearchDirs[Idx].getDir()) == LMM_NewlyLoaded) {
00161       // We just loaded a module map file; check whether the module is
00162       // available now.
00163       Module = ModMap.findModule(ModuleName);
00164       if (Module)
00165         break;
00166     }
00167               
00168     // Search for a module map in a subdirectory with the same name as the
00169     // module.
00170     SmallString<128> NestedModuleMapDirName;
00171     NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
00172     llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
00173     if (loadModuleMapFile(NestedModuleMapDirName) == LMM_NewlyLoaded) {
00174       // If we just loaded a module map file, look for the module again.
00175       Module = ModMap.findModule(ModuleName);
00176       if (Module)
00177         break;
00178     }
00179   }
00180   
00181   return Module;
00182 }
00183 
00184 //===----------------------------------------------------------------------===//
00185 // File lookup within a DirectoryLookup scope
00186 //===----------------------------------------------------------------------===//
00187 
00188 /// getName - Return the directory or filename corresponding to this lookup
00189 /// object.
00190 const char *DirectoryLookup::getName() const {
00191   if (isNormalDir())
00192     return getDir()->getName();
00193   if (isFramework())
00194     return getFrameworkDir()->getName();
00195   assert(isHeaderMap() && "Unknown DirectoryLookup");
00196   return getHeaderMap()->getFileName();
00197 }
00198 
00199 
00200 /// LookupFile - Lookup the specified file in this search path, returning it
00201 /// if it exists or returning null if not.
00202 const FileEntry *DirectoryLookup::LookupFile(
00203     StringRef Filename,
00204     HeaderSearch &HS,
00205     SmallVectorImpl<char> *SearchPath,
00206     SmallVectorImpl<char> *RelativePath,
00207     Module **SuggestedModule,
00208     bool &InUserSpecifiedSystemFramework) const {
00209   InUserSpecifiedSystemFramework = false;
00210 
00211   SmallString<1024> TmpDir;
00212   if (isNormalDir()) {
00213     // Concatenate the requested file onto the directory.
00214     TmpDir = getDir()->getName();
00215     llvm::sys::path::append(TmpDir, Filename);
00216     if (SearchPath != NULL) {
00217       StringRef SearchPathRef(getDir()->getName());
00218       SearchPath->clear();
00219       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
00220     }
00221     if (RelativePath != NULL) {
00222       RelativePath->clear();
00223       RelativePath->append(Filename.begin(), Filename.end());
00224     }
00225     
00226     // If we have a module map that might map this header, load it and
00227     // check whether we'll have a suggestion for a module.
00228     if (SuggestedModule && HS.hasModuleMap(TmpDir, getDir())) {
00229       const FileEntry *File = HS.getFileMgr().getFile(TmpDir.str(), 
00230                                                       /*openFile=*/false);
00231       if (!File)
00232         return File;
00233       
00234       // If there is a module that corresponds to this header, 
00235       // suggest it.
00236       *SuggestedModule = HS.findModuleForHeader(File);
00237       return File;
00238     }
00239     
00240     return HS.getFileMgr().getFile(TmpDir.str(), /*openFile=*/true);
00241   }
00242 
00243   if (isFramework())
00244     return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
00245                              SuggestedModule, InUserSpecifiedSystemFramework);
00246 
00247   assert(isHeaderMap() && "Unknown directory lookup");
00248   const FileEntry * const Result = getHeaderMap()->LookupFile(
00249       Filename, HS.getFileMgr());
00250   if (Result) {
00251     if (SearchPath != NULL) {
00252       StringRef SearchPathRef(getName());
00253       SearchPath->clear();
00254       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
00255     }
00256     if (RelativePath != NULL) {
00257       RelativePath->clear();
00258       RelativePath->append(Filename.begin(), Filename.end());
00259     }
00260   }
00261   return Result;
00262 }
00263 
00264 
00265 /// DoFrameworkLookup - Do a lookup of the specified file in the current
00266 /// DirectoryLookup, which is a framework directory.
00267 const FileEntry *DirectoryLookup::DoFrameworkLookup(
00268     StringRef Filename,
00269     HeaderSearch &HS,
00270     SmallVectorImpl<char> *SearchPath,
00271     SmallVectorImpl<char> *RelativePath,
00272     Module **SuggestedModule,
00273     bool &InUserSpecifiedSystemFramework) const
00274 {
00275   FileManager &FileMgr = HS.getFileMgr();
00276 
00277   // Framework names must have a '/' in the filename.
00278   size_t SlashPos = Filename.find('/');
00279   if (SlashPos == StringRef::npos) return 0;
00280 
00281   // Find out if this is the home for the specified framework, by checking
00282   // HeaderSearch.  Possible answers are yes/no and unknown.
00283   HeaderSearch::FrameworkCacheEntry &CacheEntry =
00284     HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
00285 
00286   // If it is known and in some other directory, fail.
00287   if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
00288     return 0;
00289 
00290   // Otherwise, construct the path to this framework dir.
00291 
00292   // FrameworkName = "/System/Library/Frameworks/"
00293   SmallString<1024> FrameworkName;
00294   FrameworkName += getFrameworkDir()->getName();
00295   if (FrameworkName.empty() || FrameworkName.back() != '/')
00296     FrameworkName.push_back('/');
00297 
00298   // FrameworkName = "/System/Library/Frameworks/Cocoa"
00299   StringRef ModuleName(Filename.begin(), SlashPos);
00300   FrameworkName += ModuleName;
00301 
00302   // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
00303   FrameworkName += ".framework/";
00304 
00305   // If the cache entry was unresolved, populate it now.
00306   if (CacheEntry.Directory == 0) {
00307     HS.IncrementFrameworkLookupCount();
00308 
00309     // If the framework dir doesn't exist, we fail.
00310     const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
00311     if (Dir == 0) return 0;
00312 
00313     // Otherwise, if it does, remember that this is the right direntry for this
00314     // framework.
00315     CacheEntry.Directory = getFrameworkDir();
00316 
00317     // If this is a user search directory, check if the framework has been
00318     // user-specified as a system framework.
00319     if (getDirCharacteristic() == SrcMgr::C_User) {
00320       SmallString<1024> SystemFrameworkMarker(FrameworkName);
00321       SystemFrameworkMarker += ".system_framework";
00322       if (llvm::sys::fs::exists(SystemFrameworkMarker.str())) {
00323         CacheEntry.IsUserSpecifiedSystemFramework = true;
00324       }
00325     }
00326   }
00327 
00328   // Set the 'user-specified system framework' flag.
00329   InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
00330 
00331   if (RelativePath != NULL) {
00332     RelativePath->clear();
00333     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
00334   }
00335 
00336   // If we're allowed to look for modules, try to load or create the module
00337   // corresponding to this framework.
00338   Module *Module = 0;
00339   if (SuggestedModule) {
00340     if (const DirectoryEntry *FrameworkDir
00341                                         = FileMgr.getDirectory(FrameworkName)) {
00342       bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
00343       Module = HS.loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
00344     }
00345   }
00346   
00347   // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
00348   unsigned OrigSize = FrameworkName.size();
00349 
00350   FrameworkName += "Headers/";
00351 
00352   if (SearchPath != NULL) {
00353     SearchPath->clear();
00354     // Without trailing '/'.
00355     SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
00356   }
00357 
00358   // Determine whether this is the module we're building or not.
00359   bool AutomaticImport = Module;  
00360   FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
00361   if (const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
00362                                             /*openFile=*/!AutomaticImport)) {
00363     if (AutomaticImport)
00364       *SuggestedModule = HS.findModuleForHeader(FE);
00365     return FE;
00366   }
00367 
00368   // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
00369   const char *Private = "Private";
00370   FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
00371                        Private+strlen(Private));
00372   if (SearchPath != NULL)
00373     SearchPath->insert(SearchPath->begin()+OrigSize, Private,
00374                        Private+strlen(Private));
00375 
00376   const FileEntry *FE = FileMgr.getFile(FrameworkName.str(), 
00377                                         /*openFile=*/!AutomaticImport);
00378   if (FE && AutomaticImport)
00379     *SuggestedModule = HS.findModuleForHeader(FE);
00380   return FE;
00381 }
00382 
00383 void HeaderSearch::setTarget(const TargetInfo &Target) {
00384   ModMap.setTarget(Target);
00385 }
00386 
00387 
00388 //===----------------------------------------------------------------------===//
00389 // Header File Location.
00390 //===----------------------------------------------------------------------===//
00391 
00392 
00393 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
00394 /// return null on failure.  isAngled indicates whether the file reference is
00395 /// for system #include's or not (i.e. using <> instead of "").  CurFileEnt, if
00396 /// non-null, indicates where the #including file is, in case a relative search
00397 /// is needed.
00398 const FileEntry *HeaderSearch::LookupFile(
00399     StringRef Filename,
00400     bool isAngled,
00401     const DirectoryLookup *FromDir,
00402     const DirectoryLookup *&CurDir,
00403     const FileEntry *CurFileEnt,
00404     SmallVectorImpl<char> *SearchPath,
00405     SmallVectorImpl<char> *RelativePath,
00406     Module **SuggestedModule,
00407     bool SkipCache)
00408 {
00409   if (SuggestedModule)
00410     *SuggestedModule = 0;
00411     
00412   // If 'Filename' is absolute, check to see if it exists and no searching.
00413   if (llvm::sys::path::is_absolute(Filename)) {
00414     CurDir = 0;
00415 
00416     // If this was an #include_next "/absolute/file", fail.
00417     if (FromDir) return 0;
00418 
00419     if (SearchPath != NULL)
00420       SearchPath->clear();
00421     if (RelativePath != NULL) {
00422       RelativePath->clear();
00423       RelativePath->append(Filename.begin(), Filename.end());
00424     }
00425     // Otherwise, just return the file.
00426     return FileMgr.getFile(Filename, /*openFile=*/true);
00427   }
00428 
00429   // Unless disabled, check to see if the file is in the #includer's
00430   // directory.  This has to be based on CurFileEnt, not CurDir, because
00431   // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
00432   // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
00433   // This search is not done for <> headers.
00434   if (CurFileEnt && !isAngled && !NoCurDirSearch) {
00435     SmallString<1024> TmpDir;
00436     // Concatenate the requested file onto the directory.
00437     // FIXME: Portability.  Filename concatenation should be in sys::Path.
00438     TmpDir += CurFileEnt->getDir()->getName();
00439     TmpDir.push_back('/');
00440     TmpDir.append(Filename.begin(), Filename.end());
00441     if (const FileEntry *FE = FileMgr.getFile(TmpDir.str(),/*openFile=*/true)) {
00442       // Leave CurDir unset.
00443       // This file is a system header or C++ unfriendly if the old file is.
00444       //
00445       // Note that the temporary 'DirInfo' is required here, as either call to
00446       // getFileInfo could resize the vector and we don't want to rely on order
00447       // of evaluation.
00448       unsigned DirInfo = getFileInfo(CurFileEnt).DirInfo;
00449       getFileInfo(FE).DirInfo = DirInfo;
00450       if (SearchPath != NULL) {
00451         StringRef SearchPathRef(CurFileEnt->getDir()->getName());
00452         SearchPath->clear();
00453         SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
00454       }
00455       if (RelativePath != NULL) {
00456         RelativePath->clear();
00457         RelativePath->append(Filename.begin(), Filename.end());
00458       }
00459       return FE;
00460     }
00461   }
00462 
00463   CurDir = 0;
00464 
00465   // If this is a system #include, ignore the user #include locs.
00466   unsigned i = isAngled ? AngledDirIdx : 0;
00467 
00468   // If this is a #include_next request, start searching after the directory the
00469   // file was found in.
00470   if (FromDir)
00471     i = FromDir-&SearchDirs[0];
00472 
00473   // Cache all of the lookups performed by this method.  Many headers are
00474   // multiply included, and the "pragma once" optimization prevents them from
00475   // being relex/pp'd, but they would still have to search through a
00476   // (potentially huge) series of SearchDirs to find it.
00477   std::pair<unsigned, unsigned> &CacheLookup =
00478     LookupFileCache.GetOrCreateValue(Filename).getValue();
00479 
00480   // If the entry has been previously looked up, the first value will be
00481   // non-zero.  If the value is equal to i (the start point of our search), then
00482   // this is a matching hit.
00483   if (!SkipCache && CacheLookup.first == i+1) {
00484     // Skip querying potentially lots of directories for this lookup.
00485     i = CacheLookup.second;
00486   } else {
00487     // Otherwise, this is the first query, or the previous query didn't match
00488     // our search start.  We will fill in our found location below, so prime the
00489     // start point value.
00490     CacheLookup.first = i+1;
00491   }
00492 
00493   // Check each directory in sequence to see if it contains this file.
00494   for (; i != SearchDirs.size(); ++i) {
00495     bool InUserSpecifiedSystemFramework = false;
00496     const FileEntry *FE =
00497       SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
00498                                SuggestedModule, InUserSpecifiedSystemFramework);
00499     if (!FE) continue;
00500 
00501     CurDir = &SearchDirs[i];
00502 
00503     // This file is a system header or C++ unfriendly if the dir is.
00504     HeaderFileInfo &HFI = getFileInfo(FE);
00505     HFI.DirInfo = CurDir->getDirCharacteristic();
00506 
00507     // If the directory characteristic is User but this framework was
00508     // user-specified to be treated as a system framework, promote the
00509     // characteristic.
00510     if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
00511       HFI.DirInfo = SrcMgr::C_System;
00512 
00513     // If this file is found in a header map and uses the framework style of
00514     // includes, then this header is part of a framework we're building.
00515     if (CurDir->isIndexHeaderMap()) {
00516       size_t SlashPos = Filename.find('/');
00517       if (SlashPos != StringRef::npos) {
00518         HFI.IndexHeaderMapHeader = 1;
00519         HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(), 
00520                                                          SlashPos));
00521       }
00522     }
00523     
00524     // Remember this location for the next lookup we do.
00525     CacheLookup.second = i;
00526     return FE;
00527   }
00528 
00529   // If we are including a file with a quoted include "foo.h" from inside
00530   // a header in a framework that is currently being built, and we couldn't
00531   // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
00532   // "Foo" is the name of the framework in which the including header was found.
00533   if (CurFileEnt && !isAngled && Filename.find('/') == StringRef::npos) {
00534     HeaderFileInfo &IncludingHFI = getFileInfo(CurFileEnt);
00535     if (IncludingHFI.IndexHeaderMapHeader) {
00536       SmallString<128> ScratchFilename;
00537       ScratchFilename += IncludingHFI.Framework;
00538       ScratchFilename += '/';
00539       ScratchFilename += Filename;
00540       
00541       const FileEntry *Result = LookupFile(ScratchFilename, /*isAngled=*/true,
00542                                            FromDir, CurDir, CurFileEnt, 
00543                                            SearchPath, RelativePath,
00544                                            SuggestedModule);
00545       std::pair<unsigned, unsigned> &CacheLookup 
00546         = LookupFileCache.GetOrCreateValue(Filename).getValue();
00547       CacheLookup.second
00548         = LookupFileCache.GetOrCreateValue(ScratchFilename).getValue().second;
00549       return Result;
00550     }
00551   }
00552 
00553   // Otherwise, didn't find it. Remember we didn't find this.
00554   CacheLookup.second = SearchDirs.size();
00555   return 0;
00556 }
00557 
00558 /// LookupSubframeworkHeader - Look up a subframework for the specified
00559 /// #include file.  For example, if #include'ing <HIToolbox/HIToolbox.h> from
00560 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
00561 /// is a subframework within Carbon.framework.  If so, return the FileEntry
00562 /// for the designated file, otherwise return null.
00563 const FileEntry *HeaderSearch::
00564 LookupSubframeworkHeader(StringRef Filename,
00565                          const FileEntry *ContextFileEnt,
00566                          SmallVectorImpl<char> *SearchPath,
00567                          SmallVectorImpl<char> *RelativePath) {
00568   assert(ContextFileEnt && "No context file?");
00569 
00570   // Framework names must have a '/' in the filename.  Find it.
00571   // FIXME: Should we permit '\' on Windows?
00572   size_t SlashPos = Filename.find('/');
00573   if (SlashPos == StringRef::npos) return 0;
00574 
00575   // Look up the base framework name of the ContextFileEnt.
00576   const char *ContextName = ContextFileEnt->getName();
00577 
00578   // If the context info wasn't a framework, couldn't be a subframework.
00579   const unsigned DotFrameworkLen = 10;
00580   const char *FrameworkPos = strstr(ContextName, ".framework");
00581   if (FrameworkPos == 0 || 
00582       (FrameworkPos[DotFrameworkLen] != '/' && 
00583        FrameworkPos[DotFrameworkLen] != '\\'))
00584     return 0;
00585 
00586   SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
00587 
00588   // Append Frameworks/HIToolbox.framework/
00589   FrameworkName += "Frameworks/";
00590   FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
00591   FrameworkName += ".framework/";
00592 
00593   llvm::StringMapEntry<FrameworkCacheEntry> &CacheLookup =
00594     FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
00595 
00596   // Some other location?
00597   if (CacheLookup.getValue().Directory &&
00598       CacheLookup.getKeyLength() == FrameworkName.size() &&
00599       memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
00600              CacheLookup.getKeyLength()) != 0)
00601     return 0;
00602 
00603   // Cache subframework.
00604   if (CacheLookup.getValue().Directory == 0) {
00605     ++NumSubFrameworkLookups;
00606 
00607     // If the framework dir doesn't exist, we fail.
00608     const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
00609     if (Dir == 0) return 0;
00610 
00611     // Otherwise, if it does, remember that this is the right direntry for this
00612     // framework.
00613     CacheLookup.getValue().Directory = Dir;
00614   }
00615 
00616   const FileEntry *FE = 0;
00617 
00618   if (RelativePath != NULL) {
00619     RelativePath->clear();
00620     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
00621   }
00622 
00623   // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
00624   SmallString<1024> HeadersFilename(FrameworkName);
00625   HeadersFilename += "Headers/";
00626   if (SearchPath != NULL) {
00627     SearchPath->clear();
00628     // Without trailing '/'.
00629     SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
00630   }
00631 
00632   HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
00633   if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
00634 
00635     // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
00636     HeadersFilename = FrameworkName;
00637     HeadersFilename += "PrivateHeaders/";
00638     if (SearchPath != NULL) {
00639       SearchPath->clear();
00640       // Without trailing '/'.
00641       SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
00642     }
00643 
00644     HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
00645     if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
00646       return 0;
00647   }
00648 
00649   // This file is a system header or C++ unfriendly if the old file is.
00650   //
00651   // Note that the temporary 'DirInfo' is required here, as either call to
00652   // getFileInfo could resize the vector and we don't want to rely on order
00653   // of evaluation.
00654   unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
00655   getFileInfo(FE).DirInfo = DirInfo;
00656   return FE;
00657 }
00658 
00659 /// \brief Helper static function to normalize a path for injection into
00660 /// a synthetic header.
00661 /*static*/ std::string
00662 HeaderSearch::NormalizeDashIncludePath(StringRef File, FileManager &FileMgr) {
00663   // Implicit include paths should be resolved relative to the current
00664   // working directory first, and then use the regular header search
00665   // mechanism. The proper way to handle this is to have the
00666   // predefines buffer located at the current working directory, but
00667   // it has no file entry. For now, workaround this by using an
00668   // absolute path if we find the file here, and otherwise letting
00669   // header search handle it.
00670   SmallString<128> Path(File);
00671   llvm::sys::fs::make_absolute(Path);
00672   bool exists;
00673   if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
00674     Path = File;
00675   else if (exists)
00676     FileMgr.getFile(File);
00677 
00678   return Lexer::Stringify(Path.str());
00679 }
00680 
00681 //===----------------------------------------------------------------------===//
00682 // File Info Management.
00683 //===----------------------------------------------------------------------===//
00684 
00685 /// \brief Merge the header file info provided by \p OtherHFI into the current
00686 /// header file info (\p HFI)
00687 static void mergeHeaderFileInfo(HeaderFileInfo &HFI, 
00688                                 const HeaderFileInfo &OtherHFI) {
00689   HFI.isImport |= OtherHFI.isImport;
00690   HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
00691   HFI.NumIncludes += OtherHFI.NumIncludes;
00692   
00693   if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
00694     HFI.ControllingMacro = OtherHFI.ControllingMacro;
00695     HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
00696   }
00697   
00698   if (OtherHFI.External) {
00699     HFI.DirInfo = OtherHFI.DirInfo;
00700     HFI.External = OtherHFI.External;
00701     HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
00702   }
00703 
00704   if (HFI.Framework.empty())
00705     HFI.Framework = OtherHFI.Framework;
00706   
00707   HFI.Resolved = true;
00708 }
00709                                 
00710 /// getFileInfo - Return the HeaderFileInfo structure for the specified
00711 /// FileEntry.
00712 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
00713   if (FE->getUID() >= FileInfo.size())
00714     FileInfo.resize(FE->getUID()+1);
00715   
00716   HeaderFileInfo &HFI = FileInfo[FE->getUID()];
00717   if (ExternalSource && !HFI.Resolved)
00718     mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
00719   return HFI;
00720 }
00721 
00722 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
00723   // Check if we've ever seen this file as a header.
00724   if (File->getUID() >= FileInfo.size())
00725     return false;
00726 
00727   // Resolve header file info from the external source, if needed.
00728   HeaderFileInfo &HFI = FileInfo[File->getUID()];
00729   if (ExternalSource && !HFI.Resolved)
00730     mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
00731 
00732   return HFI.isPragmaOnce || HFI.ControllingMacro || HFI.ControllingMacroID;
00733 }
00734 
00735 void HeaderSearch::setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID) {
00736   if (UID >= FileInfo.size())
00737     FileInfo.resize(UID+1);
00738   HFI.Resolved = true;
00739   FileInfo[UID] = HFI;
00740 }
00741 
00742 /// ShouldEnterIncludeFile - Mark the specified file as a target of of a
00743 /// #include, #include_next, or #import directive.  Return false if #including
00744 /// the file will have no effect or true if we should include it.
00745 bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
00746   ++NumIncluded; // Count # of attempted #includes.
00747 
00748   // Get information about this file.
00749   HeaderFileInfo &FileInfo = getFileInfo(File);
00750 
00751   // If this is a #import directive, check that we have not already imported
00752   // this header.
00753   if (isImport) {
00754     // If this has already been imported, don't import it again.
00755     FileInfo.isImport = true;
00756 
00757     // Has this already been #import'ed or #include'd?
00758     if (FileInfo.NumIncludes) return false;
00759   } else {
00760     // Otherwise, if this is a #include of a file that was previously #import'd
00761     // or if this is the second #include of a #pragma once file, ignore it.
00762     if (FileInfo.isImport)
00763       return false;
00764   }
00765 
00766   // Next, check to see if the file is wrapped with #ifndef guards.  If so, and
00767   // if the macro that guards it is defined, we know the #include has no effect.
00768   if (const IdentifierInfo *ControllingMacro
00769       = FileInfo.getControllingMacro(ExternalLookup))
00770     if (ControllingMacro->hasMacroDefinition()) {
00771       ++NumMultiIncludeFileOptzn;
00772       return false;
00773     }
00774 
00775   // Increment the number of times this file has been included.
00776   ++FileInfo.NumIncludes;
00777 
00778   return true;
00779 }
00780 
00781 size_t HeaderSearch::getTotalMemory() const {
00782   return SearchDirs.capacity()
00783     + llvm::capacity_in_bytes(FileInfo)
00784     + llvm::capacity_in_bytes(HeaderMaps)
00785     + LookupFileCache.getAllocator().getTotalMemory()
00786     + FrameworkMap.getAllocator().getTotalMemory();
00787 }
00788 
00789 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
00790   return FrameworkNames.GetOrCreateValue(Framework).getKey();
00791 }
00792 
00793 bool HeaderSearch::hasModuleMap(StringRef FileName, 
00794                                 const DirectoryEntry *Root) {
00795   llvm::SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
00796   
00797   StringRef DirName = FileName;
00798   do {
00799     // Get the parent directory name.
00800     DirName = llvm::sys::path::parent_path(DirName);
00801     if (DirName.empty())
00802       return false;
00803     
00804     // Determine whether this directory exists.
00805     const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
00806     if (!Dir)
00807       return false;
00808     
00809     // Try to load the module map file in this directory.
00810     switch (loadModuleMapFile(Dir)) {
00811     case LMM_NewlyLoaded:
00812     case LMM_AlreadyLoaded:
00813       // Success. All of the directories we stepped through inherit this module
00814       // map file.
00815       for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
00816         DirectoryHasModuleMap[FixUpDirectories[I]] = true;
00817       
00818       return true;
00819 
00820     case LMM_NoDirectory:
00821     case LMM_InvalidModuleMap:
00822       break;
00823     }
00824 
00825     // If we hit the top of our search, we're done.
00826     if (Dir == Root)
00827       return false;
00828         
00829     // Keep track of all of the directories we checked, so we can mark them as
00830     // having module maps if we eventually do find a module map.
00831     FixUpDirectories.push_back(Dir);
00832   } while (true);
00833 }
00834 
00835 Module *HeaderSearch::findModuleForHeader(const FileEntry *File) {
00836   if (Module *Mod = ModMap.findModuleForHeader(File))
00837     return Mod;
00838   
00839   return 0;
00840 }
00841 
00842 bool HeaderSearch::loadModuleMapFile(const FileEntry *File) {
00843   const DirectoryEntry *Dir = File->getDir();
00844   
00845   llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
00846     = DirectoryHasModuleMap.find(Dir);
00847   if (KnownDir != DirectoryHasModuleMap.end())
00848     return !KnownDir->second;
00849   
00850   bool Result = ModMap.parseModuleMapFile(File);
00851   if (!Result && llvm::sys::path::filename(File->getName()) == "module.map") {
00852     // If the file we loaded was a module.map, look for the corresponding
00853     // module_private.map.
00854     SmallString<128> PrivateFilename(Dir->getName());
00855     llvm::sys::path::append(PrivateFilename, "module_private.map");
00856     if (const FileEntry *PrivateFile = FileMgr.getFile(PrivateFilename))
00857       Result = ModMap.parseModuleMapFile(PrivateFile);
00858   }
00859   
00860   DirectoryHasModuleMap[Dir] = !Result;  
00861   return Result;
00862 }
00863 
00864 Module *HeaderSearch::loadFrameworkModule(StringRef Name, 
00865                                           const DirectoryEntry *Dir,
00866                                           bool IsSystem) {
00867   if (Module *Module = ModMap.findModule(Name))
00868     return Module;
00869   
00870   // Try to load a module map file.
00871   switch (loadModuleMapFile(Dir)) {
00872   case LMM_InvalidModuleMap:
00873     break;
00874     
00875   case LMM_AlreadyLoaded:
00876   case LMM_NoDirectory:
00877     return 0;
00878     
00879   case LMM_NewlyLoaded:
00880     return ModMap.findModule(Name);
00881   }
00882 
00883   // The top-level framework directory, from which we'll infer a framework
00884   // module.
00885   const DirectoryEntry *TopFrameworkDir = Dir;
00886   
00887   // The path from the module we're actually looking for back to the top-level
00888   // framework name.
00889   llvm::SmallVector<StringRef, 2> SubmodulePath;
00890   SubmodulePath.push_back(Name);
00891   
00892   // Walk the directory structure to find any enclosing frameworks.
00893   StringRef DirName = Dir->getName();
00894   do {
00895     // Get the parent directory name.
00896     DirName = llvm::sys::path::parent_path(DirName);
00897     if (DirName.empty())
00898       break;
00899     
00900     // Determine whether this directory exists.
00901     Dir = FileMgr.getDirectory(DirName);
00902     if (!Dir)
00903       break;
00904     
00905     // If this is a framework directory, then we're a subframework of this
00906     // framework.
00907     if (llvm::sys::path::extension(DirName) == ".framework") {
00908       SubmodulePath.push_back(llvm::sys::path::stem(DirName));
00909       TopFrameworkDir = Dir;
00910     }
00911   } while (true);
00912   
00913   // Try to infer a module map from the top-level framework directory.
00914   Module *Result = ModMap.inferFrameworkModule(SubmodulePath.back(), 
00915                                                TopFrameworkDir,
00916                                                IsSystem,
00917                                                /*Parent=*/0);
00918   
00919   // Follow the submodule path to find the requested (sub)framework module
00920   // within the top-level framework module.
00921   SubmodulePath.pop_back();
00922   while (!SubmodulePath.empty() && Result) {
00923     Result = ModMap.lookupModuleQualified(SubmodulePath.back(), Result);
00924     SubmodulePath.pop_back();
00925   }
00926   return Result;
00927 }
00928 
00929 
00930 HeaderSearch::LoadModuleMapResult 
00931 HeaderSearch::loadModuleMapFile(StringRef DirName) {
00932   if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
00933     return loadModuleMapFile(Dir);
00934   
00935   return LMM_NoDirectory;
00936 }
00937 
00938 HeaderSearch::LoadModuleMapResult 
00939 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir) {
00940   llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
00941     = DirectoryHasModuleMap.find(Dir);
00942   if (KnownDir != DirectoryHasModuleMap.end())
00943     return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
00944   
00945   SmallString<128> ModuleMapFileName;
00946   ModuleMapFileName += Dir->getName();
00947   unsigned ModuleMapDirNameLen = ModuleMapFileName.size();
00948   llvm::sys::path::append(ModuleMapFileName, "module.map");
00949   if (const FileEntry *ModuleMapFile = FileMgr.getFile(ModuleMapFileName)) {
00950     // We have found a module map file. Try to parse it.
00951     if (ModMap.parseModuleMapFile(ModuleMapFile)) {
00952       // No suitable module map.
00953       DirectoryHasModuleMap[Dir] = false;
00954       return LMM_InvalidModuleMap;
00955     }
00956 
00957     // This directory has a module map.
00958     DirectoryHasModuleMap[Dir] = true;
00959     
00960     // Check whether there is a private module map that we need to load as well.
00961     ModuleMapFileName.erase(ModuleMapFileName.begin() + ModuleMapDirNameLen,
00962                             ModuleMapFileName.end());
00963     llvm::sys::path::append(ModuleMapFileName, "module_private.map");
00964     if (const FileEntry *PrivateModuleMapFile
00965                                         = FileMgr.getFile(ModuleMapFileName)) {
00966       if (ModMap.parseModuleMapFile(PrivateModuleMapFile)) {
00967         // No suitable module map.
00968         DirectoryHasModuleMap[Dir] = false;
00969         return LMM_InvalidModuleMap;
00970       }      
00971     }
00972     
00973     return LMM_NewlyLoaded;
00974   }
00975   
00976   // No suitable module map.
00977   DirectoryHasModuleMap[Dir] = false;
00978   return LMM_InvalidModuleMap;
00979 }
00980 
00981 void HeaderSearch::collectAllModules(llvm::SmallVectorImpl<Module *> &Modules) {
00982   Modules.clear();
00983   
00984   // Load module maps for each of the header search directories.
00985   for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
00986     if (SearchDirs[Idx].isFramework()) {
00987       llvm::error_code EC;
00988       SmallString<128> DirNative;
00989       llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
00990                               DirNative);
00991       
00992       // Search each of the ".framework" directories to load them as modules.
00993       bool IsSystem = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
00994       for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
00995            Dir != DirEnd && !EC; Dir.increment(EC)) {
00996         if (llvm::sys::path::extension(Dir->path()) != ".framework")
00997           continue;
00998         
00999         const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(Dir->path());
01000         if (!FrameworkDir)
01001           continue;
01002         
01003         // Load this framework module.
01004         loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
01005                             IsSystem);
01006       }
01007       continue;
01008     }
01009     
01010     // FIXME: Deal with header maps.
01011     if (SearchDirs[Idx].isHeaderMap())
01012       continue;
01013     
01014     // Try to load a module map file for the search directory.
01015     loadModuleMapFile(SearchDirs[Idx].getDir());
01016     
01017     // Try to load module map files for immediate subdirectories of this search
01018     // directory.
01019     llvm::error_code EC;
01020     SmallString<128> DirNative;
01021     llvm::sys::path::native(SearchDirs[Idx].getDir()->getName(), DirNative);
01022     for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
01023          Dir != DirEnd && !EC; Dir.increment(EC)) {
01024       loadModuleMapFile(Dir->path());
01025     }
01026   }
01027   
01028   // Populate the list of modules.
01029   for (ModuleMap::module_iterator M = ModMap.module_begin(), 
01030                                MEnd = ModMap.module_end();
01031        M != MEnd; ++M) {
01032     Modules.push_back(M->getValue());
01033   }
01034 }
01035