blob: 3ac1df1740c817b784b73467b1ebc146c48e542c [file] [log] [blame]
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +00001//===- HeaderSearch.cpp - Resolve Header File Locations -------------------===//
Chris Lattner59a9ebd2006-10-18 05:34:33 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner59a9ebd2006-10-18 05:34:33 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the DirectoryLookup and HeaderSearch interfaces.
10//
11//===----------------------------------------------------------------------===//
12
Chris Lattner59a9ebd2006-10-18 05:34:33 +000013#include "clang/Lex/HeaderSearch.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000014#include "clang/Basic/Diagnostic.h"
Chris Lattneref6b1362007-10-07 08:58:51 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000017#include "clang/Basic/Module.h"
18#include "clang/Basic/SourceManager.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000019#include "clang/Lex/DirectoryLookup.h"
Richard Smith2aedca32015-07-01 02:29:35 +000020#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/HeaderMap.h"
22#include "clang/Lex/HeaderSearchOptions.h"
Will Wilson0fafd342013-12-27 19:46:16 +000023#include "clang/Lex/LexDiagnostic.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000024#include "clang/Lex/ModuleMap.h"
Richard Smith20e883e2015-04-29 23:20:19 +000025#include "clang/Lex/Preprocessor.h"
Ben Langmuirbeee15e2014-04-14 18:00:01 +000026#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/Hashing.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +000028#include "llvm/ADT/SmallString.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000029#include "llvm/ADT/SmallVector.h"
Volodymyr Sapsaie8752a92019-10-11 18:22:34 +000030#include "llvm/ADT/Statistic.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000031#include "llvm/ADT/StringRef.h"
32#include "llvm/Support/Allocator.h"
Ted Kremenekae63d102011-07-27 18:41:18 +000033#include "llvm/Support/Capacity.h"
Alexey Bataev4a0328c2019-08-13 19:32:36 +000034#include "llvm/Support/Errc.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000035#include "llvm/Support/ErrorHandling.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "llvm/Support/FileSystem.h"
37#include "llvm/Support/Path.h"
Jonas Devliegherefc514902018-10-10 13:27:25 +000038#include "llvm/Support/VirtualFileSystem.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000039#include <algorithm>
40#include <cassert>
41#include <cstddef>
Chris Lattnerc25d8a72009-03-02 22:20:04 +000042#include <cstdio>
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000043#include <cstring>
44#include <string>
45#include <system_error>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000046#include <utility>
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000047
Chris Lattner59a9ebd2006-10-18 05:34:33 +000048using namespace clang;
49
Volodymyr Sapsaie8752a92019-10-11 18:22:34 +000050#define DEBUG_TYPE "file-search"
51
52ALWAYS_ENABLED_STATISTIC(NumIncluded, "Number of attempted #includes.");
53ALWAYS_ENABLED_STATISTIC(
54 NumMultiIncludeFileOptzn,
55 "Number of #includes skipped due to the multi-include optimization.");
56ALWAYS_ENABLED_STATISTIC(NumFrameworkLookups, "Number of framework lookups.");
57ALWAYS_ENABLED_STATISTIC(NumSubFrameworkLookups,
58 "Number of subframework lookups.");
59
Douglas Gregor99734e72009-04-25 23:30:02 +000060const IdentifierInfo *
Richard Smith2aedca32015-07-01 02:29:35 +000061HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {
62 if (ControllingMacro) {
Chandler Carruth59666772016-11-04 06:32:57 +000063 if (ControllingMacro->isOutOfDate()) {
64 assert(External && "We must have an external source if we have a "
65 "controlling macro that is out of date.");
Richard Smith2aedca32015-07-01 02:29:35 +000066 External->updateOutOfDateIdentifier(
67 *const_cast<IdentifierInfo *>(ControllingMacro));
Chandler Carruth59666772016-11-04 06:32:57 +000068 }
Douglas Gregor99734e72009-04-25 23:30:02 +000069 return ControllingMacro;
Richard Smith2aedca32015-07-01 02:29:35 +000070 }
Douglas Gregor99734e72009-04-25 23:30:02 +000071
72 if (!ControllingMacroID || !External)
Craig Topperd2d442c2014-05-17 23:10:59 +000073 return nullptr;
Douglas Gregor99734e72009-04-25 23:30:02 +000074
75 ControllingMacro = External->GetIdentifier(ControllingMacroID);
76 return ControllingMacro;
77}
78
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000079ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() = default;
Douglas Gregor09b69892011-02-10 17:09:37 +000080
David Blaikie9c28cb32017-01-06 01:04:46 +000081HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +000082 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
Will Wilson0fafd342013-12-27 19:46:16 +000083 const LangOptions &LangOpts,
Douglas Gregor89929282012-01-30 06:01:29 +000084 const TargetInfo *Target)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000085 : HSOpts(std::move(HSOpts)), Diags(Diags),
86 FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000087 ModMap(SourceMgr, Diags, LangOpts, Target, *this) {}
Chris Lattner641a0be2006-10-20 06:23:14 +000088
Chris Lattner59a9ebd2006-10-18 05:34:33 +000089void HeaderSearch::PrintStats() {
Volodymyr Sapsaie8752a92019-10-11 18:22:34 +000090 llvm::errs() << "\n*** HeaderSearch Stats:\n"
91 << FileInfo.size() << " files tracked.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +000092 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
93 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
94 NumOnceOnlyFiles += FileInfo[i].isImport;
95 if (MaxNumIncludes < FileInfo[i].NumIncludes)
96 MaxNumIncludes = FileInfo[i].NumIncludes;
97 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
98 }
Volodymyr Sapsaie8752a92019-10-11 18:22:34 +000099 llvm::errs() << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n"
100 << " " << NumSingleIncludedFiles << " included exactly once.\n"
101 << " " << MaxNumIncludes << " max times a file is included.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000102
Volodymyr Sapsaie8752a92019-10-11 18:22:34 +0000103 llvm::errs() << " " << NumIncluded << " #include/#include_next/#import.\n"
104 << " " << NumMultiIncludeFileOptzn
105 << " #includes skipped due to the multi-include optimization.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000106
Volodymyr Sapsaie8752a92019-10-11 18:22:34 +0000107 llvm::errs() << NumFrameworkLookups << " framework lookups.\n"
108 << NumSubFrameworkLookups << " subframework lookups.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000109}
110
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000111/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000112/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner4ffe46c2007-12-17 18:34:53 +0000113const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000114 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerf62f7582007-12-17 07:52:39 +0000115 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000116 if (!HeaderMaps.empty()) {
117 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerf62f7582007-12-17 07:52:39 +0000118 // Pointer equality comparison of FileEntries works because they are
119 // already uniqued by inode.
Mike Stump11289f42009-09-09 15:08:12 +0000120 if (HeaderMaps[i].first == FE)
Fangrui Song48769772018-08-20 19:15:02 +0000121 return HeaderMaps[i].second.get();
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000122 }
Mike Stump11289f42009-09-09 15:08:12 +0000123
Fangrui Song48769772018-08-20 19:15:02 +0000124 if (std::unique_ptr<HeaderMap> HM = HeaderMap::Create(FE, FileMgr)) {
125 HeaderMaps.emplace_back(FE, std::move(HM));
126 return HeaderMaps.back().second.get();
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000127 }
Mike Stump11289f42009-09-09 15:08:12 +0000128
Craig Topperd2d442c2014-05-17 23:10:59 +0000129 return nullptr;
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000130}
131
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000132/// Get filenames for all registered header maps.
Bruno Cardoso Lopes181225b2016-12-11 04:27:28 +0000133void HeaderSearch::getHeaderMapFileNames(
134 SmallVectorImpl<std::string> &Names) const {
135 for (auto &HM : HeaderMaps)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100136 Names.push_back(std::string(HM.first->getName()));
Bruno Cardoso Lopes181225b2016-12-11 04:27:28 +0000137}
138
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000139std::string HeaderSearch::getCachedModuleFileName(Module *Module) {
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000140 const FileEntry *ModuleMap =
141 getModuleMap().getModuleMapFileForUniquing(Module);
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000142 return getCachedModuleFileName(Module->Name, ModuleMap->getName());
Douglas Gregor279a6c32012-01-29 17:08:11 +0000143}
144
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000145std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,
146 bool FileMapOnly) {
147 // First check the module name to pcm file map.
Benjamin Krameref83d462020-02-08 13:27:52 +0100148 auto i(HSOpts->PrebuiltModuleFiles.find(ModuleName));
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000149 if (i != HSOpts->PrebuiltModuleFiles.end())
150 return i->second;
151
152 if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000153 return {};
Manman Ren11f2a472016-08-18 17:42:15 +0000154
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000155 // Then go through each prebuilt module directory and try to find the pcm
156 // file.
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000157 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
158 SmallString<256> Result(Dir);
159 llvm::sys::fs::make_absolute(Result);
160 llvm::sys::path::append(Result, ModuleName + ".pcm");
161 if (getFileMgr().getFile(Result.str()))
Jonas Devlieghere509e21a2020-01-29 21:27:46 -0800162 return std::string(Result);
Manman Ren11f2a472016-08-18 17:42:15 +0000163 }
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000164 return {};
165}
Manman Ren11f2a472016-08-18 17:42:15 +0000166
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000167std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,
168 StringRef ModuleMapPath) {
Richard Smithd520a252015-07-21 18:07:47 +0000169 // If we don't have a module cache path or aren't supposed to use one, we
170 // can't do anything.
Richard Smith3938f0c2015-08-15 00:34:15 +0000171 if (getModuleCachePath().empty())
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000172 return {};
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000173
Richard Smith3938f0c2015-08-15 00:34:15 +0000174 SmallString<256> Result(getModuleCachePath());
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000175 llvm::sys::fs::make_absolute(Result);
176
177 if (HSOpts->DisableModuleHash) {
178 llvm::sys::path::append(Result, ModuleName + ".pcm");
179 } else {
180 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
Richard Smith54cc3c22014-12-11 20:50:24 +0000181 // ideally be globally unique to this particular module. Name collisions
182 // in the hash are safe (because any translation unit can only import one
183 // module with each name), but result in a loss of caching.
184 //
185 // To avoid false-negatives, we form as canonical a path as we can, and map
186 // to lower-case in case we're on a case-insensitive file system.
Benjamin Krameradcd0262020-01-28 20:23:46 +0100187 std::string Parent =
188 std::string(llvm::sys::path::parent_path(ModuleMapPath));
Richard Smith3f57cff2017-03-09 00:58:22 +0000189 if (Parent.empty())
190 Parent = ".";
Harlan Haskins8d323d12019-08-01 21:31:56 +0000191 auto Dir = FileMgr.getDirectory(Parent);
Richard Smith54cc3c22014-12-11 20:50:24 +0000192 if (!Dir)
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000193 return {};
Harlan Haskins8d323d12019-08-01 21:31:56 +0000194 auto DirName = FileMgr.getCanonicalName(*Dir);
Richard Smith54cc3c22014-12-11 20:50:24 +0000195 auto FileName = llvm::sys::path::filename(ModuleMapPath);
196
197 llvm::hash_code Hash =
Adrian Prantl793038d32016-01-12 21:01:56 +0000198 llvm::hash_combine(DirName.lower(), FileName.lower());
Richard Smith54cc3c22014-12-11 20:50:24 +0000199
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000200 SmallString<128> HashStr;
Richard Smith54cc3c22014-12-11 20:50:24 +0000201 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
Yaron Keren92e1b622015-03-18 10:17:07 +0000202 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000203 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000204 return Result.str().str();
205}
206
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000207Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch,
208 bool AllowExtraModuleMapSearch) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000209 // Look in the module map to determine if there is a module by this name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000210 Module *Module = ModMap.findModule(ModuleName);
Richard Smith47972af2015-06-16 00:08:24 +0000211 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
Douglas Gregor279a6c32012-01-29 17:08:11 +0000212 return Module;
Graydon Hoare4d867642016-12-21 00:24:39 +0000213
214 StringRef SearchName = ModuleName;
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000215 Module = lookupModule(ModuleName, SearchName, AllowExtraModuleMapSearch);
Graydon Hoare4d867642016-12-21 00:24:39 +0000216
217 // The facility for "private modules" -- adjacent, optional module maps named
218 // module.private.modulemap that are supposed to define private submodules --
Bruno Cardoso Lopes297299192017-12-22 02:53:30 +0000219 // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private.
220 //
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000221 // Foo.Private is now deprecated in favor of Foo_Private. Users of FooPrivate
Bruno Cardoso Lopes297299192017-12-22 02:53:30 +0000222 // should also rename to Foo_Private. Representing private as submodules
223 // could force building unwanted dependencies into the parent module and cause
224 // dependency cycles.
225 if (!Module && SearchName.consume_back("_Private"))
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000226 Module = lookupModule(ModuleName, SearchName, AllowExtraModuleMapSearch);
Graydon Hoare4d867642016-12-21 00:24:39 +0000227 if (!Module && SearchName.consume_back("Private"))
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000228 Module = lookupModule(ModuleName, SearchName, AllowExtraModuleMapSearch);
Graydon Hoare4d867642016-12-21 00:24:39 +0000229 return Module;
230}
231
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000232Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName,
233 bool AllowExtraModuleMapSearch) {
Graydon Hoare4d867642016-12-21 00:24:39 +0000234 Module *Module = nullptr;
235
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000236 // Look through the various header search paths to load any available module
Douglas Gregor279a6c32012-01-29 17:08:11 +0000237 // maps, searching for a module map that describes this module.
238 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
239 if (SearchDirs[Idx].isFramework()) {
Graydon Hoare4d867642016-12-21 00:24:39 +0000240 // Search for or infer a module map for a framework. Here we use
241 // SearchName rather than ModuleName, to permit finding private modules
242 // named FooPrivate in buggy frameworks named Foo.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000243 SmallString<128> FrameworkDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000244 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
Graydon Hoare4d867642016-12-21 00:24:39 +0000245 llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
Harlan Haskins8d323d12019-08-01 21:31:56 +0000246 if (auto FrameworkDir = FileMgr.getDirectory(FrameworkDirName)) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000247 bool IsSystem
248 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
Harlan Haskins8d323d12019-08-01 21:31:56 +0000249 Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000250 if (Module)
251 break;
252 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000253 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000254
Douglas Gregor279a6c32012-01-29 17:08:11 +0000255 // FIXME: Figure out how header maps and module maps will work together.
Fangrui Song6907ce22018-07-30 19:24:48 +0000256
Douglas Gregor279a6c32012-01-29 17:08:11 +0000257 // Only deal with normal search directories.
258 if (!SearchDirs[Idx].isNormalDir())
259 continue;
Douglas Gregor963c5532013-06-21 16:28:10 +0000260
261 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor279a6c32012-01-29 17:08:11 +0000262 // Search for a module map file in this directory.
Ben Langmuir984e1df2014-03-19 20:23:34 +0000263 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
264 /*IsFramework*/false) == LMM_NewlyLoaded) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000265 // We just loaded a module map file; check whether the module is
266 // available now.
267 Module = ModMap.findModule(ModuleName);
268 if (Module)
269 break;
270 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000271
Douglas Gregor279a6c32012-01-29 17:08:11 +0000272 // Search for a module map in a subdirectory with the same name as the
273 // module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000274 SmallString<128> NestedModuleMapDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000275 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
276 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Ben Langmuir984e1df2014-03-19 20:23:34 +0000277 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
278 /*IsFramework*/false) == LMM_NewlyLoaded){
Douglas Gregor279a6c32012-01-29 17:08:11 +0000279 // If we just loaded a module map file, look for the module again.
280 Module = ModMap.findModule(ModuleName);
281 if (Module)
282 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000283 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000284
285 // If we've already performed the exhaustive search for module maps in this
286 // search directory, don't do it again.
287 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
288 continue;
289
290 // Load all module maps in the immediate subdirectories of this search
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000291 // directory if ModuleName was from @import.
292 if (AllowExtraModuleMapSearch)
293 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor0339a642013-03-21 01:08:50 +0000294
295 // Look again for the module.
296 Module = ModMap.findModule(ModuleName);
297 if (Module)
298 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000299 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000300
Douglas Gregor279a6c32012-01-29 17:08:11 +0000301 return Module;
Douglas Gregor1e44e022011-09-12 20:41:59 +0000302}
303
Chris Lattnerf62f7582007-12-17 07:52:39 +0000304//===----------------------------------------------------------------------===//
305// File lookup within a DirectoryLookup scope
306//===----------------------------------------------------------------------===//
307
Chris Lattner8d720d02007-12-17 17:57:27 +0000308/// getName - Return the directory or filename corresponding to this lookup
309/// object.
Mehdi Amini99d1b292016-10-01 16:38:28 +0000310StringRef DirectoryLookup::getName() const {
Alex Lorenz0377ca62019-08-31 01:26:04 +0000311 // FIXME: Use the name from \c DirectoryEntryRef.
Chris Lattner8d720d02007-12-17 17:57:27 +0000312 if (isNormalDir())
313 return getDir()->getName();
314 if (isFramework())
315 return getFrameworkDir()->getName();
316 assert(isHeaderMap() && "Unknown DirectoryLookup");
317 return getHeaderMap()->getFileName();
318}
319
Alex Lorenz4dc55732019-08-22 18:15:50 +0000320Optional<FileEntryRef> HeaderSearch::getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000321 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
322 bool IsSystemHeaderDir, Module *RequestingModule,
323 ModuleMap::KnownHeader *SuggestedModule) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000324 // If we have a module map that might map this header, load it and
325 // check whether we'll have a suggestion for a module.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000326 auto File = getFileMgr().getFileRef(FileName, /*OpenFile=*/true);
Nico Weberbabdfde2019-08-08 17:58:32 +0000327 if (!File) {
328 // For rare, surprising errors (e.g. "out of file handles"), diag the EC
329 // message.
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51 +0000330 std::error_code EC = llvm::errorToErrorCode(File.takeError());
Alexey Bataev4a0328c2019-08-13 19:32:36 +0000331 if (EC != llvm::errc::no_such_file_or_directory &&
332 EC != llvm::errc::invalid_argument &&
333 EC != llvm::errc::is_a_directory && EC != llvm::errc::not_a_directory) {
Reid Kleckner1d63b022019-08-08 21:35:03 +0000334 Diags.Report(IncludeLoc, diag::err_cannot_open_file)
335 << FileName << EC.message();
Nico Weberbabdfde2019-08-08 17:58:32 +0000336 }
Alex Lorenz4dc55732019-08-22 18:15:50 +0000337 return None;
Nico Weberbabdfde2019-08-08 17:58:32 +0000338 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000339
Richard Smith3d5b48c2015-10-16 21:42:56 +0000340 // If there is a module that corresponds to this header, suggest it.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000341 if (!findUsableModuleForHeader(
342 &File->getFileEntry(), Dir ? Dir : File->getFileEntry().getDir(),
343 RequestingModule, SuggestedModule, IsSystemHeaderDir))
344 return None;
Richard Smith8c71eba2014-03-05 20:51:45 +0000345
Harlan Haskins8d323d12019-08-01 21:31:56 +0000346 return *File;
Richard Smith8c71eba2014-03-05 20:51:45 +0000347}
Chris Lattner8d720d02007-12-17 17:57:27 +0000348
Chris Lattnerf62f7582007-12-17 07:52:39 +0000349/// LookupFile - Lookup the specified file in this search path, returning it
350/// if it exists or returning null if not.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000351Optional<FileEntryRef> DirectoryLookup::LookupFile(
352 StringRef &Filename, HeaderSearch &HS, SourceLocation IncludeLoc,
353 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
354 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
355 bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound,
Volodymyr Sapsai2f843612019-09-11 20:39:04 +0000356 bool &IsInHeaderMap, SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000357 InUserSpecifiedSystemFramework = false;
Volodymyr Sapsai2f843612019-09-11 20:39:04 +0000358 IsInHeaderMap = false;
359 MappedName.clear();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000360
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000361 SmallString<1024> TmpDir;
Chris Lattner712e3872007-12-17 08:13:48 +0000362 if (isNormalDir()) {
363 // Concatenate the requested file onto the directory.
Eli Friedmanf7ca26a2011-07-08 20:17:28 +0000364 TmpDir = getDir()->getName();
365 llvm::sys::path::append(TmpDir, Filename);
Craig Topperd2d442c2014-05-17 23:10:59 +0000366 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000367 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000368 SearchPath->clear();
369 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
370 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000371 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000372 RelativePath->clear();
373 RelativePath->append(Filename.begin(), Filename.end());
374 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000375
Taewook Ohf42103c2016-06-13 20:40:21 +0000376 return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
Richard Smith3d5b48c2015-10-16 21:42:56 +0000377 isSystemHeaderDirectory(),
378 RequestingModule, SuggestedModule);
Chris Lattner712e3872007-12-17 08:13:48 +0000379 }
Mike Stump11289f42009-09-09 15:08:12 +0000380
Chris Lattner712e3872007-12-17 08:13:48 +0000381 if (isFramework())
Douglas Gregor97eec242011-09-15 22:00:41 +0000382 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000383 RequestingModule, SuggestedModule,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000384 InUserSpecifiedSystemFramework, IsFrameworkFound);
Mike Stump11289f42009-09-09 15:08:12 +0000385
Chris Lattner44bd21b2007-12-17 08:17:39 +0000386 assert(isHeaderMap() && "Unknown directory lookup");
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000387 const HeaderMap *HM = getHeaderMap();
388 SmallString<1024> Path;
389 StringRef Dest = HM->lookupFilename(Filename, Path);
390 if (Dest.empty())
Alex Lorenz4dc55732019-08-22 18:15:50 +0000391 return None;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000392
Volodymyr Sapsai2f843612019-09-11 20:39:04 +0000393 IsInHeaderMap = true;
394
Alex Lorenz4dc55732019-08-22 18:15:50 +0000395 auto FixupSearchPath = [&]() {
Craig Topperd2d442c2014-05-17 23:10:59 +0000396 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000397 StringRef SearchPathRef(getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000398 SearchPath->clear();
399 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
400 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000401 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000402 RelativePath->clear();
403 RelativePath->append(Filename.begin(), Filename.end());
404 }
Alex Lorenz4dc55732019-08-22 18:15:50 +0000405 };
406
407 // Check if the headermap maps the filename to a framework include
408 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
409 // framework include.
410 if (llvm::sys::path::is_relative(Dest)) {
Alex Lorenz4dc55732019-08-22 18:15:50 +0000411 MappedName.append(Dest.begin(), Dest.end());
412 Filename = StringRef(MappedName.begin(), MappedName.size());
Alex Lorenz4dc55732019-08-22 18:15:50 +0000413 Optional<FileEntryRef> Result = HM->LookupFile(Filename, HS.getFileMgr());
414 if (Result) {
415 FixupSearchPath();
416 return *Result;
417 }
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51 +0000418 } else if (auto Res = HS.getFileMgr().getOptionalFileRef(Dest)) {
Alex Lorenz4dc55732019-08-22 18:15:50 +0000419 FixupSearchPath();
420 return *Res;
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000421 }
Alex Lorenz4dc55732019-08-22 18:15:50 +0000422
423 return None;
Chris Lattnerf62f7582007-12-17 07:52:39 +0000424}
425
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000426/// Given a framework directory, find the top-most framework directory.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000427///
428/// \param FileMgr The file manager to use for directory lookups.
429/// \param DirName The name of the framework directory.
430/// \param SubmodulePath Will be populated with the submodule path from the
431/// returned top-level module to the originally named framework.
432static const DirectoryEntry *
433getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
434 SmallVectorImpl<std::string> &SubmodulePath) {
435 assert(llvm::sys::path::extension(DirName) == ".framework" &&
436 "Not a framework directory");
437
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000438 // Note: as an egregious but useful hack we use the real path here, because
439 // frameworks moving between top-level frameworks to embedded frameworks tend
440 // to be symlinked, and we base the logical structure of modules on the
441 // physical layout. In particular, we need to deal with crazy includes like
442 //
443 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
444 //
445 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
446 // which one should access with, e.g.,
447 //
448 // #include <Bar/Wibble.h>
449 //
450 // Similar issues occur when a top-level framework has moved into an
451 // embedded framework.
Harlan Haskins8d323d12019-08-01 21:31:56 +0000452 const DirectoryEntry *TopFrameworkDir = nullptr;
453 if (auto TopFrameworkDirOrErr = FileMgr.getDirectory(DirName))
454 TopFrameworkDir = *TopFrameworkDirOrErr;
455
456 if (TopFrameworkDir)
457 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000458 do {
459 // Get the parent directory name.
460 DirName = llvm::sys::path::parent_path(DirName);
461 if (DirName.empty())
462 break;
463
464 // Determine whether this directory exists.
Harlan Haskins8d323d12019-08-01 21:31:56 +0000465 auto Dir = FileMgr.getDirectory(DirName);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000466 if (!Dir)
467 break;
468
469 // If this is a framework directory, then we're a subframework of this
470 // framework.
471 if (llvm::sys::path::extension(DirName) == ".framework") {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100472 SubmodulePath.push_back(std::string(llvm::sys::path::stem(DirName)));
Harlan Haskins8d323d12019-08-01 21:31:56 +0000473 TopFrameworkDir = *Dir;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000474 }
475 } while (true);
476
477 return TopFrameworkDir;
478}
Chris Lattnerf62f7582007-12-17 07:52:39 +0000479
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +0000480static bool needModuleLookup(Module *RequestingModule,
481 bool HasSuggestedModule) {
482 return HasSuggestedModule ||
483 (RequestingModule && RequestingModule->NoUndeclaredIncludes);
484}
485
Chris Lattner712e3872007-12-17 08:13:48 +0000486/// DoFrameworkLookup - Do a lookup of the specified file in the current
487/// DirectoryLookup, which is a framework directory.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000488Optional<FileEntryRef> DirectoryLookup::DoFrameworkLookup(
Richard Smith3d5b48c2015-10-16 21:42:56 +0000489 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
490 SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000491 ModuleMap::KnownHeader *SuggestedModule,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000492 bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound) const {
Chris Lattner712e3872007-12-17 08:13:48 +0000493 FileManager &FileMgr = HS.getFileMgr();
Mike Stump11289f42009-09-09 15:08:12 +0000494
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000495 // Framework names must have a '/' in the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000496 size_t SlashPos = Filename.find('/');
Alex Lorenz4dc55732019-08-22 18:15:50 +0000497 if (SlashPos == StringRef::npos)
498 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000499
Chris Lattner712e3872007-12-17 08:13:48 +0000500 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar17138612012-04-05 17:09:40 +0000501 // HeaderSearch. Possible answers are yes/no and unknown.
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000502 FrameworkCacheEntry &CacheEntry =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000503 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000504
Chris Lattner712e3872007-12-17 08:13:48 +0000505 // If it is known and in some other directory, fail.
Daniel Dunbar17138612012-04-05 17:09:40 +0000506 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Alex Lorenz4dc55732019-08-22 18:15:50 +0000507 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000508
Chris Lattner712e3872007-12-17 08:13:48 +0000509 // Otherwise, construct the path to this framework dir.
Mike Stump11289f42009-09-09 15:08:12 +0000510
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000511 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000512 SmallString<1024> FrameworkName;
Alex Lorenz0377ca62019-08-31 01:26:04 +0000513 FrameworkName += getFrameworkDirRef()->getName();
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000514 if (FrameworkName.empty() || FrameworkName.back() != '/')
515 FrameworkName.push_back('/');
Mike Stump11289f42009-09-09 15:08:12 +0000516
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000517 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor56c64012011-11-17 01:41:17 +0000518 StringRef ModuleName(Filename.begin(), SlashPos);
519 FrameworkName += ModuleName;
Mike Stump11289f42009-09-09 15:08:12 +0000520
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000521 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
522 FrameworkName += ".framework/";
Mike Stump11289f42009-09-09 15:08:12 +0000523
Daniel Dunbar17138612012-04-05 17:09:40 +0000524 // If the cache entry was unresolved, populate it now.
Craig Topperd2d442c2014-05-17 23:10:59 +0000525 if (!CacheEntry.Directory) {
Volodymyr Sapsaie8752a92019-10-11 18:22:34 +0000526 ++NumFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000527
Chris Lattner5ed76da2006-10-22 07:24:13 +0000528 // If the framework dir doesn't exist, we fail.
Harlan Haskins8d323d12019-08-01 21:31:56 +0000529 auto Dir = FileMgr.getDirectory(FrameworkName);
Alex Lorenz4dc55732019-08-22 18:15:50 +0000530 if (!Dir)
531 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000532
Chris Lattner5ed76da2006-10-22 07:24:13 +0000533 // Otherwise, if it does, remember that this is the right direntry for this
534 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000535 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000536
537 // If this is a user search directory, check if the framework has been
538 // user-specified as a system framework.
539 if (getDirCharacteristic() == SrcMgr::C_User) {
540 SmallString<1024> SystemFrameworkMarker(FrameworkName);
541 SystemFrameworkMarker += ".system_framework";
Yaron Keren92e1b622015-03-18 10:17:07 +0000542 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000543 CacheEntry.IsUserSpecifiedSystemFramework = true;
544 }
545 }
Chris Lattner5ed76da2006-10-22 07:24:13 +0000546 }
Mike Stump11289f42009-09-09 15:08:12 +0000547
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000548 // Set out flags.
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000549 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000550 IsFrameworkFound = CacheEntry.Directory;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000551
Craig Topperd2d442c2014-05-17 23:10:59 +0000552 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000553 RelativePath->clear();
554 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
555 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000556
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000557 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000558 unsigned OrigSize = FrameworkName.size();
Mike Stump11289f42009-09-09 15:08:12 +0000559
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000560 FrameworkName += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000561
Craig Topperd2d442c2014-05-17 23:10:59 +0000562 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000563 SearchPath->clear();
564 // Without trailing '/'.
565 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
566 }
567
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000568 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Harlan Haskins8d323d12019-08-01 21:31:56 +0000569
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51 +0000570 auto File =
571 FileMgr.getOptionalFileRef(FrameworkName, /*OpenFile=*/!SuggestedModule);
Alex Lorenz4dc55732019-08-22 18:15:50 +0000572 if (!File) {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000573 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
574 const char *Private = "Private";
575 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
576 Private+strlen(Private));
Craig Topperd2d442c2014-05-17 23:10:59 +0000577 if (SearchPath)
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000578 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
579 Private+strlen(Private));
580
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51 +0000581 File = FileMgr.getOptionalFileRef(FrameworkName,
582 /*OpenFile=*/!SuggestedModule);
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000583 }
Mike Stump11289f42009-09-09 15:08:12 +0000584
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000585 // If we found the header and are allowed to suggest a module, do so now.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000586 if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000587 // Find the framework in which this header occurs.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000588 StringRef FrameworkPath = File->getFileEntry().getDir()->getName();
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000589 bool FoundFramework = false;
590 do {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000591 // Determine whether this directory exists.
Harlan Haskins8d323d12019-08-01 21:31:56 +0000592 auto Dir = FileMgr.getDirectory(FrameworkPath);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000593 if (!Dir)
594 break;
595
596 // If this is a framework directory, then we're a subframework of this
597 // framework.
598 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
599 FoundFramework = true;
600 break;
601 }
Ben Langmuiref914b82014-05-15 16:20:33 +0000602
603 // Get the parent directory name.
604 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
605 if (FrameworkPath.empty())
606 break;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000607 } while (true);
608
Richard Smith3d5b48c2015-10-16 21:42:56 +0000609 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000610 if (FoundFramework) {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000611 if (!HS.findUsableModuleForFrameworkHeader(
Alex Lorenz4dc55732019-08-22 18:15:50 +0000612 &File->getFileEntry(), FrameworkPath, RequestingModule,
613 SuggestedModule, IsSystem))
614 return None;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000615 } else {
Alex Lorenz4dc55732019-08-22 18:15:50 +0000616 if (!HS.findUsableModuleForHeader(&File->getFileEntry(), getDir(),
617 RequestingModule, SuggestedModule,
618 IsSystem))
619 return None;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000620 }
621 }
Alex Lorenz4dc55732019-08-22 18:15:50 +0000622 if (File)
623 return *File;
624 return None;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000625}
626
Douglas Gregor89929282012-01-30 06:01:29 +0000627void HeaderSearch::setTarget(const TargetInfo &Target) {
628 ModMap.setTarget(Target);
629}
630
Chris Lattner712e3872007-12-17 08:13:48 +0000631//===----------------------------------------------------------------------===//
632// Header File Location.
633//===----------------------------------------------------------------------===//
634
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000635/// Return true with a diagnostic if the file that MSVC would have found
Reid Klecknera97d4c02014-02-18 23:49:24 +0000636/// fails to match the one that Clang would have found with MSVC header search
637/// disabled.
638static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
639 const FileEntry *MSFE, const FileEntry *FE,
640 SourceLocation IncludeLoc) {
641 if (MSFE && FE != MSFE) {
642 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
643 return true;
644 }
645 return false;
646}
Chris Lattner712e3872007-12-17 08:13:48 +0000647
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000648static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
649 assert(!Str.empty());
650 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
651 std::copy(Str.begin(), Str.end(), CopyStr);
652 CopyStr[Str.size()] = '\0';
653 return CopyStr;
654}
655
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000656static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader,
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000657 SmallVectorImpl<char> &FrameworkName) {
658 using namespace llvm::sys;
659 path::const_iterator I = path::begin(Path);
660 path::const_iterator E = path::end(Path);
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000661 IsPrivateHeader = false;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000662
663 // Detect different types of framework style paths:
664 //
665 // ...Foo.framework/{Headers,PrivateHeaders}
666 // ...Foo.framework/Versions/{A,Current}/{Headers,PrivateHeaders}
667 // ...Foo.framework/Frameworks/Nested.framework/{Headers,PrivateHeaders}
668 // ...<other variations with 'Versions' like in the above path>
669 //
670 // and some other variations among these lines.
671 int FoundComp = 0;
672 while (I != E) {
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000673 if (*I == "Headers")
674 ++FoundComp;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000675 if (I->endswith(".framework")) {
676 FrameworkName.append(I->begin(), I->end());
677 ++FoundComp;
678 }
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000679 if (*I == "PrivateHeaders") {
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000680 ++FoundComp;
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000681 IsPrivateHeader = true;
682 }
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000683 ++I;
684 }
685
Erik Pilkingtonabacc252018-09-20 19:00:03 +0000686 return !FrameworkName.empty() && FoundComp >= 2;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000687}
688
689static void
690diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc,
691 StringRef Includer, StringRef IncludeFilename,
692 const FileEntry *IncludeFE, bool isAngled = false,
693 bool FoundByHeaderMap = false) {
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000694 bool IsIncluderPrivateHeader = false;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000695 SmallString<128> FromFramework, ToFramework;
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000696 if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework))
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000697 return;
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000698 bool IsIncludeePrivateHeader = false;
699 bool IsIncludeeInFramework = isFrameworkStylePath(
700 IncludeFE->getName(), IsIncludeePrivateHeader, ToFramework);
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000701
702 if (!isAngled && !FoundByHeaderMap) {
703 SmallString<128> NewInclude("<");
704 if (IsIncludeeInFramework) {
705 NewInclude += StringRef(ToFramework).drop_back(10); // drop .framework
706 NewInclude += "/";
707 }
708 NewInclude += IncludeFilename;
709 NewInclude += ">";
710 Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header)
711 << IncludeFilename
712 << FixItHint::CreateReplacement(IncludeLoc, NewInclude);
713 }
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000714
715 // Headers in Foo.framework/Headers should not include headers
716 // from Foo.framework/PrivateHeaders, since this violates public/private
717 // API boundaries and can cause modular dependency cycles.
718 if (!IsIncluderPrivateHeader && IsIncludeeInFramework &&
719 IsIncludeePrivateHeader && FromFramework == ToFramework)
720 Diags.Report(IncludeLoc, diag::warn_framework_include_private_from_public)
721 << IncludeFilename;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000722}
723
James Dennettc07ab2c2012-06-20 00:56:32 +0000724/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000725/// return null on failure. isAngled indicates whether the file reference is
Will Wilson0fafd342013-12-27 19:46:16 +0000726/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
727/// non-empty, indicates where the \#including file(s) are, in case a relative
728/// search is needed. Microsoft mode will pass all \#including files.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000729Optional<FileEntryRef> HeaderSearch::LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000730 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
731 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000732 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
733 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000734 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000735 bool *IsMapped, bool *IsFrameworkFound, bool SkipCache,
736 bool BuildSystemModule) {
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000737 if (IsMapped)
738 *IsMapped = false;
739
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000740 if (IsFrameworkFound)
741 *IsFrameworkFound = false;
742
Douglas Gregor97eec242011-09-15 22:00:41 +0000743 if (SuggestedModule)
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000744 *SuggestedModule = ModuleMap::KnownHeader();
Fangrui Song6907ce22018-07-30 19:24:48 +0000745
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000746 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000747 if (llvm::sys::path::is_absolute(Filename)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000748 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000749
750 // If this was an #include_next "/absolute/file", fail.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000751 if (FromDir)
752 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000753
Craig Topperd2d442c2014-05-17 23:10:59 +0000754 if (SearchPath)
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000755 SearchPath->clear();
Craig Topperd2d442c2014-05-17 23:10:59 +0000756 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000757 RelativePath->clear();
758 RelativePath->append(Filename.begin(), Filename.end());
759 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000760 // Otherwise, just return the file.
Taewook Ohf42103c2016-06-13 20:40:21 +0000761 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000762 /*IsSystemHeaderDir*/false,
763 RequestingModule, SuggestedModule);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000764 }
Mike Stump11289f42009-09-09 15:08:12 +0000765
Reid Klecknera97d4c02014-02-18 23:49:24 +0000766 // This is the header that MSVC's header search would have found.
Richard Smith8c71eba2014-03-05 20:51:45 +0000767 ModuleMap::KnownHeader MSSuggestedModule;
Alex Lorenz4dc55732019-08-22 18:15:50 +0000768 const FileEntry *MSFE_FE = nullptr;
769 StringRef MSFE_Name;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000770
Douglas Gregor9f93e382011-07-28 04:45:53 +0000771 // Unless disabled, check to see if the file is in the #includer's
Will Wilson0fafd342013-12-27 19:46:16 +0000772 // directory. This cannot be based on CurDir, because each includer could be
773 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
774 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerf62f7582007-12-17 07:52:39 +0000775 // This search is not done for <> headers.
Will Wilson0fafd342013-12-27 19:46:16 +0000776 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
NAKAMURA Takumi9cb62642013-12-10 02:36:28 +0000777 SmallString<1024> TmpDir;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000778 bool First = true;
779 for (const auto &IncluderAndDir : Includers) {
780 const FileEntry *Includer = IncluderAndDir.first;
781
Will Wilson0fafd342013-12-27 19:46:16 +0000782 // Concatenate the requested file onto the directory.
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000783 // FIXME: Portability. Filename concatenation should be in sys::Path.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000784 TmpDir = IncluderAndDir.second->getName();
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000785 TmpDir.push_back('/');
786 TmpDir.append(Filename.begin(), Filename.end());
Richard Smith8c71eba2014-03-05 20:51:45 +0000787
Richard Smith6f548ec2014-03-06 18:08:08 +0000788 // FIXME: We don't cache the result of getFileInfo across the call to
789 // getFileAndSuggestModule, because it's a reference to an element of
790 // a container that could be reallocated across this call.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000791 //
Manman Rene4a5d372016-05-17 02:15:12 +0000792 // If we have no includer, that means we're processing a #include
Richard Smith3c1a41a2014-12-02 00:08:08 +0000793 // from a module build. We should treat this as a system header if we're
794 // building a [system] module.
Richard Smith6f548ec2014-03-06 18:08:08 +0000795 bool IncluderIsSystemHeader =
Manman Rene39c8142016-05-17 18:04:38 +0000796 Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
797 BuildSystemModule;
Alex Lorenz4dc55732019-08-22 18:15:50 +0000798 if (Optional<FileEntryRef> FE = getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000799 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000800 RequestingModule, SuggestedModule)) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000801 if (!Includer) {
802 assert(First && "only first includer can have no file");
803 return FE;
804 }
805
Will Wilson0fafd342013-12-27 19:46:16 +0000806 // Leave CurDir unset.
807 // This file is a system header or C++ unfriendly if the old file is.
808 //
809 // Note that we only use one of FromHFI/ToHFI at once, due to potential
810 // reallocation of the underlying vector potentially making the first
811 // reference binding dangling.
Richard Smith6f548ec2014-03-06 18:08:08 +0000812 HeaderFileInfo &FromHFI = getFileInfo(Includer);
Will Wilson0fafd342013-12-27 19:46:16 +0000813 unsigned DirInfo = FromHFI.DirInfo;
814 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
815 StringRef Framework = FromHFI.Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000816
Alex Lorenz4dc55732019-08-22 18:15:50 +0000817 HeaderFileInfo &ToHFI = getFileInfo(&FE->getFileEntry());
Will Wilson0fafd342013-12-27 19:46:16 +0000818 ToHFI.DirInfo = DirInfo;
819 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
820 ToHFI.Framework = Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000821
Craig Topperd2d442c2014-05-17 23:10:59 +0000822 if (SearchPath) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000823 StringRef SearchPathRef(IncluderAndDir.second->getName());
Will Wilson0fafd342013-12-27 19:46:16 +0000824 SearchPath->clear();
825 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
826 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000827 if (RelativePath) {
Will Wilson0fafd342013-12-27 19:46:16 +0000828 RelativePath->clear();
829 RelativePath->append(Filename.begin(), Filename.end());
830 }
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000831 if (First) {
832 diagnoseFrameworkInclude(Diags, IncludeLoc,
833 IncluderAndDir.second->getName(), Filename,
Alex Lorenz4dc55732019-08-22 18:15:50 +0000834 &FE->getFileEntry());
Reid Klecknera97d4c02014-02-18 23:49:24 +0000835 return FE;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000836 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000837
838 // Otherwise, we found the path via MSVC header search rules. If
839 // -Wmsvc-include is enabled, we have to keep searching to see if we
840 // would've found this header in -I or -isystem directories.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000841 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
Reid Klecknera97d4c02014-02-18 23:49:24 +0000842 return FE;
843 } else {
Alex Lorenz4dc55732019-08-22 18:15:50 +0000844 MSFE_FE = &FE->getFileEntry();
845 MSFE_Name = FE->getName();
Richard Smith8c71eba2014-03-05 20:51:45 +0000846 if (SuggestedModule) {
847 MSSuggestedModule = *SuggestedModule;
848 *SuggestedModule = ModuleMap::KnownHeader();
849 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000850 break;
851 }
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000852 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000853 First = false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000854 }
855 }
Mike Stump11289f42009-09-09 15:08:12 +0000856
Alex Lorenz4dc55732019-08-22 18:15:50 +0000857 Optional<FileEntryRef> MSFE(MSFE_FE ? FileEntryRef(MSFE_Name, *MSFE_FE)
858 : Optional<FileEntryRef>());
859
Craig Topperd2d442c2014-05-17 23:10:59 +0000860 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000861
862 // If this is a system #include, ignore the user #include locs.
Nico Weber3b1d1212011-05-24 04:31:14 +0000863 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000864
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000865 // If this is a #include_next request, start searching after the directory the
866 // file was found in.
867 if (FromDir)
868 i = FromDir-&SearchDirs[0];
Mike Stump11289f42009-09-09 15:08:12 +0000869
Chris Lattnerd4275422007-07-22 07:28:00 +0000870 // Cache all of the lookups performed by this method. Many headers are
871 // multiply included, and the "pragma once" optimization prevents them from
872 // being relex/pp'd, but they would still have to search through a
873 // (potentially huge) series of SearchDirs to find it.
David Blaikie13156b62014-11-19 03:06:06 +0000874 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
Chris Lattnerd4275422007-07-22 07:28:00 +0000875
876 // If the entry has been previously looked up, the first value will be
877 // non-zero. If the value is equal to i (the start point of our search), then
878 // this is a matching hit.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000879 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattnerd4275422007-07-22 07:28:00 +0000880 // Skip querying potentially lots of directories for this lookup.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000881 i = CacheLookup.HitIdx;
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000882 if (CacheLookup.MappedName) {
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000883 Filename = CacheLookup.MappedName;
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000884 if (IsMapped)
885 *IsMapped = true;
886 }
Chris Lattnerd4275422007-07-22 07:28:00 +0000887 } else {
888 // Otherwise, this is the first query, or the previous query didn't match
889 // our search start. We will fill in our found location below, so prime the
890 // start point value.
Argyrios Kyrtzidis7bd78a92014-03-29 03:22:54 +0000891 CacheLookup.reset(/*StartIdx=*/i+1);
Chris Lattnerd4275422007-07-22 07:28:00 +0000892 }
Mike Stump11289f42009-09-09 15:08:12 +0000893
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000894 SmallString<64> MappedName;
895
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000896 // Check each directory in sequence to see if it contains this file.
897 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000898 bool InUserSpecifiedSystemFramework = false;
Volodymyr Sapsai2f843612019-09-11 20:39:04 +0000899 bool IsInHeaderMap = false;
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000900 bool IsFrameworkFoundInDir = false;
Alex Lorenz4dc55732019-08-22 18:15:50 +0000901 Optional<FileEntryRef> File = SearchDirs[i].LookupFile(
Taewook Ohf42103c2016-06-13 20:40:21 +0000902 Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000903 SuggestedModule, InUserSpecifiedSystemFramework, IsFrameworkFoundInDir,
Volodymyr Sapsai2f843612019-09-11 20:39:04 +0000904 IsInHeaderMap, MappedName);
905 if (!MappedName.empty()) {
906 assert(IsInHeaderMap && "MappedName should come from a header map");
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000907 CacheLookup.MappedName =
Volodymyr Sapsai2f843612019-09-11 20:39:04 +0000908 copyString(MappedName, LookupFileCache.getAllocator());
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000909 }
Volodymyr Sapsai2f843612019-09-11 20:39:04 +0000910 if (IsMapped)
911 // A filename is mapped when a header map remapped it to a relative path
912 // used in subsequent header search or to an absolute path pointing to an
913 // existing file.
914 *IsMapped |= (!MappedName.empty() || (IsInHeaderMap && File));
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000915 if (IsFrameworkFound)
Volodymyr Sapsaie32ff092019-05-27 19:15:30 +0000916 // Because we keep a filename remapped for subsequent search directory
917 // lookups, ignore IsFrameworkFoundInDir after the first remapping and not
918 // just for remapping in a current search directory.
919 *IsFrameworkFound |= (IsFrameworkFoundInDir && !CacheLookup.MappedName);
Alex Lorenz4dc55732019-08-22 18:15:50 +0000920 if (!File)
921 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000922
Chris Lattner712e3872007-12-17 08:13:48 +0000923 CurDir = &SearchDirs[i];
Mike Stump11289f42009-09-09 15:08:12 +0000924
Chris Lattner712e3872007-12-17 08:13:48 +0000925 // This file is a system header or C++ unfriendly if the dir is.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000926 HeaderFileInfo &HFI = getFileInfo(&File->getFileEntry());
Douglas Gregor9f93e382011-07-28 04:45:53 +0000927 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000928
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000929 // If the directory characteristic is User but this framework was
930 // user-specified to be treated as a system framework, promote the
931 // characteristic.
932 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
933 HFI.DirInfo = SrcMgr::C_System;
934
Richard Smith8acadcb2012-06-13 20:27:03 +0000935 // If the filename matches a known system header prefix, override
936 // whether the file is a system header.
Richard Trieu871f5f32012-06-13 20:52:36 +0000937 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
938 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
939 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smith8acadcb2012-06-13 20:27:03 +0000940 : SrcMgr::C_User;
941 break;
942 }
943 }
944
Douglas Gregor9f93e382011-07-28 04:45:53 +0000945 // If this file is found in a header map and uses the framework style of
946 // includes, then this header is part of a framework we're building.
947 if (CurDir->isIndexHeaderMap()) {
948 size_t SlashPos = Filename.find('/');
949 if (SlashPos != StringRef::npos) {
950 HFI.IndexHeaderMapHeader = 1;
Fangrui Song6907ce22018-07-30 19:24:48 +0000951 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
Douglas Gregor9f93e382011-07-28 04:45:53 +0000952 SlashPos));
953 }
954 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000955
Alex Lorenz4dc55732019-08-22 18:15:50 +0000956 if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
957 &File->getFileEntry(), IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000958 if (SuggestedModule)
959 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000960 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000961 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000962
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000963 bool FoundByHeaderMap = !IsMapped ? false : *IsMapped;
964 if (!Includers.empty())
Alex Lorenz4dc55732019-08-22 18:15:50 +0000965 diagnoseFrameworkInclude(
966 Diags, IncludeLoc, Includers.front().second->getName(), Filename,
967 &File->getFileEntry(), isAngled, FoundByHeaderMap);
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000968
Chris Lattner712e3872007-12-17 08:13:48 +0000969 // Remember this location for the next lookup we do.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000970 CacheLookup.HitIdx = i;
Alex Lorenz4dc55732019-08-22 18:15:50 +0000971 return File;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000972 }
Mike Stump11289f42009-09-09 15:08:12 +0000973
Douglas Gregord8575e12011-07-30 06:28:34 +0000974 // If we are including a file with a quoted include "foo.h" from inside
975 // a header in a framework that is currently being built, and we couldn't
976 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
977 // "Foo" is the name of the framework in which the including header was found.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000978 if (!Includers.empty() && Includers.front().first && !isAngled &&
Will Wilson0fafd342013-12-27 19:46:16 +0000979 Filename.find('/') == StringRef::npos) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000980 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
Douglas Gregord8575e12011-07-30 06:28:34 +0000981 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000982 SmallString<128> ScratchFilename;
Douglas Gregord8575e12011-07-30 06:28:34 +0000983 ScratchFilename += IncludingHFI.Framework;
984 ScratchFilename += '/';
985 ScratchFilename += Filename;
Will Wilson0fafd342013-12-27 19:46:16 +0000986
Alex Lorenz4dc55732019-08-22 18:15:50 +0000987 Optional<FileEntryRef> File = LookupFile(
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000988 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
989 Includers.front(), SearchPath, RelativePath, RequestingModule,
990 SuggestedModule, IsMapped, /*IsFrameworkFound=*/nullptr);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000991
Alex Lorenz4dc55732019-08-22 18:15:50 +0000992 if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
993 File ? &File->getFileEntry() : nullptr,
994 IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000995 if (SuggestedModule)
996 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000997 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000998 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000999
David Blaikie3c8c46e2014-11-19 05:48:40 +00001000 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
David Blaikie13156b62014-11-19 03:06:06 +00001001 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
Richard Smith8c71eba2014-03-05 20:51:45 +00001002 // FIXME: SuggestedModule.
Alex Lorenz4dc55732019-08-22 18:15:50 +00001003 return File;
Douglas Gregord8575e12011-07-30 06:28:34 +00001004 }
1005 }
1006
Alex Lorenz4dc55732019-08-22 18:15:50 +00001007 if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
1008 nullptr, IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +00001009 if (SuggestedModule)
1010 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +00001011 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +00001012 }
Reid Klecknera97d4c02014-02-18 23:49:24 +00001013
Chris Lattnerd4275422007-07-22 07:28:00 +00001014 // Otherwise, didn't find it. Remember we didn't find this.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +00001015 CacheLookup.HitIdx = SearchDirs.size();
Alex Lorenz4dc55732019-08-22 18:15:50 +00001016 return None;
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001017}
1018
Chris Lattner63dd32b2006-10-20 04:42:40 +00001019/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennettc07ab2c2012-06-20 00:56:32 +00001020/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Chris Lattner63dd32b2006-10-20 04:42:40 +00001021/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
1022/// is a subframework within Carbon.framework. If so, return the FileEntry
1023/// for the designated file, otherwise return null.
Alex Lorenz4dc55732019-08-22 18:15:50 +00001024Optional<FileEntryRef> HeaderSearch::LookupSubframeworkHeader(
1025 StringRef Filename, const FileEntry *ContextFileEnt,
1026 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
1027 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner12261882008-02-01 05:34:02 +00001028 assert(ContextFileEnt && "No context file?");
Mike Stump11289f42009-09-09 15:08:12 +00001029
Chris Lattner63dd32b2006-10-20 04:42:40 +00001030 // Framework names must have a '/' in the filename. Find it.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +00001031 // FIXME: Should we permit '\' on Windows?
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001032 size_t SlashPos = Filename.find('/');
Alex Lorenz4dc55732019-08-22 18:15:50 +00001033 if (SlashPos == StringRef::npos)
1034 return None;
Mike Stump11289f42009-09-09 15:08:12 +00001035
Chris Lattner63dd32b2006-10-20 04:42:40 +00001036 // Look up the base framework name of the ContextFileEnt.
Mehdi Amini004b9c72016-10-10 22:52:47 +00001037 StringRef ContextName = ContextFileEnt->getName();
Mike Stump11289f42009-09-09 15:08:12 +00001038
Chris Lattner63dd32b2006-10-20 04:42:40 +00001039 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +00001040 const unsigned DotFrameworkLen = 10;
Mehdi Amini004b9c72016-10-10 22:52:47 +00001041 auto FrameworkPos = ContextName.find(".framework");
1042 if (FrameworkPos == StringRef::npos ||
1043 (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
1044 ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
Alex Lorenz4dc55732019-08-22 18:15:50 +00001045 return None;
Mike Stump11289f42009-09-09 15:08:12 +00001046
Mehdi Amini004b9c72016-10-10 22:52:47 +00001047 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
1048 FrameworkPos +
1049 DotFrameworkLen + 1);
Chris Lattner5ed76da2006-10-22 07:24:13 +00001050
Chris Lattner63dd32b2006-10-20 04:42:40 +00001051 // Append Frameworks/HIToolbox.framework/
1052 FrameworkName += "Frameworks/";
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001053 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Chris Lattner63dd32b2006-10-20 04:42:40 +00001054 FrameworkName += ".framework/";
Chris Lattner577377e2006-10-20 04:55:45 +00001055
David Blaikie13156b62014-11-19 03:06:06 +00001056 auto &CacheLookup =
1057 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
1058 FrameworkCacheEntry())).first;
Mike Stump11289f42009-09-09 15:08:12 +00001059
Chris Lattner5ed76da2006-10-22 07:24:13 +00001060 // Some other location?
David Blaikie13156b62014-11-19 03:06:06 +00001061 if (CacheLookup.second.Directory &&
1062 CacheLookup.first().size() == FrameworkName.size() &&
1063 memcmp(CacheLookup.first().data(), &FrameworkName[0],
1064 CacheLookup.first().size()) != 0)
Alex Lorenz4dc55732019-08-22 18:15:50 +00001065 return None;
Mike Stump11289f42009-09-09 15:08:12 +00001066
Chris Lattner5ed76da2006-10-22 07:24:13 +00001067 // Cache subframework.
David Blaikie13156b62014-11-19 03:06:06 +00001068 if (!CacheLookup.second.Directory) {
Chris Lattner5ed76da2006-10-22 07:24:13 +00001069 ++NumSubFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +00001070
Chris Lattner5ed76da2006-10-22 07:24:13 +00001071 // If the framework dir doesn't exist, we fail.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001072 auto Dir = FileMgr.getDirectory(FrameworkName);
Alex Lorenz4dc55732019-08-22 18:15:50 +00001073 if (!Dir)
1074 return None;
Mike Stump11289f42009-09-09 15:08:12 +00001075
Chris Lattner5ed76da2006-10-22 07:24:13 +00001076 // Otherwise, if it does, remember that this is the right direntry for this
1077 // framework.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001078 CacheLookup.second.Directory = *Dir;
Chris Lattner5ed76da2006-10-22 07:24:13 +00001079 }
Mike Stump11289f42009-09-09 15:08:12 +00001080
Chris Lattner577377e2006-10-20 04:55:45 +00001081
Craig Topperd2d442c2014-05-17 23:10:59 +00001082 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001083 RelativePath->clear();
1084 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
1085 }
1086
Chris Lattner63dd32b2006-10-20 04:42:40 +00001087 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001088 SmallString<1024> HeadersFilename(FrameworkName);
Chris Lattner43fd42e2006-10-30 03:40:58 +00001089 HeadersFilename += "Headers/";
Craig Topperd2d442c2014-05-17 23:10:59 +00001090 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001091 SearchPath->clear();
1092 // Without trailing '/'.
1093 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1094 }
1095
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001096 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51 +00001097 auto File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
Alex Lorenz4dc55732019-08-22 18:15:50 +00001098 if (!File) {
Chris Lattner63dd32b2006-10-20 04:42:40 +00001099 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +00001100 HeadersFilename = FrameworkName;
1101 HeadersFilename += "PrivateHeaders/";
Craig Topperd2d442c2014-05-17 23:10:59 +00001102 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001103 SearchPath->clear();
1104 // Without trailing '/'.
1105 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1106 }
1107
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001108 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51 +00001109 File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
Alex Lorenz4dc55732019-08-22 18:15:50 +00001110
1111 if (!File)
1112 return None;
Chris Lattner63dd32b2006-10-20 04:42:40 +00001113 }
Mike Stump11289f42009-09-09 15:08:12 +00001114
Chris Lattner577377e2006-10-20 04:55:45 +00001115 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenek72be0682008-02-24 03:55:14 +00001116 //
Chris Lattnerf5c619f2008-02-25 21:38:21 +00001117 // Note that the temporary 'DirInfo' is required here, as either call to
1118 // getFileInfo could resize the vector and we don't want to rely on order
1119 // of evaluation.
1120 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
Alex Lorenz4dc55732019-08-22 18:15:50 +00001121 getFileInfo(&File->getFileEntry()).DirInfo = DirInfo;
Douglas Gregorf5f94522013-02-08 00:10:48 +00001122
Richard Smith3d5b48c2015-10-16 21:42:56 +00001123 FrameworkName.pop_back(); // remove the trailing '/'
Alex Lorenz4dc55732019-08-22 18:15:50 +00001124 if (!findUsableModuleForFrameworkHeader(&File->getFileEntry(), FrameworkName,
1125 RequestingModule, SuggestedModule,
1126 /*IsSystem*/ false))
1127 return None;
Douglas Gregorf5f94522013-02-08 00:10:48 +00001128
Alex Lorenz4dc55732019-08-22 18:15:50 +00001129 return *File;
Chris Lattner63dd32b2006-10-20 04:42:40 +00001130}
1131
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001132//===----------------------------------------------------------------------===//
1133// File Info Management.
1134//===----------------------------------------------------------------------===//
1135
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001136/// Merge the header file info provided by \p OtherHFI into the current
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001137/// header file info (\p HFI)
Fangrui Song6907ce22018-07-30 19:24:48 +00001138static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001139 const HeaderFileInfo &OtherHFI) {
Richard Smithd8879c82015-08-24 21:59:32 +00001140 assert(OtherHFI.External && "expected to merge external HFI");
1141
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001142 HFI.isImport |= OtherHFI.isImport;
1143 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001144 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001145 HFI.NumIncludes += OtherHFI.NumIncludes;
Richard Smithd8879c82015-08-24 21:59:32 +00001146
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001147 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
1148 HFI.ControllingMacro = OtherHFI.ControllingMacro;
1149 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
1150 }
Richard Smithd8879c82015-08-24 21:59:32 +00001151
1152 HFI.DirInfo = OtherHFI.DirInfo;
1153 HFI.External = (!HFI.IsValid || HFI.External);
1154 HFI.IsValid = true;
1155 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001156
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001157 if (HFI.Framework.empty())
1158 HFI.Framework = OtherHFI.Framework;
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001159}
Fangrui Song6907ce22018-07-30 19:24:48 +00001160
Steve Naroff3fa455a2009-04-24 20:03:17 +00001161/// getFileInfo - Return the HeaderFileInfo structure for the specified
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001162/// FileEntry.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001163HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001164 if (FE->getUID() >= FileInfo.size())
Richard Smith386bb072015-08-18 23:42:23 +00001165 FileInfo.resize(FE->getUID() + 1);
1166
Richard Smithd8879c82015-08-24 21:59:32 +00001167 HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
Richard Smith386bb072015-08-18 23:42:23 +00001168 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +00001169 if (ExternalSource && !HFI->Resolved) {
1170 HFI->Resolved = true;
1171 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1172
1173 HFI = &FileInfo[FE->getUID()];
1174 if (ExternalHFI.External)
1175 mergeHeaderFileInfo(*HFI, ExternalHFI);
Richard Smith386bb072015-08-18 23:42:23 +00001176 }
1177
Richard Smithd8879c82015-08-24 21:59:32 +00001178 HFI->IsValid = true;
Richard Smith386bb072015-08-18 23:42:23 +00001179 // We have local information about this header file, so it's no longer
1180 // strictly external.
Richard Smithd8879c82015-08-24 21:59:32 +00001181 HFI->External = false;
1182 return *HFI;
Mike Stump11289f42009-09-09 15:08:12 +00001183}
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001184
Richard Smith386bb072015-08-18 23:42:23 +00001185const HeaderFileInfo *
Richard Smithd8879c82015-08-24 21:59:32 +00001186HeaderSearch::getExistingFileInfo(const FileEntry *FE,
1187 bool WantExternal) const {
Richard Smith386bb072015-08-18 23:42:23 +00001188 // If we have an external source, ensure we have the latest information.
1189 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +00001190 HeaderFileInfo *HFI;
1191 if (ExternalSource) {
1192 if (FE->getUID() >= FileInfo.size()) {
1193 if (!WantExternal)
1194 return nullptr;
1195 FileInfo.resize(FE->getUID() + 1);
Richard Smith386bb072015-08-18 23:42:23 +00001196 }
Richard Smithd8879c82015-08-24 21:59:32 +00001197
1198 HFI = &FileInfo[FE->getUID()];
1199 if (!WantExternal && (!HFI->IsValid || HFI->External))
1200 return nullptr;
1201 if (!HFI->Resolved) {
1202 HFI->Resolved = true;
1203 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1204
1205 HFI = &FileInfo[FE->getUID()];
1206 if (ExternalHFI.External)
1207 mergeHeaderFileInfo(*HFI, ExternalHFI);
1208 }
1209 } else if (FE->getUID() >= FileInfo.size()) {
1210 return nullptr;
1211 } else {
1212 HFI = &FileInfo[FE->getUID()];
Ben Langmuird285c502014-03-13 16:46:36 +00001213 }
Richard Smith386bb072015-08-18 23:42:23 +00001214
Richard Smithd8879c82015-08-24 21:59:32 +00001215 if (!HFI->IsValid || (HFI->External && !WantExternal))
Richard Smith386bb072015-08-18 23:42:23 +00001216 return nullptr;
1217
Richard Smithd8879c82015-08-24 21:59:32 +00001218 return HFI;
Ben Langmuird285c502014-03-13 16:46:36 +00001219}
1220
Douglas Gregor37aa4932011-05-04 00:14:37 +00001221bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
Richard Smith0a088ea2020-04-28 18:22:34 -07001222 // Check if we've entered this file and found an include guard or #pragma
1223 // once. Note that we dor't check for #import, because that's not a property
1224 // of the file itself.
Richard Smith386bb072015-08-18 23:42:23 +00001225 if (auto *HFI = getExistingFileInfo(File))
Richard Smith0a088ea2020-04-28 18:22:34 -07001226 return HFI->isPragmaOnce || HFI->ControllingMacro ||
Richard Smith386bb072015-08-18 23:42:23 +00001227 HFI->ControllingMacroID;
1228 return false;
Douglas Gregor37aa4932011-05-04 00:14:37 +00001229}
1230
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001231void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001232 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001233 bool isCompilingModuleHeader) {
Richard Smithd8879c82015-08-24 21:59:32 +00001234 bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1235
1236 // Don't mark the file info as non-external if there's nothing to change.
1237 if (!isCompilingModuleHeader) {
1238 if (!isModularHeader)
1239 return;
1240 auto *HFI = getExistingFileInfo(FE);
1241 if (HFI && HFI->isModuleHeader)
1242 return;
1243 }
1244
Richard Smith386bb072015-08-18 23:42:23 +00001245 auto &HFI = getFileInfo(FE);
Richard Smithd8879c82015-08-24 21:59:32 +00001246 HFI.isModuleHeader |= isModularHeader;
Richard Smithe70dadd2015-07-10 22:27:17 +00001247 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001248}
1249
Richard Smith20e883e2015-04-29 23:20:19 +00001250bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001251 const FileEntry *File, bool isImport,
1252 bool ModulesEnabled, Module *M) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001253 ++NumIncluded; // Count # of attempted #includes.
1254
1255 // Get information about this file.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001256 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump11289f42009-09-09 15:08:12 +00001257
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001258 // FIXME: this is a workaround for the lack of proper modules-aware support
1259 // for #import / #pragma once
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +00001260 auto TryEnterImported = [&]() -> bool {
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001261 if (!ModulesEnabled)
1262 return false;
Richard Smith040e1262017-06-02 01:55:39 +00001263 // Ensure FileInfo bits are up to date.
1264 ModMap.resolveHeaderDirectives(File);
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001265 // Modules with builtins are special; multiple modules use builtins as
1266 // modular headers, example:
1267 //
1268 // module stddef { header "stddef.h" export * }
1269 //
1270 // After module map parsing, this expands to:
1271 //
1272 // module stddef {
1273 // header "/path_to_builtin_dirs/stddef.h"
1274 // textual "stddef.h"
1275 // }
1276 //
1277 // It's common that libc++ and system modules will both define such
1278 // submodules. Make sure cached results for a builtin header won't
1279 // prevent other builtin modules to potentially enter the builtin header.
1280 // Note that builtins are header guarded and the decision to actually
1281 // enter them is postponed to the controlling macros logic below.
1282 bool TryEnterHdr = false;
1283 if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
1284 TryEnterHdr = File->getDir() == ModMap.getBuiltinDir() &&
1285 ModuleMap::isBuiltinHeader(
1286 llvm::sys::path::filename(File->getName()));
1287
1288 // Textual headers can be #imported from different modules. Since ObjC
1289 // headers find in the wild might rely only on #import and do not contain
1290 // controlling macros, be conservative and only try to enter textual headers
1291 // if such macro is present.
Bruno Cardoso Lopes4164dd92017-08-12 01:38:26 +00001292 if (!FileInfo.isModuleHeader &&
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001293 FileInfo.getControllingMacro(ExternalLookup))
1294 TryEnterHdr = true;
1295 return TryEnterHdr;
1296 };
1297
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001298 // If this is a #import directive, check that we have not already imported
1299 // this header.
1300 if (isImport) {
1301 // If this has already been imported, don't import it again.
1302 FileInfo.isImport = true;
Mike Stump11289f42009-09-09 15:08:12 +00001303
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001304 // Has this already been #import'ed or #include'd?
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001305 if (FileInfo.NumIncludes && !TryEnterImported())
1306 return false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001307 } else {
1308 // Otherwise, if this is a #include of a file that was previously #import'd
1309 // or if this is the second #include of a #pragma once file, ignore it.
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001310 if (FileInfo.isImport && !TryEnterImported())
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001311 return false;
1312 }
Mike Stump11289f42009-09-09 15:08:12 +00001313
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001314 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1315 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump11289f42009-09-09 15:08:12 +00001316 if (const IdentifierInfo *ControllingMacro
Richard Smithe70dadd2015-07-10 22:27:17 +00001317 = FileInfo.getControllingMacro(ExternalLookup)) {
1318 // If the header corresponds to a module, check whether the macro is already
1319 // defined in that module rather than checking in the current set of visible
1320 // modules.
1321 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1322 : PP.isMacroDefined(ControllingMacro)) {
Douglas Gregor99734e72009-04-25 23:30:02 +00001323 ++NumMultiIncludeFileOptzn;
1324 return false;
1325 }
Richard Smithe70dadd2015-07-10 22:27:17 +00001326 }
Mike Stump11289f42009-09-09 15:08:12 +00001327
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001328 // Increment the number of times this file has been included.
1329 ++FileInfo.NumIncludes;
Mike Stump11289f42009-09-09 15:08:12 +00001330
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001331 return true;
1332}
1333
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001334size_t HeaderSearch::getTotalMemory() const {
1335 return SearchDirs.capacity()
Ted Kremenekae63d102011-07-27 18:41:18 +00001336 + llvm::capacity_in_bytes(FileInfo)
1337 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001338 + LookupFileCache.getAllocator().getTotalMemory()
1339 + FrameworkMap.getAllocator().getTotalMemory();
1340}
Douglas Gregor9f93e382011-07-28 04:45:53 +00001341
1342StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
David Blaikie13156b62014-11-19 03:06:06 +00001343 return FrameworkNames.insert(Framework).first->first();
Douglas Gregor9f93e382011-07-28 04:45:53 +00001344}
Douglas Gregor718292f2011-11-11 19:10:28 +00001345
Fangrui Song6907ce22018-07-30 19:24:48 +00001346bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor963c5532013-06-21 16:28:10 +00001347 const DirectoryEntry *Root,
1348 bool IsSystem) {
Richard Smith47972af2015-06-16 00:08:24 +00001349 if (!HSOpts->ImplicitModuleMaps)
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +00001350 return false;
1351
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001352 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Fangrui Song6907ce22018-07-30 19:24:48 +00001353
Douglas Gregor718292f2011-11-11 19:10:28 +00001354 StringRef DirName = FileName;
1355 do {
1356 // Get the parent directory name.
1357 DirName = llvm::sys::path::parent_path(DirName);
1358 if (DirName.empty())
1359 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001360
Douglas Gregor718292f2011-11-11 19:10:28 +00001361 // Determine whether this directory exists.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001362 auto Dir = FileMgr.getDirectory(DirName);
Douglas Gregor718292f2011-11-11 19:10:28 +00001363 if (!Dir)
1364 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001365
Ben Langmuir984e1df2014-03-19 20:23:34 +00001366 // Try to load the module map file in this directory.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001367 switch (loadModuleMapFile(*Dir, IsSystem,
1368 llvm::sys::path::extension((*Dir)->getName()) ==
Richard Smith3c1a41a2014-12-02 00:08:08 +00001369 ".framework")) {
Douglas Gregor80b69042011-11-12 00:22:19 +00001370 case LMM_NewlyLoaded:
1371 case LMM_AlreadyLoaded:
Daniel Jasperca9f7382013-09-24 09:27:13 +00001372 // Success. All of the directories we stepped through inherit this module
1373 // map file.
1374 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1375 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1376 return true;
Daniel Jasper97da9172013-10-22 08:09:47 +00001377
1378 case LMM_NoDirectory:
1379 case LMM_InvalidModuleMap:
1380 break;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001381 }
1382
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001383 // If we hit the top of our search, we're done.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001384 if (*Dir == Root)
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001385 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001386
Douglas Gregor718292f2011-11-11 19:10:28 +00001387 // Keep track of all of the directories we checked, so we can mark them as
1388 // having module maps if we eventually do find a module map.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001389 FixUpDirectories.push_back(*Dir);
Douglas Gregor718292f2011-11-11 19:10:28 +00001390 } while (true);
Douglas Gregor718292f2011-11-11 19:10:28 +00001391}
1392
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001393ModuleMap::KnownHeader
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001394HeaderSearch::findModuleForHeader(const FileEntry *File,
1395 bool AllowTextual) const {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001396 if (ExternalSource) {
1397 // Make sure the external source has handled header info about this file,
1398 // which includes whether the file is part of a module.
Richard Smith386bb072015-08-18 23:42:23 +00001399 (void)getExistingFileInfo(File);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001400 }
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001401 return ModMap.findModuleForHeader(File, AllowTextual);
1402}
1403
Richard Smith0a088ea2020-04-28 18:22:34 -07001404ArrayRef<ModuleMap::KnownHeader>
1405HeaderSearch::findAllModulesForHeader(const FileEntry *File) const {
1406 if (ExternalSource) {
1407 // Make sure the external source has handled header info about this file,
1408 // which includes whether the file is part of a module.
1409 (void)getExistingFileInfo(File);
1410 }
1411 return ModMap.findAllModulesForHeader(File);
1412}
1413
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001414static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1415 Module *RequestingModule,
1416 ModuleMap::KnownHeader *SuggestedModule) {
1417 ModuleMap::KnownHeader Module =
1418 HS.findModuleForHeader(File, /*AllowTextual*/true);
1419 if (SuggestedModule)
1420 *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1421 ? ModuleMap::KnownHeader()
1422 : Module;
1423
1424 // If this module specifies [no_undeclared_includes], we cannot find any
1425 // file that's in a non-dependency module.
1426 if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1427 HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/false);
1428 if (!RequestingModule->directlyUses(Module.getModule())) {
1429 return false;
1430 }
1431 }
1432
1433 return true;
Douglas Gregor718292f2011-11-11 19:10:28 +00001434}
1435
Richard Smith3d5b48c2015-10-16 21:42:56 +00001436bool HeaderSearch::findUsableModuleForHeader(
1437 const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1438 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001439 if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
Richard Smith3d5b48c2015-10-16 21:42:56 +00001440 // If there is a module that corresponds to this header, suggest it.
1441 hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001442 return suggestModule(*this, File, RequestingModule, SuggestedModule);
Richard Smith3d5b48c2015-10-16 21:42:56 +00001443 }
1444 return true;
1445}
1446
1447bool HeaderSearch::findUsableModuleForFrameworkHeader(
1448 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1449 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1450 // If we're supposed to suggest a module, look for one now.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001451 if (needModuleLookup(RequestingModule, SuggestedModule)) {
Richard Smith3d5b48c2015-10-16 21:42:56 +00001452 // Find the top-level framework based on this framework.
1453 SmallVector<std::string, 4> SubmodulePath;
1454 const DirectoryEntry *TopFrameworkDir
1455 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
Fangrui Song6907ce22018-07-30 19:24:48 +00001456
Richard Smith3d5b48c2015-10-16 21:42:56 +00001457 // Determine the name of the top-level framework.
1458 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1459
1460 // Load this framework module. If that succeeds, find the suggested module
1461 // for this header, if any.
1462 loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1463
1464 // FIXME: This can find a module not part of ModuleName, which is
1465 // important so that we're consistent about whether this header
1466 // corresponds to a module. Possibly we should lock down framework modules
1467 // so that this is not possible.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001468 return suggestModule(*this, File, RequestingModule, SuggestedModule);
Richard Smith3d5b48c2015-10-16 21:42:56 +00001469 }
1470 return true;
1471}
1472
Richard Smith9acb99e32014-12-10 03:09:48 +00001473static const FileEntry *getPrivateModuleMap(const FileEntry *File,
Ben Langmuir984e1df2014-03-19 20:23:34 +00001474 FileManager &FileMgr) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001475 StringRef Filename = llvm::sys::path::filename(File->getName());
1476 SmallString<128> PrivateFilename(File->getDir()->getName());
Ben Langmuir984e1df2014-03-19 20:23:34 +00001477 if (Filename == "module.map")
Douglas Gregor80306772011-12-07 21:25:07 +00001478 llvm::sys::path::append(PrivateFilename, "module_private.map");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001479 else if (Filename == "module.modulemap")
1480 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1481 else
1482 return nullptr;
Harlan Haskins8d323d12019-08-01 21:31:56 +00001483 if (auto File = FileMgr.getFile(PrivateFilename))
1484 return *File;
1485 return nullptr;
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001486}
1487
Richard Smith8128f332017-05-05 22:18:51 +00001488bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
Richard Smith8b706102017-05-31 20:56:55 +00001489 FileID ID, unsigned *Offset,
1490 StringRef OriginalModuleMapFile) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001491 // Find the directory for the module. For frameworks, that may require going
1492 // up from the 'Modules' directory.
1493 const DirectoryEntry *Dir = nullptr;
Harlan Haskins8d323d12019-08-01 21:31:56 +00001494 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) {
1495 if (auto DirOrErr = FileMgr.getDirectory("."))
1496 Dir = *DirOrErr;
1497 } else {
Richard Smith8b706102017-05-31 20:56:55 +00001498 if (!OriginalModuleMapFile.empty()) {
1499 // We're building a preprocessed module map. Find or invent the directory
1500 // that it originally occupied.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001501 auto DirOrErr = FileMgr.getDirectory(
Richard Smith8b706102017-05-31 20:56:55 +00001502 llvm::sys::path::parent_path(OriginalModuleMapFile));
Harlan Haskins8d323d12019-08-01 21:31:56 +00001503 if (DirOrErr) {
1504 Dir = *DirOrErr;
1505 } else {
Richard Smith8b706102017-05-31 20:56:55 +00001506 auto *FakeFile = FileMgr.getVirtualFile(OriginalModuleMapFile, 0, 0);
1507 Dir = FakeFile->getDir();
1508 }
1509 } else {
1510 Dir = File->getDir();
1511 }
1512
Richard Smith9acb99e32014-12-10 03:09:48 +00001513 StringRef DirName(Dir->getName());
1514 if (llvm::sys::path::filename(DirName) == "Modules") {
1515 DirName = llvm::sys::path::parent_path(DirName);
1516 if (DirName.endswith(".framework"))
Harlan Haskins8d323d12019-08-01 21:31:56 +00001517 if (auto DirOrErr = FileMgr.getDirectory(DirName))
1518 Dir = *DirOrErr;
Richard Smith9acb99e32014-12-10 03:09:48 +00001519 // FIXME: This assert can fail if there's a race between the above check
1520 // and the removal of the directory.
1521 assert(Dir && "parent must exist");
1522 }
1523 }
1524
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001525 switch (loadModuleMapFileImpl(File, IsSystem, Dir, ID, Offset)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001526 case LMM_AlreadyLoaded:
1527 case LMM_NewlyLoaded:
1528 return false;
1529 case LMM_NoDirectory:
1530 case LMM_InvalidModuleMap:
1531 return true;
1532 }
Aaron Ballmand8de5b62014-03-20 14:22:33 +00001533 llvm_unreachable("Unknown load module map result");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001534}
1535
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001536HeaderSearch::LoadModuleMapResult
1537HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1538 const DirectoryEntry *Dir, FileID ID,
1539 unsigned *Offset) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001540 assert(File && "expected FileEntry");
1541
Richard Smith9887d792014-10-17 01:42:53 +00001542 // Check whether we've already loaded this module map, and mark it as being
1543 // loaded in case we recursively try to load it from itself.
1544 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1545 if (!AddResult.second)
1546 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001547
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001548 if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
Richard Smith9887d792014-10-17 01:42:53 +00001549 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001550 return LMM_InvalidModuleMap;
1551 }
1552
1553 // Try to load a corresponding private module map.
Richard Smith9acb99e32014-12-10 03:09:48 +00001554 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001555 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001556 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001557 return LMM_InvalidModuleMap;
1558 }
1559 }
1560
1561 // This directory has a module map.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001562 return LMM_NewlyLoaded;
1563}
1564
1565const FileEntry *
1566HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
Richard Smith47972af2015-06-16 00:08:24 +00001567 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001568 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001569 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1570 // module.map at the framework root is also accepted.
1571 SmallString<128> ModuleMapFileName(Dir->getName());
1572 if (IsFramework)
1573 llvm::sys::path::append(ModuleMapFileName, "Modules");
1574 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
Harlan Haskins8d323d12019-08-01 21:31:56 +00001575 if (auto F = FileMgr.getFile(ModuleMapFileName))
1576 return *F;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001577
1578 // Continue to allow module.map
1579 ModuleMapFileName = Dir->getName();
1580 llvm::sys::path::append(ModuleMapFileName, "module.map");
Harlan Haskins8d323d12019-08-01 21:31:56 +00001581 if (auto F = FileMgr.getFile(ModuleMapFileName))
1582 return *F;
Volodymyr Sapsai4069dd12020-02-27 15:51:24 -08001583
1584 // For frameworks, allow to have a private module map with a preferred
1585 // spelling when a public module map is absent.
1586 if (IsFramework) {
1587 ModuleMapFileName = Dir->getName();
1588 llvm::sys::path::append(ModuleMapFileName, "Modules",
1589 "module.private.modulemap");
1590 if (auto F = FileMgr.getFile(ModuleMapFileName))
1591 return *F;
1592 }
Harlan Haskins8d323d12019-08-01 21:31:56 +00001593 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001594}
1595
1596Module *HeaderSearch::loadFrameworkModule(StringRef Name,
Douglas Gregor279a6c32012-01-29 17:08:11 +00001597 const DirectoryEntry *Dir,
1598 bool IsSystem) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00001599 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor56c64012011-11-17 01:41:17 +00001600 return Module;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001601
Douglas Gregor56c64012011-11-17 01:41:17 +00001602 // Try to load a module map file.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001603 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
Douglas Gregor56c64012011-11-17 01:41:17 +00001604 case LMM_InvalidModuleMap:
Ben Langmuira5254002015-07-02 13:19:48 +00001605 // Try to infer a module map from the framework directory.
1606 if (HSOpts->ImplicitModuleMaps)
1607 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
Douglas Gregor56c64012011-11-17 01:41:17 +00001608 break;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001609
Douglas Gregor56c64012011-11-17 01:41:17 +00001610 case LMM_AlreadyLoaded:
1611 case LMM_NoDirectory:
Craig Topperd2d442c2014-05-17 23:10:59 +00001612 return nullptr;
1613
Douglas Gregor56c64012011-11-17 01:41:17 +00001614 case LMM_NewlyLoaded:
Ben Langmuira5254002015-07-02 13:19:48 +00001615 break;
Douglas Gregor56c64012011-11-17 01:41:17 +00001616 }
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001617
Ben Langmuira5254002015-07-02 13:19:48 +00001618 return ModMap.findModule(Name);
Douglas Gregor56c64012011-11-17 01:41:17 +00001619}
1620
Fangrui Song6907ce22018-07-30 19:24:48 +00001621HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001622HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1623 bool IsFramework) {
Harlan Haskins8d323d12019-08-01 21:31:56 +00001624 if (auto Dir = FileMgr.getDirectory(DirName))
1625 return loadModuleMapFile(*Dir, IsSystem, IsFramework);
Fangrui Song6907ce22018-07-30 19:24:48 +00001626
Douglas Gregor80b69042011-11-12 00:22:19 +00001627 return LMM_NoDirectory;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001628}
1629
Fangrui Song6907ce22018-07-30 19:24:48 +00001630HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001631HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1632 bool IsFramework) {
1633 auto KnownDir = DirectoryHasModuleMap.find(Dir);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001634 if (KnownDir != DirectoryHasModuleMap.end())
Richard Smith9887d792014-10-17 01:42:53 +00001635 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregore7ab3662011-12-07 02:23:45 +00001636
Ben Langmuir984e1df2014-03-19 20:23:34 +00001637 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001638 LoadModuleMapResult Result =
1639 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
Ben Langmuir984e1df2014-03-19 20:23:34 +00001640 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1641 // E.g. Foo.framework/Modules/module.modulemap
1642 // ^Dir ^ModuleMapFile
1643 if (Result == LMM_NewlyLoaded)
1644 DirectoryHasModuleMap[Dir] = true;
Richard Smith9887d792014-10-17 01:42:53 +00001645 else if (Result == LMM_InvalidModuleMap)
1646 DirectoryHasModuleMap[Dir] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001647 return Result;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001648 }
Douglas Gregor80b69042011-11-12 00:22:19 +00001649 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001650}
Douglas Gregor718292f2011-11-11 19:10:28 +00001651
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001652void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001653 Modules.clear();
Daniel Jasper21a0f552014-11-25 09:45:48 +00001654
Richard Smith47972af2015-06-16 00:08:24 +00001655 if (HSOpts->ImplicitModuleMaps) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001656 // Load module maps for each of the header search directories.
1657 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1658 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1659 if (SearchDirs[Idx].isFramework()) {
1660 std::error_code EC;
1661 SmallString<128> DirNative;
1662 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1663 DirNative);
1664
1665 // Search each of the ".framework" directories to load them as modules.
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +00001666 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
Jonas Devliegherefc514902018-10-10 13:27:25 +00001667 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
1668 DirEnd;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001669 Dir != DirEnd && !EC; Dir.increment(EC)) {
Sam McCall0ae00562018-09-14 12:47:38 +00001670 if (llvm::sys::path::extension(Dir->path()) != ".framework")
Daniel Jasper21a0f552014-11-25 09:45:48 +00001671 continue;
1672
Harlan Haskins8d323d12019-08-01 21:31:56 +00001673 auto FrameworkDir =
Sam McCall0ae00562018-09-14 12:47:38 +00001674 FileMgr.getDirectory(Dir->path());
Daniel Jasper21a0f552014-11-25 09:45:48 +00001675 if (!FrameworkDir)
1676 continue;
1677
1678 // Load this framework module.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001679 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir,
Sam McCall0ae00562018-09-14 12:47:38 +00001680 IsSystem);
Daniel Jasper21a0f552014-11-25 09:45:48 +00001681 }
1682 continue;
Douglas Gregor07f43572012-01-29 18:15:03 +00001683 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001684
1685 // FIXME: Deal with header maps.
1686 if (SearchDirs[Idx].isHeaderMap())
1687 continue;
1688
1689 // Try to load a module map file for the search directory.
1690 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1691 /*IsFramework*/ false);
1692
1693 // Try to load module map files for immediate subdirectories of this
1694 // search directory.
1695 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor07f43572012-01-29 18:15:03 +00001696 }
Douglas Gregor07f43572012-01-29 18:15:03 +00001697 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001698
Douglas Gregor07f43572012-01-29 18:15:03 +00001699 // Populate the list of modules.
Fangrui Song6907ce22018-07-30 19:24:48 +00001700 for (ModuleMap::module_iterator M = ModMap.module_begin(),
Douglas Gregor07f43572012-01-29 18:15:03 +00001701 MEnd = ModMap.module_end();
1702 M != MEnd; ++M) {
1703 Modules.push_back(M->getValue());
1704 }
1705}
Douglas Gregor0339a642013-03-21 01:08:50 +00001706
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001707void HeaderSearch::loadTopLevelSystemModules() {
Richard Smith47972af2015-06-16 00:08:24 +00001708 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001709 return;
1710
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001711 // Load module maps for each of the header search directories.
1712 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor299787f2013-11-01 23:08:38 +00001713 // We only care about normal header directories.
1714 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001715 continue;
1716 }
1717
1718 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001719 loadModuleMapFile(SearchDirs[Idx].getDir(),
Ben Langmuir984e1df2014-03-19 20:23:34 +00001720 SearchDirs[Idx].isSystemHeaderDirectory(),
1721 SearchDirs[Idx].isFramework());
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001722 }
1723}
1724
Douglas Gregor0339a642013-03-21 01:08:50 +00001725void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
Richard Smith47972af2015-06-16 00:08:24 +00001726 assert(HSOpts->ImplicitModuleMaps &&
Daniel Jasper21a0f552014-11-25 09:45:48 +00001727 "Should not be loading subdirectory module maps");
1728
Douglas Gregor0339a642013-03-21 01:08:50 +00001729 if (SearchDir.haveSearchedAllModuleMaps())
1730 return;
Rafael Espindolac0809172014-06-12 14:02:15 +00001731
1732 std::error_code EC;
Alex Lorenz7d76ef92018-11-14 01:08:03 +00001733 SmallString<128> Dir = SearchDir.getDir()->getName();
1734 FileMgr.makeAbsolutePath(Dir);
Douglas Gregor0339a642013-03-21 01:08:50 +00001735 SmallString<128> DirNative;
Alex Lorenz7d76ef92018-11-14 01:08:03 +00001736 llvm::sys::path::native(Dir, DirNative);
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +00001737 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
Jonas Devliegherefc514902018-10-10 13:27:25 +00001738 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Douglas Gregor0339a642013-03-21 01:08:50 +00001739 Dir != DirEnd && !EC; Dir.increment(EC)) {
Sam McCall0ae00562018-09-14 12:47:38 +00001740 bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001741 if (IsFramework == SearchDir.isFramework())
Sam McCall0ae00562018-09-14 12:47:38 +00001742 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001743 SearchDir.isFramework());
Douglas Gregor0339a642013-03-21 01:08:50 +00001744 }
1745
1746 SearchDir.setSearchedAllModuleMaps(true);
1747}
Richard Smith4eb83932016-04-27 21:57:05 +00001748
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001749std::string HeaderSearch::suggestPathToFileForDiagnostics(
1750 const FileEntry *File, llvm::StringRef MainFile, bool *IsSystem) {
Richard Smith4eb83932016-04-27 21:57:05 +00001751 // FIXME: We assume that the path name currently cached in the FileEntry is
Eric Liudffb1a82018-01-29 13:21:23 +00001752 // the most appropriate one for this analysis (and that it's spelled the
1753 // same way as the corresponding header search path).
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001754 return suggestPathToFileForDiagnostics(File->getName(), /*WorkingDir=*/"",
1755 MainFile, IsSystem);
Eric Liudffb1a82018-01-29 13:21:23 +00001756}
1757
1758std::string HeaderSearch::suggestPathToFileForDiagnostics(
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001759 llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile,
1760 bool *IsSystem) {
Eric Liudffb1a82018-01-29 13:21:23 +00001761 using namespace llvm::sys;
Richard Smith4eb83932016-04-27 21:57:05 +00001762
1763 unsigned BestPrefixLength = 0;
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001764 // Checks whether Dir and File shares a common prefix, if they do and that's
1765 // the longest prefix we've seen so for it returns true and updates the
1766 // BestPrefixLength accordingly.
1767 auto CheckDir = [&](llvm::StringRef Dir) -> bool {
Eric Liudffb1a82018-01-29 13:21:23 +00001768 llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
Kadir Cetinkaya936c67d2019-04-24 09:23:31 +00001769 if (!WorkingDir.empty() && !path::is_absolute(Dir))
Pavel Labath1ad53ca2019-01-16 09:55:32 +00001770 fs::make_absolute(WorkingDir, DirPath);
Kadir Cetinkaya936c67d2019-04-24 09:23:31 +00001771 path::remove_dots(DirPath, /*remove_dot_dot=*/true);
1772 Dir = DirPath;
Eric Liudffb1a82018-01-29 13:21:23 +00001773 for (auto NI = path::begin(File), NE = path::end(File),
1774 DI = path::begin(Dir), DE = path::end(Dir);
Richard Smith4eb83932016-04-27 21:57:05 +00001775 /*termination condition in loop*/; ++NI, ++DI) {
Eric Liudffb1a82018-01-29 13:21:23 +00001776 // '.' components in File are ignored.
Richard Smith4eb83932016-04-27 21:57:05 +00001777 while (NI != NE && *NI == ".")
1778 ++NI;
1779 if (NI == NE)
1780 break;
1781
1782 // '.' components in Dir are ignored.
1783 while (DI != DE && *DI == ".")
1784 ++DI;
1785 if (DI == DE) {
Eric Liudffb1a82018-01-29 13:21:23 +00001786 // Dir is a prefix of File, up to '.' components and choice of path
Richard Smith4eb83932016-04-27 21:57:05 +00001787 // separators.
Eric Liudffb1a82018-01-29 13:21:23 +00001788 unsigned PrefixLength = NI - path::begin(File);
Richard Smith4eb83932016-04-27 21:57:05 +00001789 if (PrefixLength > BestPrefixLength) {
1790 BestPrefixLength = PrefixLength;
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001791 return true;
Richard Smith4eb83932016-04-27 21:57:05 +00001792 }
1793 break;
1794 }
1795
Kadir Cetinkaya51f85b42019-06-06 18:49:16 +00001796 // Consider all path separators equal.
1797 if (NI->size() == 1 && DI->size() == 1 &&
1798 path::is_separator(NI->front()) && path::is_separator(DI->front()))
1799 continue;
1800
Richard Smith4eb83932016-04-27 21:57:05 +00001801 if (*NI != *DI)
1802 break;
1803 }
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001804 return false;
1805 };
1806
1807 for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1808 // FIXME: Support this search within frameworks and header maps.
1809 if (!SearchDirs[I].isNormalDir())
1810 continue;
1811
1812 StringRef Dir = SearchDirs[I].getDir()->getName();
1813 if (CheckDir(Dir) && IsSystem)
1814 *IsSystem = BestPrefixLength ? I >= SystemDirIdx : false;
Richard Smith4eb83932016-04-27 21:57:05 +00001815 }
1816
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001817 // Try to shorten include path using TUs directory, if we couldn't find any
1818 // suitable prefix in include search paths.
1819 if (!BestPrefixLength && CheckDir(path::parent_path(MainFile)) && IsSystem)
1820 *IsSystem = false;
1821
1822
Kadir Cetinkaya40f8f7f2019-04-24 08:45:03 +00001823 return path::convert_to_slash(File.drop_front(BestPrefixLength));
Richard Smith4eb83932016-04-27 21:57:05 +00001824}