HeaderSearch.cpp 53 KB

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