HeaderSearch.cpp 63 KB

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