HeaderSearch.cpp 60 KB

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