HeaderSearch.cpp 65 KB

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