HeaderSearch.cpp 67 KB

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