#include "clang/Lex/HeaderSearch.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/DirectoryLookup.h"
#include "clang/Lex/ExternalPreprocessorSource.h"
#include "clang/Lex/HeaderMap.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Lex/LexDiagnostic.h"
#include "clang/Lex/ModuleMap.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Capacity.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/VirtualFileSystem.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <string>
#include <system_error>
#include <utility>
using namespace clang;
#define DEBUG_TYPE "file-search"
ALWAYS_ENABLED_STATISTIC(NumIncluded, "Number of attempted #includes.");
ALWAYS_ENABLED_STATISTIC(
NumMultiIncludeFileOptzn,
"Number of #includes skipped due to the multi-include optimization.");
ALWAYS_ENABLED_STATISTIC(NumFrameworkLookups, "Number of framework lookups.");
ALWAYS_ENABLED_STATISTIC(NumSubFrameworkLookups,
"Number of subframework lookups.");
const IdentifierInfo *
HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {
if (ControllingMacro) {
if (ControllingMacro->isOutOfDate()) {
assert(External && "We must have an external source if we have a "
"controlling macro that is out of date.");
External->updateOutOfDateIdentifier(
*const_cast<IdentifierInfo *>(ControllingMacro));
}
return ControllingMacro;
}
if (!ControllingMacroID || !External)
return nullptr;
ControllingMacro = External->GetIdentifier(ControllingMacroID);
return ControllingMacro;
}
ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() = default;
HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
SourceManager &SourceMgr, DiagnosticsEngine &Diags,
const LangOptions &LangOpts,
const TargetInfo *Target)
: HSOpts(std::move(HSOpts)), Diags(Diags),
FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
ModMap(SourceMgr, Diags, LangOpts, Target, *this) {}
void HeaderSearch::PrintStats() {
llvm::errs() << "\n*** HeaderSearch Stats:\n"
<< FileInfo.size() << " files tracked.\n";
unsigned NumOnceOnlyFiles = 0;
for (unsigned i = 0, e = FileInfo.size(); i != e; ++i)
NumOnceOnlyFiles += (FileInfo[i].isPragmaOnce || FileInfo[i].isImport);
llvm::errs() << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
llvm::errs() << " " << NumIncluded << " #include/#include_next/#import.\n"
<< " " << NumMultiIncludeFileOptzn
<< " #includes skipped due to the multi-include optimization.\n";
llvm::errs() << NumFrameworkLookups << " framework lookups.\n"
<< NumSubFrameworkLookups << " subframework lookups.\n";
}
void HeaderSearch::SetSearchPaths(
std::vector<DirectoryLookup> dirs, unsigned int angledDirIdx,
unsigned int systemDirIdx, bool noCurDirSearch,
llvm::DenseMap<unsigned int, unsigned int> searchDirToHSEntry) {
assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&
"Directory indices are unordered");
SearchDirs = std::move(dirs);
SearchDirsUsage.assign(SearchDirs.size(), false);
AngledDirIdx = angledDirIdx;
SystemDirIdx = systemDirIdx;
NoCurDirSearch = noCurDirSearch;
SearchDirToHSEntry = std::move(searchDirToHSEntry);
}
void HeaderSearch::AddSearchPath(const DirectoryLookup &dir, bool isAngled) {
unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx;
SearchDirs.insert(SearchDirs.begin() + idx, dir);
SearchDirsUsage.insert(SearchDirsUsage.begin() + idx, false);
if (!isAngled)
AngledDirIdx++;
SystemDirIdx++;
}
std::vector<bool> HeaderSearch::computeUserEntryUsage() const {
std::vector<bool> UserEntryUsage(HSOpts->UserEntries.size());
for (unsigned I = 0, E = SearchDirsUsage.size(); I < E; ++I) {
if (SearchDirsUsage[I]) {
auto UserEntryIdxIt = SearchDirToHSEntry.find(I);
if (UserEntryIdxIt != SearchDirToHSEntry.end())
UserEntryUsage[UserEntryIdxIt->second] = true;
}
}
return UserEntryUsage;
}
const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
if (!HeaderMaps.empty()) {
for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
if (HeaderMaps[i].first == FE)
return HeaderMaps[i].second.get();
}
if (std::unique_ptr<HeaderMap> HM = HeaderMap::Create(FE, FileMgr)) {
HeaderMaps.emplace_back(FE, std::move(HM));
return HeaderMaps.back().second.get();
}
return nullptr;
}
void HeaderSearch::getHeaderMapFileNames(
SmallVectorImpl<std::string> &Names) const {
for (auto &HM : HeaderMaps)
Names.push_back(std::string(HM.first->getName()));
}
std::string HeaderSearch::getCachedModuleFileName(Module *Module) {
const FileEntry *ModuleMap =
getModuleMap().getModuleMapFileForUniquing(Module);
if (ModuleMap == nullptr)
return {};
return getCachedModuleFileName(Module->Name, ModuleMap->getName());
}
std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,
bool FileMapOnly) {
auto i(HSOpts->PrebuiltModuleFiles.find(ModuleName));
if (i != HSOpts->PrebuiltModuleFiles.end())
return i->second;
if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())
return {};
for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
SmallString<256> Result(Dir);
llvm::sys::fs::make_absolute(Result);
if (ModuleName.contains(':'))
llvm::sys::path::append(Result, ModuleName.split(':').first + "-" +
ModuleName.split(':').second +
".pcm");
else
llvm::sys::path::append(Result, ModuleName + ".pcm");
if (getFileMgr().getFile(Result.str()))
return std::string(Result);
}
return {};
}
std::string HeaderSearch::getPrebuiltImplicitModuleFileName(Module *Module) {
const FileEntry *ModuleMap =
getModuleMap().getModuleMapFileForUniquing(Module);
StringRef ModuleName = Module->Name;
StringRef ModuleMapPath = ModuleMap->getName();
StringRef ModuleCacheHash = HSOpts->DisableModuleHash ? "" : getModuleHash();
for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
SmallString<256> CachePath(Dir);
llvm::sys::fs::make_absolute(CachePath);
llvm::sys::path::append(CachePath, ModuleCacheHash);
std::string FileName =
getCachedModuleFileNameImpl(ModuleName, ModuleMapPath, CachePath);
if (!FileName.empty() && getFileMgr().getFile(FileName))
return FileName;
}
return {};
}
std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,
StringRef ModuleMapPath) {
return getCachedModuleFileNameImpl(ModuleName, ModuleMapPath,
getModuleCachePath());
}
std::string HeaderSearch::getCachedModuleFileNameImpl(StringRef ModuleName,
StringRef ModuleMapPath,
StringRef CachePath) {
if (CachePath.empty())
return {};
SmallString<256> Result(CachePath);
llvm::sys::fs::make_absolute(Result);
if (HSOpts->DisableModuleHash) {
llvm::sys::path::append(Result, ModuleName + ".pcm");
} else {
std::string Parent =
std::string(llvm::sys::path::parent_path(ModuleMapPath));
if (Parent.empty())
Parent = ".";
auto Dir = FileMgr.getDirectory(Parent);
if (!Dir)
return {};
auto DirName = FileMgr.getCanonicalName(*Dir);
auto FileName = llvm::sys::path::filename(ModuleMapPath);
llvm::hash_code Hash =
llvm::hash_combine(DirName.lower(), FileName.lower());
SmallString<128> HashStr;
llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, 36);
llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
}
return Result.str().str();
}
Module *HeaderSearch::lookupModule(StringRef ModuleName,
SourceLocation ImportLoc, bool AllowSearch,
bool AllowExtraModuleMapSearch) {
Module *Module = ModMap.findModule(ModuleName);
if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
return Module;
StringRef SearchName = ModuleName;
Module = lookupModule(ModuleName, SearchName, ImportLoc,
AllowExtraModuleMapSearch);
if (!Module && SearchName.consume_back("_Private"))
Module = lookupModule(ModuleName, SearchName, ImportLoc,
AllowExtraModuleMapSearch);
if (!Module && SearchName.consume_back("Private"))
Module = lookupModule(ModuleName, SearchName, ImportLoc,
AllowExtraModuleMapSearch);
return Module;
}
Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName,
SourceLocation ImportLoc,
bool AllowExtraModuleMapSearch) {
Module *Module = nullptr;
for (DirectoryLookup Dir : search_dir_range()) {
if (Dir.isFramework()) {
SmallString<128> FrameworkDirName;
FrameworkDirName += Dir.getFrameworkDir()->getName();
llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
if (auto FrameworkDir =
FileMgr.getOptionalDirectoryRef(FrameworkDirName)) {
bool IsSystem = Dir.getDirCharacteristic() != SrcMgr::C_User;
Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem);
if (Module)
break;
}
}
if (!Dir.isNormalDir())
continue;
bool IsSystem = Dir.isSystemHeaderDirectory();
DirectoryEntryRef NormalDir = *Dir.getDirRef();
if (loadModuleMapFile(NormalDir, IsSystem,
false) == LMM_NewlyLoaded) {
Module = ModMap.findModule(ModuleName);
if (Module)
break;
}
SmallString<128> NestedModuleMapDirName;
NestedModuleMapDirName = Dir.getDir()->getName();
llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
false) == LMM_NewlyLoaded){
Module = ModMap.findModule(ModuleName);
if (Module)
break;
}
if (Dir.haveSearchedAllModuleMaps())
continue;
if (AllowExtraModuleMapSearch)
loadSubdirectoryModuleMaps(Dir);
Module = ModMap.findModule(ModuleName);
if (Module)
break;
}
return Module;
}
StringRef DirectoryLookup::getName() const {
if (isNormalDir())
return getDir()->getName();
if (isFramework())
return getFrameworkDir()->getName();
assert(isHeaderMap() && "Unknown DirectoryLookup");
return getHeaderMap()->getFileName();
}
Optional<FileEntryRef> HeaderSearch::getFileAndSuggestModule(
StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
bool IsSystemHeaderDir, Module *RequestingModule,
ModuleMap::KnownHeader *SuggestedModule) {
auto File = getFileMgr().getFileRef(FileName, true);
if (!File) {
std::error_code EC = llvm::errorToErrorCode(File.takeError());
if (EC != llvm::errc::no_such_file_or_directory &&
EC != llvm::errc::invalid_argument &&
EC != llvm::errc::is_a_directory && EC != llvm::errc::not_a_directory) {
Diags.Report(IncludeLoc, diag::err_cannot_open_file)
<< FileName << EC.message();
}
return None;
}
if (!findUsableModuleForHeader(
&File->getFileEntry(), Dir ? Dir : File->getFileEntry().getDir(),
RequestingModule, SuggestedModule, IsSystemHeaderDir))
return None;
return *File;
}
Optional<FileEntryRef> DirectoryLookup::LookupFile(
StringRef &Filename, HeaderSearch &HS, SourceLocation IncludeLoc,
SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound,
bool &IsInHeaderMap, SmallVectorImpl<char> &MappedName) const {
InUserSpecifiedSystemFramework = false;
IsInHeaderMap = false;
MappedName.clear();
SmallString<1024> TmpDir;
if (isNormalDir()) {
TmpDir = getDirRef()->getName();
llvm::sys::path::append(TmpDir, Filename);
if (SearchPath) {
StringRef SearchPathRef(getDirRef()->getName());
SearchPath->clear();
SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
}
if (RelativePath) {
RelativePath->clear();
RelativePath->append(Filename.begin(), Filename.end());
}
return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
isSystemHeaderDirectory(),
RequestingModule, SuggestedModule);
}
if (isFramework())
return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
RequestingModule, SuggestedModule,
InUserSpecifiedSystemFramework, IsFrameworkFound);
assert(isHeaderMap() && "Unknown directory lookup");
const HeaderMap *HM = getHeaderMap();
SmallString<1024> Path;
StringRef Dest = HM->lookupFilename(Filename, Path);
if (Dest.empty())
return None;
IsInHeaderMap = true;
auto FixupSearchPath = [&]() {
if (SearchPath) {
StringRef SearchPathRef(getName());
SearchPath->clear();
SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
}
if (RelativePath) {
RelativePath->clear();
RelativePath->append(Filename.begin(), Filename.end());
}
};
if (llvm::sys::path::is_relative(Dest)) {
MappedName.append(Dest.begin(), Dest.end());
Filename = StringRef(MappedName.begin(), MappedName.size());
Dest = HM->lookupFilename(Filename, Path);
}
if (auto Res = HS.getFileMgr().getOptionalFileRef(Dest)) {
FixupSearchPath();
return *Res;
}
HS.noteLookupUsage(HS.searchDirIdx(*this), IncludeLoc);
return None;
}
static Optional<DirectoryEntryRef>
getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
SmallVectorImpl<std::string> &SubmodulePath) {
assert(llvm::sys::path::extension(DirName) == ".framework" &&
"Not a framework directory");
auto TopFrameworkDir = FileMgr.getOptionalDirectoryRef(DirName);
if (TopFrameworkDir)
DirName = FileMgr.getCanonicalName(*TopFrameworkDir);
do {
DirName = llvm::sys::path::parent_path(DirName);
if (DirName.empty())
break;
auto Dir = FileMgr.getOptionalDirectoryRef(DirName);
if (!Dir)
break;
if (llvm::sys::path::extension(DirName) == ".framework") {
SubmodulePath.push_back(std::string(llvm::sys::path::stem(DirName)));
TopFrameworkDir = *Dir;
}
} while (true);
return TopFrameworkDir;
}
static bool needModuleLookup(Module *RequestingModule,
bool HasSuggestedModule) {
return HasSuggestedModule ||
(RequestingModule && RequestingModule->NoUndeclaredIncludes);
}
Optional<FileEntryRef> DirectoryLookup::DoFrameworkLookup(
StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
ModuleMap::KnownHeader *SuggestedModule,
bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound) const {
FileManager &FileMgr = HS.getFileMgr();
size_t SlashPos = Filename.find('/');
if (SlashPos == StringRef::npos)
return None;
FrameworkCacheEntry &CacheEntry =
HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDirRef())
return None;
SmallString<1024> FrameworkName;
FrameworkName += getFrameworkDirRef()->getName();
if (FrameworkName.empty() || FrameworkName.back() != '/')
FrameworkName.push_back('/');
StringRef ModuleName(Filename.begin(), SlashPos);
FrameworkName += ModuleName;
FrameworkName += ".framework/";
if (!CacheEntry.Directory) {
++NumFrameworkLookups;
auto Dir = FileMgr.getDirectory(FrameworkName);
if (!Dir)
return None;
CacheEntry.Directory = getFrameworkDirRef();
if (getDirCharacteristic() == SrcMgr::C_User) {
SmallString<1024> SystemFrameworkMarker(FrameworkName);
SystemFrameworkMarker += ".system_framework";
if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
CacheEntry.IsUserSpecifiedSystemFramework = true;
}
}
}
InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
IsFrameworkFound = CacheEntry.Directory.has_value();
if (RelativePath) {
RelativePath->clear();
RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
}
unsigned OrigSize = FrameworkName.size();
FrameworkName += "Headers/";
if (SearchPath) {
SearchPath->clear();
SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
}
FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
auto File =
FileMgr.getOptionalFileRef(FrameworkName, !SuggestedModule);
if (!File) {
const char *Private = "Private";
FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
Private+strlen(Private));
if (SearchPath)
SearchPath->insert(SearchPath->begin()+OrigSize, Private,
Private+strlen(Private));
File = FileMgr.getOptionalFileRef(FrameworkName,
!SuggestedModule);
}
if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
StringRef FrameworkPath = File->getFileEntry().getDir()->getName();
bool FoundFramework = false;
do {
auto Dir = FileMgr.getDirectory(FrameworkPath);
if (!Dir)
break;
if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
FoundFramework = true;
break;
}
FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
if (FrameworkPath.empty())
break;
} while (true);
bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
if (FoundFramework) {
if (!HS.findUsableModuleForFrameworkHeader(
&File->getFileEntry(), FrameworkPath, RequestingModule,
SuggestedModule, IsSystem))
return None;
} else {
if (!HS.findUsableModuleForHeader(&File->getFileEntry(), getDir(),
RequestingModule, SuggestedModule,
IsSystem))
return None;
}
}
if (File)
return *File;
return None;
}
void HeaderSearch::cacheLookupSuccess(LookupFileCacheInfo &CacheLookup,
ConstSearchDirIterator HitIt,
SourceLocation Loc) {
CacheLookup.HitIt = HitIt;
noteLookupUsage(HitIt.Idx, Loc);
}
void HeaderSearch::noteLookupUsage(unsigned HitIdx, SourceLocation Loc) {
SearchDirsUsage[HitIdx] = true;
auto UserEntryIdxIt = SearchDirToHSEntry.find(HitIdx);
if (UserEntryIdxIt != SearchDirToHSEntry.end())
Diags.Report(Loc, diag::remark_pp_search_path_usage)
<< HSOpts->UserEntries[UserEntryIdxIt->second].Path;
}
void HeaderSearch::setTarget(const TargetInfo &Target) {
ModMap.setTarget(Target);
}
static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
const FileEntry *MSFE, const FileEntry *FE,
SourceLocation IncludeLoc) {
if (MSFE && FE != MSFE) {
Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
return true;
}
return false;
}
static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
assert(!Str.empty());
char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
std::copy(Str.begin(), Str.end(), CopyStr);
CopyStr[Str.size()] = '\0';
return CopyStr;
}
static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader,
SmallVectorImpl<char> &FrameworkName,
SmallVectorImpl<char> &IncludeSpelling) {
using namespace llvm::sys;
path::const_iterator I = path::begin(Path);
path::const_iterator E = path::end(Path);
IsPrivateHeader = false;
int FoundComp = 0;
while (I != E) {
if (*I == "Headers") {
++FoundComp;
} else if (*I == "PrivateHeaders") {
++FoundComp;
IsPrivateHeader = true;
} else if (I->endswith(".framework")) {
StringRef Name = I->drop_back(10); FrameworkName.clear();
FrameworkName.append(Name.begin(), Name.end());
IncludeSpelling.clear();
IncludeSpelling.append(Name.begin(), Name.end());
FoundComp = 1;
} else if (FoundComp >= 2) {
IncludeSpelling.push_back('/');
IncludeSpelling.append(I->begin(), I->end());
}
++I;
}
return !FrameworkName.empty() && FoundComp >= 2;
}
static void
diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc,
StringRef Includer, StringRef IncludeFilename,
const FileEntry *IncludeFE, bool isAngled = false,
bool FoundByHeaderMap = false) {
bool IsIncluderPrivateHeader = false;
SmallString<128> FromFramework, ToFramework;
SmallString<128> FromIncludeSpelling, ToIncludeSpelling;
if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework,
FromIncludeSpelling))
return;
bool IsIncludeePrivateHeader = false;
bool IsIncludeeInFramework =
isFrameworkStylePath(IncludeFE->getName(), IsIncludeePrivateHeader,
ToFramework, ToIncludeSpelling);
if (!isAngled && !FoundByHeaderMap) {
SmallString<128> NewInclude("<");
if (IsIncludeeInFramework) {
NewInclude += ToIncludeSpelling;
NewInclude += ">";
} else {
NewInclude += IncludeFilename;
NewInclude += ">";
}
Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header)
<< IncludeFilename
<< FixItHint::CreateReplacement(IncludeLoc, NewInclude);
}
if (!IsIncluderPrivateHeader && IsIncludeeInFramework &&
IsIncludeePrivateHeader && FromFramework == ToFramework)
Diags.Report(IncludeLoc, diag::warn_framework_include_private_from_public)
<< IncludeFilename;
}
Optional<FileEntryRef> HeaderSearch::LookupFile(
StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
ConstSearchDirIterator FromDir, ConstSearchDirIterator *CurDirArg,
ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
bool *IsMapped, bool *IsFrameworkFound, bool SkipCache,
bool BuildSystemModule) {
ConstSearchDirIterator CurDirLocal = nullptr;
ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal;
if (IsMapped)
*IsMapped = false;
if (IsFrameworkFound)
*IsFrameworkFound = false;
if (SuggestedModule)
*SuggestedModule = ModuleMap::KnownHeader();
if (llvm::sys::path::is_absolute(Filename)) {
CurDir = nullptr;
if (FromDir)
return None;
if (SearchPath)
SearchPath->clear();
if (RelativePath) {
RelativePath->clear();
RelativePath->append(Filename.begin(), Filename.end());
}
return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
false,
RequestingModule, SuggestedModule);
}
ModuleMap::KnownHeader MSSuggestedModule;
Optional<FileEntryRef> MSFE;
if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
SmallString<1024> TmpDir;
bool First = true;
for (const auto &IncluderAndDir : Includers) {
const FileEntry *Includer = IncluderAndDir.first;
TmpDir = IncluderAndDir.second->getName();
TmpDir.push_back('/');
TmpDir.append(Filename.begin(), Filename.end());
bool IncluderIsSystemHeader =
Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
BuildSystemModule;
if (Optional<FileEntryRef> FE = getFileAndSuggestModule(
TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
RequestingModule, SuggestedModule)) {
if (!Includer) {
assert(First && "only first includer can have no file");
return FE;
}
HeaderFileInfo &FromHFI = getFileInfo(Includer);
unsigned DirInfo = FromHFI.DirInfo;
bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
StringRef Framework = FromHFI.Framework;
HeaderFileInfo &ToHFI = getFileInfo(&FE->getFileEntry());
ToHFI.DirInfo = DirInfo;
ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
ToHFI.Framework = Framework;
if (SearchPath) {
StringRef SearchPathRef(IncluderAndDir.second->getName());
SearchPath->clear();
SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
}
if (RelativePath) {
RelativePath->clear();
RelativePath->append(Filename.begin(), Filename.end());
}
if (First) {
diagnoseFrameworkInclude(Diags, IncludeLoc,
IncluderAndDir.second->getName(), Filename,
&FE->getFileEntry());
return FE;
}
if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
return FE;
} else {
MSFE = FE;
if (SuggestedModule) {
MSSuggestedModule = *SuggestedModule;
*SuggestedModule = ModuleMap::KnownHeader();
}
break;
}
}
First = false;
}
}
CurDir = nullptr;
ConstSearchDirIterator It =
isAngled ? angled_dir_begin() : search_dir_begin();
if (FromDir)
It = FromDir;
LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
ConstSearchDirIterator NextIt = std::next(It);
if (!SkipCache && CacheLookup.StartIt == NextIt) {
if (CacheLookup.HitIt)
It = CacheLookup.HitIt;
if (CacheLookup.MappedName) {
Filename = CacheLookup.MappedName;
if (IsMapped)
*IsMapped = true;
}
} else {
CacheLookup.reset(NextIt);
}
SmallString<64> MappedName;
for (; It != search_dir_end(); ++It) {
bool InUserSpecifiedSystemFramework = false;
bool IsInHeaderMap = false;
bool IsFrameworkFoundInDir = false;
Optional<FileEntryRef> File = It->LookupFile(
Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
SuggestedModule, InUserSpecifiedSystemFramework, IsFrameworkFoundInDir,
IsInHeaderMap, MappedName);
if (!MappedName.empty()) {
assert(IsInHeaderMap && "MappedName should come from a header map");
CacheLookup.MappedName =
copyString(MappedName, LookupFileCache.getAllocator());
}
if (IsMapped)
*IsMapped |= (!MappedName.empty() || (IsInHeaderMap && File));
if (IsFrameworkFound)
*IsFrameworkFound |= (IsFrameworkFoundInDir && !CacheLookup.MappedName);
if (!File)
continue;
CurDir = It;
const auto FE = &File->getFileEntry();
IncludeNames[FE] = Filename;
HeaderFileInfo &HFI = getFileInfo(FE);
HFI.DirInfo = CurDir->getDirCharacteristic();
if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
HFI.DirInfo = SrcMgr::C_System;
for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
: SrcMgr::C_User;
break;
}
}
if (CurDir->isHeaderMap() && isAngled) {
size_t SlashPos = Filename.find('/');
if (SlashPos != StringRef::npos)
HFI.Framework =
getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));
if (CurDir->isIndexHeaderMap())
HFI.IndexHeaderMapHeader = 1;
} else if (CurDir->isFramework()) {
size_t SlashPos = Filename.find('/');
if (SlashPos != StringRef::npos)
HFI.Framework =
getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));
}
if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
&File->getFileEntry(), IncludeLoc)) {
if (SuggestedModule)
*SuggestedModule = MSSuggestedModule;
return MSFE;
}
bool FoundByHeaderMap = !IsMapped ? false : *IsMapped;
if (!Includers.empty())
diagnoseFrameworkInclude(
Diags, IncludeLoc, Includers.front().second->getName(), Filename,
&File->getFileEntry(), isAngled, FoundByHeaderMap);
cacheLookupSuccess(CacheLookup, It, IncludeLoc);
return File;
}
if (!Includers.empty() && Includers.front().first && !isAngled &&
!Filename.contains('/')) {
HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
if (IncludingHFI.IndexHeaderMapHeader) {
SmallString<128> ScratchFilename;
ScratchFilename += IncludingHFI.Framework;
ScratchFilename += '/';
ScratchFilename += Filename;
Optional<FileEntryRef> File = LookupFile(
ScratchFilename, IncludeLoc, true, FromDir, &CurDir,
Includers.front(), SearchPath, RelativePath, RequestingModule,
SuggestedModule, IsMapped, nullptr);
if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
File ? &File->getFileEntry() : nullptr,
IncludeLoc)) {
if (SuggestedModule)
*SuggestedModule = MSSuggestedModule;
return MSFE;
}
cacheLookupSuccess(LookupFileCache[Filename],
LookupFileCache[ScratchFilename].HitIt, IncludeLoc);
return File;
}
}
if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
nullptr, IncludeLoc)) {
if (SuggestedModule)
*SuggestedModule = MSSuggestedModule;
return MSFE;
}
CacheLookup.HitIt = search_dir_end();
return None;
}
Optional<FileEntryRef> HeaderSearch::LookupSubframeworkHeader(
StringRef Filename, const FileEntry *ContextFileEnt,
SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule) {
assert(ContextFileEnt && "No context file?");
size_t SlashPos = Filename.find('/');
if (SlashPos == StringRef::npos)
return None;
StringRef ContextName = ContextFileEnt->getName();
const unsigned DotFrameworkLen = 10;
auto FrameworkPos = ContextName.find(".framework");
if (FrameworkPos == StringRef::npos ||
(ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
return None;
SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
FrameworkPos +
DotFrameworkLen + 1);
FrameworkName += "Frameworks/";
FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
FrameworkName += ".framework/";
auto &CacheLookup =
*FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
FrameworkCacheEntry())).first;
if (CacheLookup.second.Directory &&
CacheLookup.first().size() == FrameworkName.size() &&
memcmp(CacheLookup.first().data(), &FrameworkName[0],
CacheLookup.first().size()) != 0)
return None;
if (!CacheLookup.second.Directory) {
++NumSubFrameworkLookups;
auto Dir = FileMgr.getOptionalDirectoryRef(FrameworkName);
if (!Dir)
return None;
CacheLookup.second.Directory = Dir;
}
if (RelativePath) {
RelativePath->clear();
RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
}
SmallString<1024> HeadersFilename(FrameworkName);
HeadersFilename += "Headers/";
if (SearchPath) {
SearchPath->clear();
SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
}
HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
auto File = FileMgr.getOptionalFileRef(HeadersFilename, true);
if (!File) {
HeadersFilename = FrameworkName;
HeadersFilename += "PrivateHeaders/";
if (SearchPath) {
SearchPath->clear();
SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
}
HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
File = FileMgr.getOptionalFileRef(HeadersFilename, true);
if (!File)
return None;
}
unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
getFileInfo(&File->getFileEntry()).DirInfo = DirInfo;
FrameworkName.pop_back(); if (!findUsableModuleForFrameworkHeader(&File->getFileEntry(), FrameworkName,
RequestingModule, SuggestedModule,
false))
return None;
return *File;
}
static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
const HeaderFileInfo &OtherHFI) {
assert(OtherHFI.External && "expected to merge external HFI");
HFI.isImport |= OtherHFI.isImport;
HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
HFI.isModuleHeader |= OtherHFI.isModuleHeader;
if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
HFI.ControllingMacro = OtherHFI.ControllingMacro;
HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
}
HFI.DirInfo = OtherHFI.DirInfo;
HFI.External = (!HFI.IsValid || HFI.External);
HFI.IsValid = true;
HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
if (HFI.Framework.empty())
HFI.Framework = OtherHFI.Framework;
}
HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
if (FE->getUID() >= FileInfo.size())
FileInfo.resize(FE->getUID() + 1);
HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
if (ExternalSource && !HFI->Resolved) {
auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
if (ExternalHFI.IsValid) {
HFI->Resolved = true;
if (ExternalHFI.External)
mergeHeaderFileInfo(*HFI, ExternalHFI);
}
}
HFI->IsValid = true;
HFI->External = false;
return *HFI;
}
const HeaderFileInfo *
HeaderSearch::getExistingFileInfo(const FileEntry *FE,
bool WantExternal) const {
HeaderFileInfo *HFI;
if (ExternalSource) {
if (FE->getUID() >= FileInfo.size()) {
if (!WantExternal)
return nullptr;
FileInfo.resize(FE->getUID() + 1);
}
HFI = &FileInfo[FE->getUID()];
if (!WantExternal && (!HFI->IsValid || HFI->External))
return nullptr;
if (!HFI->Resolved) {
auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
if (ExternalHFI.IsValid) {
HFI->Resolved = true;
if (ExternalHFI.External)
mergeHeaderFileInfo(*HFI, ExternalHFI);
}
}
} else if (FE->getUID() >= FileInfo.size()) {
return nullptr;
} else {
HFI = &FileInfo[FE->getUID()];
}
if (!HFI->IsValid || (HFI->External && !WantExternal))
return nullptr;
return HFI;
}
bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
if (auto *HFI = getExistingFileInfo(File))
return HFI->isPragmaOnce || HFI->ControllingMacro ||
HFI->ControllingMacroID;
return false;
}
void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
ModuleMap::ModuleHeaderRole Role,
bool isCompilingModuleHeader) {
bool isModularHeader = !(Role & ModuleMap::TextualHeader);
if (!isCompilingModuleHeader) {
if (!isModularHeader)
return;
auto *HFI = getExistingFileInfo(FE);
if (HFI && HFI->isModuleHeader)
return;
}
auto &HFI = getFileInfo(FE);
HFI.isModuleHeader |= isModularHeader;
HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
}
bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
const FileEntry *File, bool isImport,
bool ModulesEnabled, Module *M,
bool &IsFirstIncludeOfFile) {
++NumIncluded;
IsFirstIncludeOfFile = false;
HeaderFileInfo &FileInfo = getFileInfo(File);
auto TryEnterImported = [&]() -> bool {
if (!ModulesEnabled)
return false;
ModMap.resolveHeaderDirectives(File);
bool TryEnterHdr = false;
if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
TryEnterHdr = ModMap.isBuiltinHeader(File);
if (!FileInfo.isModuleHeader &&
FileInfo.getControllingMacro(ExternalLookup))
TryEnterHdr = true;
return TryEnterHdr;
};
if (isImport) {
FileInfo.isImport = true;
if (PP.alreadyIncluded(File) && !TryEnterImported())
return false;
} else {
if ((FileInfo.isPragmaOnce || FileInfo.isImport) && !TryEnterImported())
return false;
}
if (const IdentifierInfo *ControllingMacro
= FileInfo.getControllingMacro(ExternalLookup)) {
if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
: PP.isMacroDefined(ControllingMacro)) {
++NumMultiIncludeFileOptzn;
return false;
}
}
IsFirstIncludeOfFile = PP.markIncluded(File);
return true;
}
size_t HeaderSearch::getTotalMemory() const {
return SearchDirs.capacity()
+ llvm::capacity_in_bytes(FileInfo)
+ llvm::capacity_in_bytes(HeaderMaps)
+ LookupFileCache.getAllocator().getTotalMemory()
+ FrameworkMap.getAllocator().getTotalMemory();
}
unsigned HeaderSearch::searchDirIdx(const DirectoryLookup &DL) const {
return &DL - &*SearchDirs.begin();
}
StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
return FrameworkNames.insert(Framework).first->first();
}
StringRef HeaderSearch::getIncludeNameForHeader(const FileEntry *File) const {
auto It = IncludeNames.find(File);
if (It == IncludeNames.end())
return {};
return It->second;
}
bool HeaderSearch::hasModuleMap(StringRef FileName,
const DirectoryEntry *Root,
bool IsSystem) {
if (!HSOpts->ImplicitModuleMaps)
return false;
SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
StringRef DirName = FileName;
do {
DirName = llvm::sys::path::parent_path(DirName);
if (DirName.empty())
return false;
auto Dir = FileMgr.getOptionalDirectoryRef(DirName);
if (!Dir)
return false;
switch (loadModuleMapFile(*Dir, IsSystem,
llvm::sys::path::extension(Dir->getName()) ==
".framework")) {
case LMM_NewlyLoaded:
case LMM_AlreadyLoaded:
for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
DirectoryHasModuleMap[FixUpDirectories[I]] = true;
return true;
case LMM_NoDirectory:
case LMM_InvalidModuleMap:
break;
}
if (*Dir == Root)
return false;
FixUpDirectories.push_back(*Dir);
} while (true);
}
ModuleMap::KnownHeader
HeaderSearch::findModuleForHeader(const FileEntry *File,
bool AllowTextual) const {
if (ExternalSource) {
(void)getExistingFileInfo(File);
}
return ModMap.findModuleForHeader(File, AllowTextual);
}
ArrayRef<ModuleMap::KnownHeader>
HeaderSearch::findAllModulesForHeader(const FileEntry *File) const {
if (ExternalSource) {
(void)getExistingFileInfo(File);
}
return ModMap.findAllModulesForHeader(File);
}
static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
Module *RequestingModule,
ModuleMap::KnownHeader *SuggestedModule) {
ModuleMap::KnownHeader Module =
HS.findModuleForHeader(File, true);
if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
HS.getModuleMap().resolveUses(RequestingModule, false);
if (!RequestingModule->directlyUses(Module.getModule())) {
if (HS.getModuleMap().isBuiltinHeader(File)) {
if (SuggestedModule)
*SuggestedModule = ModuleMap::KnownHeader();
return true;
}
return false;
}
}
if (SuggestedModule)
*SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
? ModuleMap::KnownHeader()
: Module;
return true;
}
bool HeaderSearch::findUsableModuleForHeader(
const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
return suggestModule(*this, File, RequestingModule, SuggestedModule);
}
return true;
}
bool HeaderSearch::findUsableModuleForFrameworkHeader(
const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
if (needModuleLookup(RequestingModule, SuggestedModule)) {
SmallVector<std::string, 4> SubmodulePath;
Optional<DirectoryEntryRef> TopFrameworkDir =
::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
assert(TopFrameworkDir && "Could not find the top-most framework dir");
StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
loadFrameworkModule(ModuleName, *TopFrameworkDir, IsSystemFramework);
return suggestModule(*this, File, RequestingModule, SuggestedModule);
}
return true;
}
static const FileEntry *getPrivateModuleMap(const FileEntry *File,
FileManager &FileMgr) {
StringRef Filename = llvm::sys::path::filename(File->getName());
SmallString<128> PrivateFilename(File->getDir()->getName());
if (Filename == "module.map")
llvm::sys::path::append(PrivateFilename, "module_private.map");
else if (Filename == "module.modulemap")
llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
else
return nullptr;
if (auto File = FileMgr.getFile(PrivateFilename))
return *File;
return nullptr;
}
bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
FileID ID, unsigned *Offset,
StringRef OriginalModuleMapFile) {
Optional<DirectoryEntryRef> Dir;
if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) {
Dir = FileMgr.getOptionalDirectoryRef(".");
} else {
if (!OriginalModuleMapFile.empty()) {
Dir = FileMgr.getOptionalDirectoryRef(
llvm::sys::path::parent_path(OriginalModuleMapFile));
if (!Dir) {
auto FakeFile = FileMgr.getVirtualFileRef(OriginalModuleMapFile, 0, 0);
Dir = FakeFile.getDir();
}
} else {
Dir = FileMgr.getOptionalDirectoryRef(File->getDir()->getName());
}
assert(Dir && "parent must exist");
StringRef DirName(Dir->getName());
if (llvm::sys::path::filename(DirName) == "Modules") {
DirName = llvm::sys::path::parent_path(DirName);
if (DirName.endswith(".framework"))
if (auto MaybeDir = FileMgr.getOptionalDirectoryRef(DirName))
Dir = *MaybeDir;
assert(Dir && "parent must exist");
}
}
assert(Dir && "module map home directory must exist");
switch (loadModuleMapFileImpl(File, IsSystem, *Dir, ID, Offset)) {
case LMM_AlreadyLoaded:
case LMM_NewlyLoaded:
return false;
case LMM_NoDirectory:
case LMM_InvalidModuleMap:
return true;
}
llvm_unreachable("Unknown load module map result");
}
HeaderSearch::LoadModuleMapResult
HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
DirectoryEntryRef Dir, FileID ID,
unsigned *Offset) {
assert(File && "expected FileEntry");
auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
if (!AddResult.second)
return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
LoadedModuleMaps[File] = false;
return LMM_InvalidModuleMap;
}
if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
LoadedModuleMaps[File] = false;
return LMM_InvalidModuleMap;
}
}
return LMM_NewlyLoaded;
}
const FileEntry *
HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
if (!HSOpts->ImplicitModuleMaps)
return nullptr;
SmallString<128> ModuleMapFileName(Dir->getName());
if (IsFramework)
llvm::sys::path::append(ModuleMapFileName, "Modules");
llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
if (auto F = FileMgr.getFile(ModuleMapFileName))
return *F;
ModuleMapFileName = Dir->getName();
llvm::sys::path::append(ModuleMapFileName, "module.map");
if (auto F = FileMgr.getFile(ModuleMapFileName))
return *F;
if (IsFramework) {
ModuleMapFileName = Dir->getName();
llvm::sys::path::append(ModuleMapFileName, "Modules",
"module.private.modulemap");
if (auto F = FileMgr.getFile(ModuleMapFileName))
return *F;
}
return nullptr;
}
Module *HeaderSearch::loadFrameworkModule(StringRef Name, DirectoryEntryRef Dir,
bool IsSystem) {
if (Module *Module = ModMap.findModule(Name))
return Module;
switch (loadModuleMapFile(Dir, IsSystem, true)) {
case LMM_InvalidModuleMap:
if (HSOpts->ImplicitModuleMaps)
ModMap.inferFrameworkModule(Dir, IsSystem, nullptr);
break;
case LMM_AlreadyLoaded:
case LMM_NoDirectory:
return nullptr;
case LMM_NewlyLoaded:
break;
}
return ModMap.findModule(Name);
}
HeaderSearch::LoadModuleMapResult
HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
bool IsFramework) {
if (auto Dir = FileMgr.getOptionalDirectoryRef(DirName))
return loadModuleMapFile(*Dir, IsSystem, IsFramework);
return LMM_NoDirectory;
}
HeaderSearch::LoadModuleMapResult
HeaderSearch::loadModuleMapFile(DirectoryEntryRef Dir, bool IsSystem,
bool IsFramework) {
auto KnownDir = DirectoryHasModuleMap.find(Dir);
if (KnownDir != DirectoryHasModuleMap.end())
return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
LoadModuleMapResult Result =
loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
if (Result == LMM_NewlyLoaded)
DirectoryHasModuleMap[Dir] = true;
else if (Result == LMM_InvalidModuleMap)
DirectoryHasModuleMap[Dir] = false;
return Result;
}
return LMM_InvalidModuleMap;
}
void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Modules.clear();
if (HSOpts->ImplicitModuleMaps) {
for (DirectoryLookup &DL : search_dir_range()) {
bool IsSystem = DL.isSystemHeaderDirectory();
if (DL.isFramework()) {
std::error_code EC;
SmallString<128> DirNative;
llvm::sys::path::native(DL.getFrameworkDir()->getName(), DirNative);
llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
DirEnd;
Dir != DirEnd && !EC; Dir.increment(EC)) {
if (llvm::sys::path::extension(Dir->path()) != ".framework")
continue;
auto FrameworkDir = FileMgr.getOptionalDirectoryRef(Dir->path());
if (!FrameworkDir)
continue;
loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir,
IsSystem);
}
continue;
}
if (DL.isHeaderMap())
continue;
loadModuleMapFile(*DL.getDirRef(), IsSystem, false);
loadSubdirectoryModuleMaps(DL);
}
}
llvm::transform(ModMap.modules(), std::back_inserter(Modules),
[](const auto &NameAndMod) { return NameAndMod.second; });
}
void HeaderSearch::loadTopLevelSystemModules() {
if (!HSOpts->ImplicitModuleMaps)
return;
for (const DirectoryLookup &DL : search_dir_range()) {
if (!DL.isNormalDir())
continue;
loadModuleMapFile(*DL.getDirRef(), DL.isSystemHeaderDirectory(),
DL.isFramework());
}
}
void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
assert(HSOpts->ImplicitModuleMaps &&
"Should not be loading subdirectory module maps");
if (SearchDir.haveSearchedAllModuleMaps())
return;
std::error_code EC;
SmallString<128> Dir = SearchDir.getDir()->getName();
FileMgr.makeAbsolutePath(Dir);
SmallString<128> DirNative;
llvm::sys::path::native(Dir, DirNative);
llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Dir != DirEnd && !EC; Dir.increment(EC)) {
bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";
if (IsFramework == SearchDir.isFramework())
loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
SearchDir.isFramework());
}
SearchDir.setSearchedAllModuleMaps(true);
}
std::string HeaderSearch::suggestPathToFileForDiagnostics(
const FileEntry *File, llvm::StringRef MainFile, bool *IsSystem) {
return suggestPathToFileForDiagnostics(File->getName(), "",
MainFile, IsSystem);
}
std::string HeaderSearch::suggestPathToFileForDiagnostics(
llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile,
bool *IsSystem) {
using namespace llvm::sys;
unsigned BestPrefixLength = 0;
auto CheckDir = [&](llvm::StringRef Dir) -> bool {
llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
if (!WorkingDir.empty() && !path::is_absolute(Dir))
fs::make_absolute(WorkingDir, DirPath);
path::remove_dots(DirPath, true);
Dir = DirPath;
for (auto NI = path::begin(File), NE = path::end(File),
DI = path::begin(Dir), DE = path::end(Dir);
; ++NI, ++DI) {
while (NI != NE && *NI == ".")
++NI;
if (NI == NE)
break;
while (DI != DE && *DI == ".")
++DI;
if (DI == DE) {
unsigned PrefixLength = NI - path::begin(File);
if (PrefixLength > BestPrefixLength) {
BestPrefixLength = PrefixLength;
return true;
}
break;
}
if (NI->size() == 1 && DI->size() == 1 &&
path::is_separator(NI->front()) && path::is_separator(DI->front()))
continue;
if (NI->endswith(".sdk") && DI->endswith(".sdk")) {
StringRef NBasename = path::stem(*NI);
StringRef DBasename = path::stem(*DI);
if (DBasename.startswith(NBasename))
continue;
}
if (*NI != *DI)
break;
}
return false;
};
bool BestPrefixIsFramework = false;
for (const DirectoryLookup &DL : search_dir_range()) {
if (DL.isNormalDir()) {
StringRef Dir = DL.getDir()->getName();
if (CheckDir(Dir)) {
if (IsSystem)
*IsSystem = BestPrefixLength && isSystem(DL.getDirCharacteristic());
BestPrefixIsFramework = false;
}
} else if (DL.isFramework()) {
StringRef Dir = DL.getFrameworkDir()->getName();
if (CheckDir(Dir)) {
if (IsSystem)
*IsSystem = BestPrefixLength && isSystem(DL.getDirCharacteristic());
BestPrefixIsFramework = true;
}
}
}
if (!BestPrefixLength && CheckDir(path::parent_path(MainFile))) {
if (IsSystem)
*IsSystem = false;
BestPrefixIsFramework = false;
}
StringRef Filename = File.drop_front(BestPrefixLength);
for (const DirectoryLookup &DL : search_dir_range()) {
if (!DL.isHeaderMap())
continue;
StringRef SpelledFilename =
DL.getHeaderMap()->reverseLookupFilename(Filename);
if (!SpelledFilename.empty()) {
Filename = SpelledFilename;
BestPrefixIsFramework = false;
break;
}
}
bool IsPrivateHeader;
SmallString<128> FrameworkName, IncludeSpelling;
if (BestPrefixIsFramework &&
isFrameworkStylePath(Filename, IsPrivateHeader, FrameworkName,
IncludeSpelling)) {
Filename = IncludeSpelling;
}
return path::convert_to_slash(Filename);
}