HeaderSearch.cpp 64 KB

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