HeaderSearch.cpp 73 KB

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