blob: b1a2ef121288e505f214eb2f710e508b00fe0b81 [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//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59a9ebd2006-10-18 05:34:33 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the DirectoryLookup and HeaderSearch interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner59a9ebd2006-10-18 05:34:33 +000014#include "clang/Lex/HeaderSearch.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000015#include "clang/Basic/Diagnostic.h"
Chris Lattneref6b1362007-10-07 08:58:51 +000016#include "clang/Basic/FileManager.h"
17#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000018#include "clang/Basic/Module.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/VirtualFileSystem.h"
21#include "clang/Lex/DirectoryLookup.h"
Richard Smith2aedca32015-07-01 02:29:35 +000022#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Lex/HeaderMap.h"
24#include "clang/Lex/HeaderSearchOptions.h"
Will Wilson0fafd342013-12-27 19:46:16 +000025#include "clang/Lex/LexDiagnostic.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000026#include "clang/Lex/ModuleMap.h"
Richard Smith20e883e2015-04-29 23:20:19 +000027#include "clang/Lex/Preprocessor.h"
Ben Langmuirbeee15e2014-04-14 18:00:01 +000028#include "llvm/ADT/APInt.h"
29#include "llvm/ADT/Hashing.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +000030#include "llvm/ADT/SmallString.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000031#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/StringRef.h"
33#include "llvm/Support/Allocator.h"
Ted Kremenekae63d102011-07-27 18:41:18 +000034#include "llvm/Support/Capacity.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"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000038#include <algorithm>
39#include <cassert>
40#include <cstddef>
Chris Lattnerc25d8a72009-03-02 22:20:04 +000041#include <cstdio>
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000042#include <cstring>
43#include <string>
44#include <system_error>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000045#include <utility>
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000046
Chris Lattner59a9ebd2006-10-18 05:34:33 +000047using namespace clang;
48
Douglas Gregor99734e72009-04-25 23:30:02 +000049const IdentifierInfo *
Richard Smith2aedca32015-07-01 02:29:35 +000050HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {
51 if (ControllingMacro) {
Chandler Carruth59666772016-11-04 06:32:57 +000052 if (ControllingMacro->isOutOfDate()) {
53 assert(External && "We must have an external source if we have a "
54 "controlling macro that is out of date.");
Richard Smith2aedca32015-07-01 02:29:35 +000055 External->updateOutOfDateIdentifier(
56 *const_cast<IdentifierInfo *>(ControllingMacro));
Chandler Carruth59666772016-11-04 06:32:57 +000057 }
Douglas Gregor99734e72009-04-25 23:30:02 +000058 return ControllingMacro;
Richard Smith2aedca32015-07-01 02:29:35 +000059 }
Douglas Gregor99734e72009-04-25 23:30:02 +000060
61 if (!ControllingMacroID || !External)
Craig Topperd2d442c2014-05-17 23:10:59 +000062 return nullptr;
Douglas Gregor99734e72009-04-25 23:30:02 +000063
64 ControllingMacro = External->GetIdentifier(ControllingMacroID);
65 return ControllingMacro;
66}
67
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000068ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() = default;
Douglas Gregor09b69892011-02-10 17:09:37 +000069
David Blaikie9c28cb32017-01-06 01:04:46 +000070HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +000071 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
Will Wilson0fafd342013-12-27 19:46:16 +000072 const LangOptions &LangOpts,
Douglas Gregor89929282012-01-30 06:01:29 +000073 const TargetInfo *Target)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000074 : HSOpts(std::move(HSOpts)), Diags(Diags),
75 FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000076 ModMap(SourceMgr, Diags, LangOpts, Target, *this) {}
Chris Lattner641a0be2006-10-20 06:23:14 +000077
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000078HeaderSearch::~HeaderSearch() {
79 // Delete headermaps.
80 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
81 delete HeaderMaps[i].second;
82}
Mike Stump11289f42009-09-09 15:08:12 +000083
Chris Lattner59a9ebd2006-10-18 05:34:33 +000084void HeaderSearch::PrintStats() {
Chris Lattner23b7eb62007-06-15 23:05:46 +000085 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
86 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
Chris Lattner59a9ebd2006-10-18 05:34:33 +000087 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
88 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
89 NumOnceOnlyFiles += FileInfo[i].isImport;
90 if (MaxNumIncludes < FileInfo[i].NumIncludes)
91 MaxNumIncludes = FileInfo[i].NumIncludes;
92 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
93 }
Chris Lattner23b7eb62007-06-15 23:05:46 +000094 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
95 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
96 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump11289f42009-09-09 15:08:12 +000097
Chris Lattner23b7eb62007-06-15 23:05:46 +000098 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
99 fprintf(stderr, " %d #includes skipped due to"
100 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump11289f42009-09-09 15:08:12 +0000101
Chris Lattner23b7eb62007-06-15 23:05:46 +0000102 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
103 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000104}
105
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000106/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000107/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner4ffe46c2007-12-17 18:34:53 +0000108const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000109 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerf62f7582007-12-17 07:52:39 +0000110 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000111 if (!HeaderMaps.empty()) {
112 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerf62f7582007-12-17 07:52:39 +0000113 // Pointer equality comparison of FileEntries works because they are
114 // already uniqued by inode.
Mike Stump11289f42009-09-09 15:08:12 +0000115 if (HeaderMaps[i].first == FE)
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000116 return HeaderMaps[i].second;
117 }
Mike Stump11289f42009-09-09 15:08:12 +0000118
Chris Lattner5159f612010-11-23 08:35:12 +0000119 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000120 HeaderMaps.push_back(std::make_pair(FE, HM));
121 return HM;
122 }
Mike Stump11289f42009-09-09 15:08:12 +0000123
Craig Topperd2d442c2014-05-17 23:10:59 +0000124 return nullptr;
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000125}
126
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000127/// Get filenames for all registered header maps.
Bruno Cardoso Lopes181225b2016-12-11 04:27:28 +0000128void HeaderSearch::getHeaderMapFileNames(
129 SmallVectorImpl<std::string> &Names) const {
130 for (auto &HM : HeaderMaps)
131 Names.push_back(HM.first->getName());
132}
133
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000134std::string HeaderSearch::getCachedModuleFileName(Module *Module) {
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000135 const FileEntry *ModuleMap =
136 getModuleMap().getModuleMapFileForUniquing(Module);
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000137 return getCachedModuleFileName(Module->Name, ModuleMap->getName());
Douglas Gregor279a6c32012-01-29 17:08:11 +0000138}
139
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000140std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,
141 bool FileMapOnly) {
142 // First check the module name to pcm file map.
143 auto i (HSOpts->PrebuiltModuleFiles.find(ModuleName));
144 if (i != HSOpts->PrebuiltModuleFiles.end())
145 return i->second;
146
147 if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000148 return {};
Manman Ren11f2a472016-08-18 17:42:15 +0000149
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000150 // Then go through each prebuilt module directory and try to find the pcm
151 // file.
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000152 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
153 SmallString<256> Result(Dir);
154 llvm::sys::fs::make_absolute(Result);
155 llvm::sys::path::append(Result, ModuleName + ".pcm");
156 if (getFileMgr().getFile(Result.str()))
157 return Result.str().str();
Manman Ren11f2a472016-08-18 17:42:15 +0000158 }
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000159 return {};
160}
Manman Ren11f2a472016-08-18 17:42:15 +0000161
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000162std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,
163 StringRef ModuleMapPath) {
Richard Smithd520a252015-07-21 18:07:47 +0000164 // If we don't have a module cache path or aren't supposed to use one, we
165 // can't do anything.
Richard Smith3938f0c2015-08-15 00:34:15 +0000166 if (getModuleCachePath().empty())
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000167 return {};
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000168
Richard Smith3938f0c2015-08-15 00:34:15 +0000169 SmallString<256> Result(getModuleCachePath());
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000170 llvm::sys::fs::make_absolute(Result);
171
172 if (HSOpts->DisableModuleHash) {
173 llvm::sys::path::append(Result, ModuleName + ".pcm");
174 } else {
175 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
Richard Smith54cc3c22014-12-11 20:50:24 +0000176 // ideally be globally unique to this particular module. Name collisions
177 // in the hash are safe (because any translation unit can only import one
178 // module with each name), but result in a loss of caching.
179 //
180 // To avoid false-negatives, we form as canonical a path as we can, and map
181 // to lower-case in case we're on a case-insensitive file system.
Richard Smith3f57cff2017-03-09 00:58:22 +0000182 std::string Parent = llvm::sys::path::parent_path(ModuleMapPath);
183 if (Parent.empty())
184 Parent = ".";
185 auto *Dir = FileMgr.getDirectory(Parent);
Richard Smith54cc3c22014-12-11 20:50:24 +0000186 if (!Dir)
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000187 return {};
Richard Smith54cc3c22014-12-11 20:50:24 +0000188 auto DirName = FileMgr.getCanonicalName(Dir);
189 auto FileName = llvm::sys::path::filename(ModuleMapPath);
190
191 llvm::hash_code Hash =
Adrian Prantl793038d32016-01-12 21:01:56 +0000192 llvm::hash_combine(DirName.lower(), FileName.lower());
Richard Smith54cc3c22014-12-11 20:50:24 +0000193
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000194 SmallString<128> HashStr;
Richard Smith54cc3c22014-12-11 20:50:24 +0000195 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
Yaron Keren92e1b622015-03-18 10:17:07 +0000196 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000197 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000198 return Result.str().str();
199}
200
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000201Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch,
202 bool AllowExtraModuleMapSearch) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000203 // Look in the module map to determine if there is a module by this name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000204 Module *Module = ModMap.findModule(ModuleName);
Richard Smith47972af2015-06-16 00:08:24 +0000205 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
Douglas Gregor279a6c32012-01-29 17:08:11 +0000206 return Module;
Graydon Hoare4d867642016-12-21 00:24:39 +0000207
208 StringRef SearchName = ModuleName;
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000209 Module = lookupModule(ModuleName, SearchName, AllowExtraModuleMapSearch);
Graydon Hoare4d867642016-12-21 00:24:39 +0000210
211 // The facility for "private modules" -- adjacent, optional module maps named
212 // module.private.modulemap that are supposed to define private submodules --
Bruno Cardoso Lopes297299192017-12-22 02:53:30 +0000213 // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private.
214 //
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000215 // Foo.Private is now deprecated in favor of Foo_Private. Users of FooPrivate
Bruno Cardoso Lopes297299192017-12-22 02:53:30 +0000216 // should also rename to Foo_Private. Representing private as submodules
217 // could force building unwanted dependencies into the parent module and cause
218 // dependency cycles.
219 if (!Module && SearchName.consume_back("_Private"))
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000220 Module = lookupModule(ModuleName, SearchName, AllowExtraModuleMapSearch);
Graydon Hoare4d867642016-12-21 00:24:39 +0000221 if (!Module && SearchName.consume_back("Private"))
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000222 Module = lookupModule(ModuleName, SearchName, AllowExtraModuleMapSearch);
Graydon Hoare4d867642016-12-21 00:24:39 +0000223 return Module;
224}
225
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000226Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName,
227 bool AllowExtraModuleMapSearch) {
Graydon Hoare4d867642016-12-21 00:24:39 +0000228 Module *Module = nullptr;
229
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000230 // Look through the various header search paths to load any available module
Douglas Gregor279a6c32012-01-29 17:08:11 +0000231 // maps, searching for a module map that describes this module.
232 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
233 if (SearchDirs[Idx].isFramework()) {
Graydon Hoare4d867642016-12-21 00:24:39 +0000234 // Search for or infer a module map for a framework. Here we use
235 // SearchName rather than ModuleName, to permit finding private modules
236 // named FooPrivate in buggy frameworks named Foo.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000237 SmallString<128> FrameworkDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000238 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
Graydon Hoare4d867642016-12-21 00:24:39 +0000239 llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
240 if (const DirectoryEntry *FrameworkDir
Douglas Gregor279a6c32012-01-29 17:08:11 +0000241 = FileMgr.getDirectory(FrameworkDirName)) {
242 bool IsSystem
243 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
244 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000245 if (Module)
246 break;
247 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000248 }
249
250 // FIXME: Figure out how header maps and module maps will work together.
251
252 // Only deal with normal search directories.
253 if (!SearchDirs[Idx].isNormalDir())
254 continue;
Douglas Gregor963c5532013-06-21 16:28:10 +0000255
256 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor279a6c32012-01-29 17:08:11 +0000257 // Search for a module map file in this directory.
Ben Langmuir984e1df2014-03-19 20:23:34 +0000258 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
259 /*IsFramework*/false) == LMM_NewlyLoaded) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000260 // We just loaded a module map file; check whether the module is
261 // available now.
262 Module = ModMap.findModule(ModuleName);
263 if (Module)
264 break;
265 }
266
267 // Search for a module map in a subdirectory with the same name as the
268 // module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000269 SmallString<128> NestedModuleMapDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000270 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
271 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Ben Langmuir984e1df2014-03-19 20:23:34 +0000272 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
273 /*IsFramework*/false) == LMM_NewlyLoaded){
Douglas Gregor279a6c32012-01-29 17:08:11 +0000274 // If we just loaded a module map file, look for the module again.
275 Module = ModMap.findModule(ModuleName);
276 if (Module)
277 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000278 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000279
280 // If we've already performed the exhaustive search for module maps in this
281 // search directory, don't do it again.
282 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
283 continue;
284
285 // Load all module maps in the immediate subdirectories of this search
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000286 // directory if ModuleName was from @import.
287 if (AllowExtraModuleMapSearch)
288 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor0339a642013-03-21 01:08:50 +0000289
290 // Look again for the module.
291 Module = ModMap.findModule(ModuleName);
292 if (Module)
293 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000294 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000295
Douglas Gregor279a6c32012-01-29 17:08:11 +0000296 return Module;
Douglas Gregor1e44e022011-09-12 20:41:59 +0000297}
298
Chris Lattnerf62f7582007-12-17 07:52:39 +0000299//===----------------------------------------------------------------------===//
300// File lookup within a DirectoryLookup scope
301//===----------------------------------------------------------------------===//
302
Chris Lattner8d720d02007-12-17 17:57:27 +0000303/// getName - Return the directory or filename corresponding to this lookup
304/// object.
Mehdi Amini99d1b292016-10-01 16:38:28 +0000305StringRef DirectoryLookup::getName() const {
Chris Lattner8d720d02007-12-17 17:57:27 +0000306 if (isNormalDir())
307 return getDir()->getName();
308 if (isFramework())
309 return getFrameworkDir()->getName();
310 assert(isHeaderMap() && "Unknown DirectoryLookup");
311 return getHeaderMap()->getFileName();
312}
313
Richard Smith3d5b48c2015-10-16 21:42:56 +0000314const FileEntry *HeaderSearch::getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000315 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
316 bool IsSystemHeaderDir, Module *RequestingModule,
317 ModuleMap::KnownHeader *SuggestedModule) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000318 // If we have a module map that might map this header, load it and
319 // check whether we'll have a suggestion for a module.
Richard Smith3d5b48c2015-10-16 21:42:56 +0000320 const FileEntry *File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
Reid Klecknerafb9aae2015-10-20 18:45:57 +0000321 if (!File)
322 return nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000323
Richard Smith3d5b48c2015-10-16 21:42:56 +0000324 // If there is a module that corresponds to this header, suggest it.
325 if (!findUsableModuleForHeader(File, Dir ? Dir : File->getDir(),
326 RequestingModule, SuggestedModule,
327 IsSystemHeaderDir))
328 return nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000329
Richard Smith3d5b48c2015-10-16 21:42:56 +0000330 return File;
Richard Smith8c71eba2014-03-05 20:51:45 +0000331}
Chris Lattner8d720d02007-12-17 17:57:27 +0000332
Chris Lattnerf62f7582007-12-17 07:52:39 +0000333/// LookupFile - Lookup the specified file in this search path, returning it
334/// if it exists or returning null if not.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000335const FileEntry *DirectoryLookup::LookupFile(
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000336 StringRef &Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000337 HeaderSearch &HS,
Taewook Ohf42103c2016-06-13 20:40:21 +0000338 SourceLocation IncludeLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000339 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000340 SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000341 Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000342 ModuleMap::KnownHeader *SuggestedModule,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000343 bool &InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000344 bool &HasBeenMapped,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000345 SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000346 InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000347 HasBeenMapped = false;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000348
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000349 SmallString<1024> TmpDir;
Chris Lattner712e3872007-12-17 08:13:48 +0000350 if (isNormalDir()) {
351 // Concatenate the requested file onto the directory.
Eli Friedmanf7ca26a2011-07-08 20:17:28 +0000352 TmpDir = getDir()->getName();
353 llvm::sys::path::append(TmpDir, Filename);
Craig Topperd2d442c2014-05-17 23:10:59 +0000354 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000355 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000356 SearchPath->clear();
357 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
358 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000359 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000360 RelativePath->clear();
361 RelativePath->append(Filename.begin(), Filename.end());
362 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000363
Taewook Ohf42103c2016-06-13 20:40:21 +0000364 return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
Richard Smith3d5b48c2015-10-16 21:42:56 +0000365 isSystemHeaderDirectory(),
366 RequestingModule, SuggestedModule);
Chris Lattner712e3872007-12-17 08:13:48 +0000367 }
Mike Stump11289f42009-09-09 15:08:12 +0000368
Chris Lattner712e3872007-12-17 08:13:48 +0000369 if (isFramework())
Douglas Gregor97eec242011-09-15 22:00:41 +0000370 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000371 RequestingModule, SuggestedModule,
372 InUserSpecifiedSystemFramework);
Mike Stump11289f42009-09-09 15:08:12 +0000373
Chris Lattner44bd21b2007-12-17 08:17:39 +0000374 assert(isHeaderMap() && "Unknown directory lookup");
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000375 const HeaderMap *HM = getHeaderMap();
376 SmallString<1024> Path;
377 StringRef Dest = HM->lookupFilename(Filename, Path);
378 if (Dest.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000379 return nullptr;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000380
381 const FileEntry *Result;
382
383 // Check if the headermap maps the filename to a framework include
384 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
385 // framework include.
386 if (llvm::sys::path::is_relative(Dest)) {
387 MappedName.clear();
388 MappedName.append(Dest.begin(), Dest.end());
389 Filename = StringRef(MappedName.begin(), MappedName.size());
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000390 HasBeenMapped = true;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000391 Result = HM->LookupFile(Filename, HS.getFileMgr());
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000392 } else {
393 Result = HS.getFileMgr().getFile(Dest);
394 }
395
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000396 if (Result) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000397 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000398 StringRef SearchPathRef(getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000399 SearchPath->clear();
400 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
401 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000402 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000403 RelativePath->clear();
404 RelativePath->append(Filename.begin(), Filename.end());
405 }
406 }
407 return Result;
Chris Lattnerf62f7582007-12-17 07:52:39 +0000408}
409
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000410/// Given a framework directory, find the top-most framework directory.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000411///
412/// \param FileMgr The file manager to use for directory lookups.
413/// \param DirName The name of the framework directory.
414/// \param SubmodulePath Will be populated with the submodule path from the
415/// returned top-level module to the originally named framework.
416static const DirectoryEntry *
417getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
418 SmallVectorImpl<std::string> &SubmodulePath) {
419 assert(llvm::sys::path::extension(DirName) == ".framework" &&
420 "Not a framework directory");
421
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000422 // Note: as an egregious but useful hack we use the real path here, because
423 // frameworks moving between top-level frameworks to embedded frameworks tend
424 // to be symlinked, and we base the logical structure of modules on the
425 // physical layout. In particular, we need to deal with crazy includes like
426 //
427 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
428 //
429 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
430 // which one should access with, e.g.,
431 //
432 // #include <Bar/Wibble.h>
433 //
434 // Similar issues occur when a top-level framework has moved into an
435 // embedded framework.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000436 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
Douglas Gregore00c8b22013-01-26 00:55:12 +0000437 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000438 do {
439 // Get the parent directory name.
440 DirName = llvm::sys::path::parent_path(DirName);
441 if (DirName.empty())
442 break;
443
444 // Determine whether this directory exists.
445 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
446 if (!Dir)
447 break;
448
449 // If this is a framework directory, then we're a subframework of this
450 // framework.
451 if (llvm::sys::path::extension(DirName) == ".framework") {
452 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
453 TopFrameworkDir = Dir;
454 }
455 } while (true);
456
457 return TopFrameworkDir;
458}
Chris Lattnerf62f7582007-12-17 07:52:39 +0000459
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +0000460static bool needModuleLookup(Module *RequestingModule,
461 bool HasSuggestedModule) {
462 return HasSuggestedModule ||
463 (RequestingModule && RequestingModule->NoUndeclaredIncludes);
464}
465
Chris Lattner712e3872007-12-17 08:13:48 +0000466/// DoFrameworkLookup - Do a lookup of the specified file in the current
467/// DirectoryLookup, which is a framework directory.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000468const FileEntry *DirectoryLookup::DoFrameworkLookup(
Richard Smith3d5b48c2015-10-16 21:42:56 +0000469 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
470 SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000471 ModuleMap::KnownHeader *SuggestedModule,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000472 bool &InUserSpecifiedSystemFramework) const {
Chris Lattner712e3872007-12-17 08:13:48 +0000473 FileManager &FileMgr = HS.getFileMgr();
Mike Stump11289f42009-09-09 15:08:12 +0000474
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000475 // Framework names must have a '/' in the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000476 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000477 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000478
Chris Lattner712e3872007-12-17 08:13:48 +0000479 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar17138612012-04-05 17:09:40 +0000480 // HeaderSearch. Possible answers are yes/no and unknown.
481 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000482 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000483
Chris Lattner712e3872007-12-17 08:13:48 +0000484 // If it is known and in some other directory, fail.
Daniel Dunbar17138612012-04-05 17:09:40 +0000485 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Craig Topperd2d442c2014-05-17 23:10:59 +0000486 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000487
Chris Lattner712e3872007-12-17 08:13:48 +0000488 // Otherwise, construct the path to this framework dir.
Mike Stump11289f42009-09-09 15:08:12 +0000489
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000490 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000491 SmallString<1024> FrameworkName;
Chris Lattner712e3872007-12-17 08:13:48 +0000492 FrameworkName += getFrameworkDir()->getName();
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000493 if (FrameworkName.empty() || FrameworkName.back() != '/')
494 FrameworkName.push_back('/');
Mike Stump11289f42009-09-09 15:08:12 +0000495
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000496 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor56c64012011-11-17 01:41:17 +0000497 StringRef ModuleName(Filename.begin(), SlashPos);
498 FrameworkName += ModuleName;
Mike Stump11289f42009-09-09 15:08:12 +0000499
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000500 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
501 FrameworkName += ".framework/";
Mike Stump11289f42009-09-09 15:08:12 +0000502
Daniel Dunbar17138612012-04-05 17:09:40 +0000503 // If the cache entry was unresolved, populate it now.
Craig Topperd2d442c2014-05-17 23:10:59 +0000504 if (!CacheEntry.Directory) {
Chris Lattner712e3872007-12-17 08:13:48 +0000505 HS.IncrementFrameworkLookupCount();
Mike Stump11289f42009-09-09 15:08:12 +0000506
Chris Lattner5ed76da2006-10-22 07:24:13 +0000507 // If the framework dir doesn't exist, we fail.
Yaron Keren92e1b622015-03-18 10:17:07 +0000508 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +0000509 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000510
Chris Lattner5ed76da2006-10-22 07:24:13 +0000511 // Otherwise, if it does, remember that this is the right direntry for this
512 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000513 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000514
515 // If this is a user search directory, check if the framework has been
516 // user-specified as a system framework.
517 if (getDirCharacteristic() == SrcMgr::C_User) {
518 SmallString<1024> SystemFrameworkMarker(FrameworkName);
519 SystemFrameworkMarker += ".system_framework";
Yaron Keren92e1b622015-03-18 10:17:07 +0000520 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000521 CacheEntry.IsUserSpecifiedSystemFramework = true;
522 }
523 }
Chris Lattner5ed76da2006-10-22 07:24:13 +0000524 }
Mike Stump11289f42009-09-09 15:08:12 +0000525
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000526 // Set the 'user-specified system framework' flag.
527 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
528
Craig Topperd2d442c2014-05-17 23:10:59 +0000529 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000530 RelativePath->clear();
531 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
532 }
Douglas Gregor56c64012011-11-17 01:41:17 +0000533
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000534 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000535 unsigned OrigSize = FrameworkName.size();
Mike Stump11289f42009-09-09 15:08:12 +0000536
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000537 FrameworkName += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000538
Craig Topperd2d442c2014-05-17 23:10:59 +0000539 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000540 SearchPath->clear();
541 // Without trailing '/'.
542 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
543 }
544
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000545 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000546 const FileEntry *FE = FileMgr.getFile(FrameworkName,
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000547 /*openFile=*/!SuggestedModule);
548 if (!FE) {
549 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
550 const char *Private = "Private";
551 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
552 Private+strlen(Private));
Craig Topperd2d442c2014-05-17 23:10:59 +0000553 if (SearchPath)
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000554 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
555 Private+strlen(Private));
556
Yaron Keren92e1b622015-03-18 10:17:07 +0000557 FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule);
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000558 }
Mike Stump11289f42009-09-09 15:08:12 +0000559
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000560 // If we found the header and are allowed to suggest a module, do so now.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +0000561 if (FE && needModuleLookup(RequestingModule, SuggestedModule)) {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000562 // Find the framework in which this header occurs.
Ben Langmuiref914b82014-05-15 16:20:33 +0000563 StringRef FrameworkPath = FE->getDir()->getName();
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000564 bool FoundFramework = false;
565 do {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000566 // Determine whether this directory exists.
567 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
568 if (!Dir)
569 break;
570
571 // If this is a framework directory, then we're a subframework of this
572 // framework.
573 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
574 FoundFramework = true;
575 break;
576 }
Ben Langmuiref914b82014-05-15 16:20:33 +0000577
578 // Get the parent directory name.
579 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
580 if (FrameworkPath.empty())
581 break;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000582 } while (true);
583
Richard Smith3d5b48c2015-10-16 21:42:56 +0000584 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000585 if (FoundFramework) {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000586 if (!HS.findUsableModuleForFrameworkHeader(
587 FE, FrameworkPath, RequestingModule, SuggestedModule, IsSystem))
588 return nullptr;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000589 } else {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000590 if (!HS.findUsableModuleForHeader(FE, getDir(), RequestingModule,
591 SuggestedModule, IsSystem))
592 return nullptr;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000593 }
594 }
Douglas Gregor97eec242011-09-15 22:00:41 +0000595 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000596}
597
Douglas Gregor89929282012-01-30 06:01:29 +0000598void HeaderSearch::setTarget(const TargetInfo &Target) {
599 ModMap.setTarget(Target);
600}
601
Chris Lattner712e3872007-12-17 08:13:48 +0000602//===----------------------------------------------------------------------===//
603// Header File Location.
604//===----------------------------------------------------------------------===//
605
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000606/// Return true with a diagnostic if the file that MSVC would have found
Reid Klecknera97d4c02014-02-18 23:49:24 +0000607/// fails to match the one that Clang would have found with MSVC header search
608/// disabled.
609static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
610 const FileEntry *MSFE, const FileEntry *FE,
611 SourceLocation IncludeLoc) {
612 if (MSFE && FE != MSFE) {
613 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
614 return true;
615 }
616 return false;
617}
Chris Lattner712e3872007-12-17 08:13:48 +0000618
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000619static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
620 assert(!Str.empty());
621 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
622 std::copy(Str.begin(), Str.end(), CopyStr);
623 CopyStr[Str.size()] = '\0';
624 return CopyStr;
625}
626
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000627static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader,
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000628 SmallVectorImpl<char> &FrameworkName) {
629 using namespace llvm::sys;
630 path::const_iterator I = path::begin(Path);
631 path::const_iterator E = path::end(Path);
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000632 IsPrivateHeader = false;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000633
634 // Detect different types of framework style paths:
635 //
636 // ...Foo.framework/{Headers,PrivateHeaders}
637 // ...Foo.framework/Versions/{A,Current}/{Headers,PrivateHeaders}
638 // ...Foo.framework/Frameworks/Nested.framework/{Headers,PrivateHeaders}
639 // ...<other variations with 'Versions' like in the above path>
640 //
641 // and some other variations among these lines.
642 int FoundComp = 0;
643 while (I != E) {
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000644 if (*I == "Headers")
645 ++FoundComp;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000646 if (I->endswith(".framework")) {
647 FrameworkName.append(I->begin(), I->end());
648 ++FoundComp;
649 }
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000650 if (*I == "PrivateHeaders") {
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000651 ++FoundComp;
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000652 IsPrivateHeader = true;
653 }
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000654 ++I;
655 }
656
657 return FoundComp >= 2;
658}
659
660static void
661diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc,
662 StringRef Includer, StringRef IncludeFilename,
663 const FileEntry *IncludeFE, bool isAngled = false,
664 bool FoundByHeaderMap = false) {
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000665 bool IsIncluderPrivateHeader = false;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000666 SmallString<128> FromFramework, ToFramework;
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000667 if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework))
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000668 return;
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000669 bool IsIncludeePrivateHeader = false;
670 bool IsIncludeeInFramework = isFrameworkStylePath(
671 IncludeFE->getName(), IsIncludeePrivateHeader, ToFramework);
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000672
673 if (!isAngled && !FoundByHeaderMap) {
674 SmallString<128> NewInclude("<");
675 if (IsIncludeeInFramework) {
676 NewInclude += StringRef(ToFramework).drop_back(10); // drop .framework
677 NewInclude += "/";
678 }
679 NewInclude += IncludeFilename;
680 NewInclude += ">";
681 Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header)
682 << IncludeFilename
683 << FixItHint::CreateReplacement(IncludeLoc, NewInclude);
684 }
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000685
686 // Headers in Foo.framework/Headers should not include headers
687 // from Foo.framework/PrivateHeaders, since this violates public/private
688 // API boundaries and can cause modular dependency cycles.
689 if (!IsIncluderPrivateHeader && IsIncludeeInFramework &&
690 IsIncludeePrivateHeader && FromFramework == ToFramework)
691 Diags.Report(IncludeLoc, diag::warn_framework_include_private_from_public)
692 << IncludeFilename;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000693}
694
James Dennettc07ab2c2012-06-20 00:56:32 +0000695/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000696/// return null on failure. isAngled indicates whether the file reference is
Will Wilson0fafd342013-12-27 19:46:16 +0000697/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
698/// non-empty, indicates where the \#including file(s) are, in case a relative
699/// search is needed. Microsoft mode will pass all \#including files.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000700const FileEntry *HeaderSearch::LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000701 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
702 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000703 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
704 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000705 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000706 bool *IsMapped, bool SkipCache, bool BuildSystemModule) {
707 if (IsMapped)
708 *IsMapped = false;
709
Douglas Gregor97eec242011-09-15 22:00:41 +0000710 if (SuggestedModule)
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000711 *SuggestedModule = ModuleMap::KnownHeader();
Douglas Gregor97eec242011-09-15 22:00:41 +0000712
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000713 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000714 if (llvm::sys::path::is_absolute(Filename)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000715 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000716
717 // If this was an #include_next "/absolute/file", fail.
Craig Topperd2d442c2014-05-17 23:10:59 +0000718 if (FromDir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000719
Craig Topperd2d442c2014-05-17 23:10:59 +0000720 if (SearchPath)
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000721 SearchPath->clear();
Craig Topperd2d442c2014-05-17 23:10:59 +0000722 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000723 RelativePath->clear();
724 RelativePath->append(Filename.begin(), Filename.end());
725 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000726 // Otherwise, just return the file.
Taewook Ohf42103c2016-06-13 20:40:21 +0000727 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000728 /*IsSystemHeaderDir*/false,
729 RequestingModule, SuggestedModule);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000730 }
Mike Stump11289f42009-09-09 15:08:12 +0000731
Reid Klecknera97d4c02014-02-18 23:49:24 +0000732 // This is the header that MSVC's header search would have found.
Craig Topperd2d442c2014-05-17 23:10:59 +0000733 const FileEntry *MSFE = nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000734 ModuleMap::KnownHeader MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000735
Douglas Gregor9f93e382011-07-28 04:45:53 +0000736 // Unless disabled, check to see if the file is in the #includer's
Will Wilson0fafd342013-12-27 19:46:16 +0000737 // directory. This cannot be based on CurDir, because each includer could be
738 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
739 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerf62f7582007-12-17 07:52:39 +0000740 // This search is not done for <> headers.
Will Wilson0fafd342013-12-27 19:46:16 +0000741 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
NAKAMURA Takumi9cb62642013-12-10 02:36:28 +0000742 SmallString<1024> TmpDir;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000743 bool First = true;
744 for (const auto &IncluderAndDir : Includers) {
745 const FileEntry *Includer = IncluderAndDir.first;
746
Will Wilson0fafd342013-12-27 19:46:16 +0000747 // Concatenate the requested file onto the directory.
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000748 // FIXME: Portability. Filename concatenation should be in sys::Path.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000749 TmpDir = IncluderAndDir.second->getName();
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000750 TmpDir.push_back('/');
751 TmpDir.append(Filename.begin(), Filename.end());
Richard Smith8c71eba2014-03-05 20:51:45 +0000752
Richard Smith6f548ec2014-03-06 18:08:08 +0000753 // FIXME: We don't cache the result of getFileInfo across the call to
754 // getFileAndSuggestModule, because it's a reference to an element of
755 // a container that could be reallocated across this call.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000756 //
Manman Rene4a5d372016-05-17 02:15:12 +0000757 // If we have no includer, that means we're processing a #include
Richard Smith3c1a41a2014-12-02 00:08:08 +0000758 // from a module build. We should treat this as a system header if we're
759 // building a [system] module.
Richard Smith6f548ec2014-03-06 18:08:08 +0000760 bool IncluderIsSystemHeader =
Manman Rene39c8142016-05-17 18:04:38 +0000761 Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
762 BuildSystemModule;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000763 if (const FileEntry *FE = getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000764 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000765 RequestingModule, SuggestedModule)) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000766 if (!Includer) {
767 assert(First && "only first includer can have no file");
768 return FE;
769 }
770
Will Wilson0fafd342013-12-27 19:46:16 +0000771 // Leave CurDir unset.
772 // This file is a system header or C++ unfriendly if the old file is.
773 //
774 // Note that we only use one of FromHFI/ToHFI at once, due to potential
775 // reallocation of the underlying vector potentially making the first
776 // reference binding dangling.
Richard Smith6f548ec2014-03-06 18:08:08 +0000777 HeaderFileInfo &FromHFI = getFileInfo(Includer);
Will Wilson0fafd342013-12-27 19:46:16 +0000778 unsigned DirInfo = FromHFI.DirInfo;
779 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
780 StringRef Framework = FromHFI.Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000781
Will Wilson0fafd342013-12-27 19:46:16 +0000782 HeaderFileInfo &ToHFI = getFileInfo(FE);
783 ToHFI.DirInfo = DirInfo;
784 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
785 ToHFI.Framework = Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000786
Craig Topperd2d442c2014-05-17 23:10:59 +0000787 if (SearchPath) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000788 StringRef SearchPathRef(IncluderAndDir.second->getName());
Will Wilson0fafd342013-12-27 19:46:16 +0000789 SearchPath->clear();
790 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
791 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000792 if (RelativePath) {
Will Wilson0fafd342013-12-27 19:46:16 +0000793 RelativePath->clear();
794 RelativePath->append(Filename.begin(), Filename.end());
795 }
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000796 if (First) {
797 diagnoseFrameworkInclude(Diags, IncludeLoc,
798 IncluderAndDir.second->getName(), Filename,
799 FE);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000800 return FE;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000801 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000802
803 // Otherwise, we found the path via MSVC header search rules. If
804 // -Wmsvc-include is enabled, we have to keep searching to see if we
805 // would've found this header in -I or -isystem directories.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000806 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
Reid Klecknera97d4c02014-02-18 23:49:24 +0000807 return FE;
808 } else {
809 MSFE = FE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000810 if (SuggestedModule) {
811 MSSuggestedModule = *SuggestedModule;
812 *SuggestedModule = ModuleMap::KnownHeader();
813 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000814 break;
815 }
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000816 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000817 First = false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000818 }
819 }
Mike Stump11289f42009-09-09 15:08:12 +0000820
Craig Topperd2d442c2014-05-17 23:10:59 +0000821 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000822
823 // If this is a system #include, ignore the user #include locs.
Nico Weber3b1d1212011-05-24 04:31:14 +0000824 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000825
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000826 // If this is a #include_next request, start searching after the directory the
827 // file was found in.
828 if (FromDir)
829 i = FromDir-&SearchDirs[0];
Mike Stump11289f42009-09-09 15:08:12 +0000830
Chris Lattnerd4275422007-07-22 07:28:00 +0000831 // Cache all of the lookups performed by this method. Many headers are
832 // multiply included, and the "pragma once" optimization prevents them from
833 // being relex/pp'd, but they would still have to search through a
834 // (potentially huge) series of SearchDirs to find it.
David Blaikie13156b62014-11-19 03:06:06 +0000835 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
Chris Lattnerd4275422007-07-22 07:28:00 +0000836
837 // If the entry has been previously looked up, the first value will be
838 // non-zero. If the value is equal to i (the start point of our search), then
839 // this is a matching hit.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000840 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattnerd4275422007-07-22 07:28:00 +0000841 // Skip querying potentially lots of directories for this lookup.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000842 i = CacheLookup.HitIdx;
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000843 if (CacheLookup.MappedName) {
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000844 Filename = CacheLookup.MappedName;
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000845 if (IsMapped)
846 *IsMapped = true;
847 }
Chris Lattnerd4275422007-07-22 07:28:00 +0000848 } else {
849 // Otherwise, this is the first query, or the previous query didn't match
850 // our search start. We will fill in our found location below, so prime the
851 // start point value.
Argyrios Kyrtzidis7bd78a92014-03-29 03:22:54 +0000852 CacheLookup.reset(/*StartIdx=*/i+1);
Chris Lattnerd4275422007-07-22 07:28:00 +0000853 }
Mike Stump11289f42009-09-09 15:08:12 +0000854
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000855 SmallString<64> MappedName;
856
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000857 // Check each directory in sequence to see if it contains this file.
858 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000859 bool InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000860 bool HasBeenMapped = false;
Richard Smith3d5b48c2015-10-16 21:42:56 +0000861 const FileEntry *FE = SearchDirs[i].LookupFile(
Taewook Ohf42103c2016-06-13 20:40:21 +0000862 Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000863 SuggestedModule, InUserSpecifiedSystemFramework, HasBeenMapped,
864 MappedName);
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000865 if (HasBeenMapped) {
866 CacheLookup.MappedName =
867 copyString(Filename, LookupFileCache.getAllocator());
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000868 if (IsMapped)
869 *IsMapped = true;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000870 }
Chris Lattner712e3872007-12-17 08:13:48 +0000871 if (!FE) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000872
Chris Lattner712e3872007-12-17 08:13:48 +0000873 CurDir = &SearchDirs[i];
Mike Stump11289f42009-09-09 15:08:12 +0000874
Chris Lattner712e3872007-12-17 08:13:48 +0000875 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor9f93e382011-07-28 04:45:53 +0000876 HeaderFileInfo &HFI = getFileInfo(FE);
877 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000878
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000879 // If the directory characteristic is User but this framework was
880 // user-specified to be treated as a system framework, promote the
881 // characteristic.
882 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
883 HFI.DirInfo = SrcMgr::C_System;
884
Richard Smith8acadcb2012-06-13 20:27:03 +0000885 // If the filename matches a known system header prefix, override
886 // whether the file is a system header.
Richard Trieu871f5f32012-06-13 20:52:36 +0000887 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
888 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
889 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smith8acadcb2012-06-13 20:27:03 +0000890 : SrcMgr::C_User;
891 break;
892 }
893 }
894
Douglas Gregor9f93e382011-07-28 04:45:53 +0000895 // If this file is found in a header map and uses the framework style of
896 // includes, then this header is part of a framework we're building.
897 if (CurDir->isIndexHeaderMap()) {
898 size_t SlashPos = Filename.find('/');
899 if (SlashPos != StringRef::npos) {
900 HFI.IndexHeaderMapHeader = 1;
901 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
902 SlashPos));
903 }
904 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000905
Richard Smith8c71eba2014-03-05 20:51:45 +0000906 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
907 if (SuggestedModule)
908 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000909 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000910 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000911
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000912 bool FoundByHeaderMap = !IsMapped ? false : *IsMapped;
913 if (!Includers.empty())
914 diagnoseFrameworkInclude(Diags, IncludeLoc,
915 Includers.front().second->getName(), Filename,
916 FE, isAngled, FoundByHeaderMap);
917
Chris Lattner712e3872007-12-17 08:13:48 +0000918 // Remember this location for the next lookup we do.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000919 CacheLookup.HitIdx = i;
Chris Lattner712e3872007-12-17 08:13:48 +0000920 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000921 }
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregord8575e12011-07-30 06:28:34 +0000923 // If we are including a file with a quoted include "foo.h" from inside
924 // a header in a framework that is currently being built, and we couldn't
925 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
926 // "Foo" is the name of the framework in which the including header was found.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000927 if (!Includers.empty() && Includers.front().first && !isAngled &&
Will Wilson0fafd342013-12-27 19:46:16 +0000928 Filename.find('/') == StringRef::npos) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000929 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
Douglas Gregord8575e12011-07-30 06:28:34 +0000930 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000931 SmallString<128> ScratchFilename;
Douglas Gregord8575e12011-07-30 06:28:34 +0000932 ScratchFilename += IncludingHFI.Framework;
933 ScratchFilename += '/';
934 ScratchFilename += Filename;
Will Wilson0fafd342013-12-27 19:46:16 +0000935
Richard Smith3d5b48c2015-10-16 21:42:56 +0000936 const FileEntry *FE =
937 LookupFile(ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir,
938 CurDir, Includers.front(), SearchPath, RelativePath,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000939 RequestingModule, SuggestedModule, IsMapped);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000940
Richard Smith8c71eba2014-03-05 20:51:45 +0000941 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
942 if (SuggestedModule)
943 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000944 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000945 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000946
David Blaikie3c8c46e2014-11-19 05:48:40 +0000947 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
David Blaikie13156b62014-11-19 03:06:06 +0000948 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
Richard Smith8c71eba2014-03-05 20:51:45 +0000949 // FIXME: SuggestedModule.
Reid Klecknera97d4c02014-02-18 23:49:24 +0000950 return FE;
Douglas Gregord8575e12011-07-30 06:28:34 +0000951 }
952 }
953
Craig Topperd2d442c2014-05-17 23:10:59 +0000954 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000955 if (SuggestedModule)
956 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000957 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000958 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000959
Chris Lattnerd4275422007-07-22 07:28:00 +0000960 // Otherwise, didn't find it. Remember we didn't find this.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000961 CacheLookup.HitIdx = SearchDirs.size();
Craig Topperd2d442c2014-05-17 23:10:59 +0000962 return nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000963}
964
Chris Lattner63dd32b2006-10-20 04:42:40 +0000965/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennettc07ab2c2012-06-20 00:56:32 +0000966/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Chris Lattner63dd32b2006-10-20 04:42:40 +0000967/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
968/// is a subframework within Carbon.framework. If so, return the FileEntry
969/// for the designated file, otherwise return null.
970const FileEntry *HeaderSearch::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000971LookupSubframeworkHeader(StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000972 const FileEntry *ContextFileEnt,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000973 SmallVectorImpl<char> *SearchPath,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000974 SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000975 Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000976 ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner12261882008-02-01 05:34:02 +0000977 assert(ContextFileEnt && "No context file?");
Mike Stump11289f42009-09-09 15:08:12 +0000978
Chris Lattner63dd32b2006-10-20 04:42:40 +0000979 // Framework names must have a '/' in the filename. Find it.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000980 // FIXME: Should we permit '\' on Windows?
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000981 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000982 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000983
Chris Lattner63dd32b2006-10-20 04:42:40 +0000984 // Look up the base framework name of the ContextFileEnt.
Mehdi Amini004b9c72016-10-10 22:52:47 +0000985 StringRef ContextName = ContextFileEnt->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000986
Chris Lattner63dd32b2006-10-20 04:42:40 +0000987 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000988 const unsigned DotFrameworkLen = 10;
Mehdi Amini004b9c72016-10-10 22:52:47 +0000989 auto FrameworkPos = ContextName.find(".framework");
990 if (FrameworkPos == StringRef::npos ||
991 (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
992 ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
Craig Topperd2d442c2014-05-17 23:10:59 +0000993 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000994
Mehdi Amini004b9c72016-10-10 22:52:47 +0000995 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
996 FrameworkPos +
997 DotFrameworkLen + 1);
Chris Lattner5ed76da2006-10-22 07:24:13 +0000998
Chris Lattner63dd32b2006-10-20 04:42:40 +0000999 // Append Frameworks/HIToolbox.framework/
1000 FrameworkName += "Frameworks/";
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001001 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Chris Lattner63dd32b2006-10-20 04:42:40 +00001002 FrameworkName += ".framework/";
Chris Lattner577377e2006-10-20 04:55:45 +00001003
David Blaikie13156b62014-11-19 03:06:06 +00001004 auto &CacheLookup =
1005 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
1006 FrameworkCacheEntry())).first;
Mike Stump11289f42009-09-09 15:08:12 +00001007
Chris Lattner5ed76da2006-10-22 07:24:13 +00001008 // Some other location?
David Blaikie13156b62014-11-19 03:06:06 +00001009 if (CacheLookup.second.Directory &&
1010 CacheLookup.first().size() == FrameworkName.size() &&
1011 memcmp(CacheLookup.first().data(), &FrameworkName[0],
1012 CacheLookup.first().size()) != 0)
Craig Topperd2d442c2014-05-17 23:10:59 +00001013 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001014
Chris Lattner5ed76da2006-10-22 07:24:13 +00001015 // Cache subframework.
David Blaikie13156b62014-11-19 03:06:06 +00001016 if (!CacheLookup.second.Directory) {
Chris Lattner5ed76da2006-10-22 07:24:13 +00001017 ++NumSubFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +00001018
Chris Lattner5ed76da2006-10-22 07:24:13 +00001019 // If the framework dir doesn't exist, we fail.
Yaron Keren92e1b622015-03-18 10:17:07 +00001020 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +00001021 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001022
Chris Lattner5ed76da2006-10-22 07:24:13 +00001023 // Otherwise, if it does, remember that this is the right direntry for this
1024 // framework.
David Blaikie13156b62014-11-19 03:06:06 +00001025 CacheLookup.second.Directory = Dir;
Chris Lattner5ed76da2006-10-22 07:24:13 +00001026 }
Mike Stump11289f42009-09-09 15:08:12 +00001027
Craig Topperd2d442c2014-05-17 23:10:59 +00001028 const FileEntry *FE = nullptr;
Chris Lattner577377e2006-10-20 04:55:45 +00001029
Craig Topperd2d442c2014-05-17 23:10:59 +00001030 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001031 RelativePath->clear();
1032 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
1033 }
1034
Chris Lattner63dd32b2006-10-20 04:42:40 +00001035 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001036 SmallString<1024> HeadersFilename(FrameworkName);
Chris Lattner43fd42e2006-10-30 03:40:58 +00001037 HeadersFilename += "Headers/";
Craig Topperd2d442c2014-05-17 23:10:59 +00001038 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001039 SearchPath->clear();
1040 // Without trailing '/'.
1041 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1042 }
1043
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001044 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +00001045 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
Chris Lattner63dd32b2006-10-20 04:42:40 +00001046 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +00001047 HeadersFilename = FrameworkName;
1048 HeadersFilename += "PrivateHeaders/";
Craig Topperd2d442c2014-05-17 23:10:59 +00001049 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001050 SearchPath->clear();
1051 // Without trailing '/'.
1052 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1053 }
1054
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001055 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +00001056 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
Craig Topperd2d442c2014-05-17 23:10:59 +00001057 return nullptr;
Chris Lattner63dd32b2006-10-20 04:42:40 +00001058 }
Mike Stump11289f42009-09-09 15:08:12 +00001059
Chris Lattner577377e2006-10-20 04:55:45 +00001060 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenek72be0682008-02-24 03:55:14 +00001061 //
Chris Lattnerf5c619f2008-02-25 21:38:21 +00001062 // Note that the temporary 'DirInfo' is required here, as either call to
1063 // getFileInfo could resize the vector and we don't want to rely on order
1064 // of evaluation.
1065 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
1066 getFileInfo(FE).DirInfo = DirInfo;
Douglas Gregorf5f94522013-02-08 00:10:48 +00001067
Richard Smith3d5b48c2015-10-16 21:42:56 +00001068 FrameworkName.pop_back(); // remove the trailing '/'
1069 if (!findUsableModuleForFrameworkHeader(FE, FrameworkName, RequestingModule,
1070 SuggestedModule, /*IsSystem*/ false))
1071 return nullptr;
Douglas Gregorf5f94522013-02-08 00:10:48 +00001072
Chris Lattner577377e2006-10-20 04:55:45 +00001073 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +00001074}
1075
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001076//===----------------------------------------------------------------------===//
1077// File Info Management.
1078//===----------------------------------------------------------------------===//
1079
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001080/// Merge the header file info provided by \p OtherHFI into the current
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001081/// header file info (\p HFI)
1082static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
1083 const HeaderFileInfo &OtherHFI) {
Richard Smithd8879c82015-08-24 21:59:32 +00001084 assert(OtherHFI.External && "expected to merge external HFI");
1085
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001086 HFI.isImport |= OtherHFI.isImport;
1087 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001088 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001089 HFI.NumIncludes += OtherHFI.NumIncludes;
Richard Smithd8879c82015-08-24 21:59:32 +00001090
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001091 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
1092 HFI.ControllingMacro = OtherHFI.ControllingMacro;
1093 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
1094 }
Richard Smithd8879c82015-08-24 21:59:32 +00001095
1096 HFI.DirInfo = OtherHFI.DirInfo;
1097 HFI.External = (!HFI.IsValid || HFI.External);
1098 HFI.IsValid = true;
1099 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001100
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001101 if (HFI.Framework.empty())
1102 HFI.Framework = OtherHFI.Framework;
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001103}
1104
Steve Naroff3fa455a2009-04-24 20:03:17 +00001105/// getFileInfo - Return the HeaderFileInfo structure for the specified
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001106/// FileEntry.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001107HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001108 if (FE->getUID() >= FileInfo.size())
Richard Smith386bb072015-08-18 23:42:23 +00001109 FileInfo.resize(FE->getUID() + 1);
1110
Richard Smithd8879c82015-08-24 21:59:32 +00001111 HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
Richard Smith386bb072015-08-18 23:42:23 +00001112 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +00001113 if (ExternalSource && !HFI->Resolved) {
1114 HFI->Resolved = true;
1115 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1116
1117 HFI = &FileInfo[FE->getUID()];
1118 if (ExternalHFI.External)
1119 mergeHeaderFileInfo(*HFI, ExternalHFI);
Richard Smith386bb072015-08-18 23:42:23 +00001120 }
1121
Richard Smithd8879c82015-08-24 21:59:32 +00001122 HFI->IsValid = true;
Richard Smith386bb072015-08-18 23:42:23 +00001123 // We have local information about this header file, so it's no longer
1124 // strictly external.
Richard Smithd8879c82015-08-24 21:59:32 +00001125 HFI->External = false;
1126 return *HFI;
Mike Stump11289f42009-09-09 15:08:12 +00001127}
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001128
Richard Smith386bb072015-08-18 23:42:23 +00001129const HeaderFileInfo *
Richard Smithd8879c82015-08-24 21:59:32 +00001130HeaderSearch::getExistingFileInfo(const FileEntry *FE,
1131 bool WantExternal) const {
Richard Smith386bb072015-08-18 23:42:23 +00001132 // If we have an external source, ensure we have the latest information.
1133 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +00001134 HeaderFileInfo *HFI;
1135 if (ExternalSource) {
1136 if (FE->getUID() >= FileInfo.size()) {
1137 if (!WantExternal)
1138 return nullptr;
1139 FileInfo.resize(FE->getUID() + 1);
Richard Smith386bb072015-08-18 23:42:23 +00001140 }
Richard Smithd8879c82015-08-24 21:59:32 +00001141
1142 HFI = &FileInfo[FE->getUID()];
1143 if (!WantExternal && (!HFI->IsValid || HFI->External))
1144 return nullptr;
1145 if (!HFI->Resolved) {
1146 HFI->Resolved = true;
1147 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1148
1149 HFI = &FileInfo[FE->getUID()];
1150 if (ExternalHFI.External)
1151 mergeHeaderFileInfo(*HFI, ExternalHFI);
1152 }
1153 } else if (FE->getUID() >= FileInfo.size()) {
1154 return nullptr;
1155 } else {
1156 HFI = &FileInfo[FE->getUID()];
Ben Langmuird285c502014-03-13 16:46:36 +00001157 }
Richard Smith386bb072015-08-18 23:42:23 +00001158
Richard Smithd8879c82015-08-24 21:59:32 +00001159 if (!HFI->IsValid || (HFI->External && !WantExternal))
Richard Smith386bb072015-08-18 23:42:23 +00001160 return nullptr;
1161
Richard Smithd8879c82015-08-24 21:59:32 +00001162 return HFI;
Ben Langmuird285c502014-03-13 16:46:36 +00001163}
1164
Douglas Gregor37aa4932011-05-04 00:14:37 +00001165bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1166 // Check if we've ever seen this file as a header.
Richard Smith386bb072015-08-18 23:42:23 +00001167 if (auto *HFI = getExistingFileInfo(File))
1168 return HFI->isPragmaOnce || HFI->isImport || HFI->ControllingMacro ||
1169 HFI->ControllingMacroID;
1170 return false;
Douglas Gregor37aa4932011-05-04 00:14:37 +00001171}
1172
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001173void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001174 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001175 bool isCompilingModuleHeader) {
Richard Smithd8879c82015-08-24 21:59:32 +00001176 bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1177
1178 // Don't mark the file info as non-external if there's nothing to change.
1179 if (!isCompilingModuleHeader) {
1180 if (!isModularHeader)
1181 return;
1182 auto *HFI = getExistingFileInfo(FE);
1183 if (HFI && HFI->isModuleHeader)
1184 return;
1185 }
1186
Richard Smith386bb072015-08-18 23:42:23 +00001187 auto &HFI = getFileInfo(FE);
Richard Smithd8879c82015-08-24 21:59:32 +00001188 HFI.isModuleHeader |= isModularHeader;
Richard Smithe70dadd2015-07-10 22:27:17 +00001189 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001190}
1191
Richard Smith20e883e2015-04-29 23:20:19 +00001192bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001193 const FileEntry *File, bool isImport,
1194 bool ModulesEnabled, Module *M) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001195 ++NumIncluded; // Count # of attempted #includes.
1196
1197 // Get information about this file.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001198 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump11289f42009-09-09 15:08:12 +00001199
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001200 // FIXME: this is a workaround for the lack of proper modules-aware support
1201 // for #import / #pragma once
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +00001202 auto TryEnterImported = [&]() -> bool {
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001203 if (!ModulesEnabled)
1204 return false;
Richard Smith040e1262017-06-02 01:55:39 +00001205 // Ensure FileInfo bits are up to date.
1206 ModMap.resolveHeaderDirectives(File);
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001207 // Modules with builtins are special; multiple modules use builtins as
1208 // modular headers, example:
1209 //
1210 // module stddef { header "stddef.h" export * }
1211 //
1212 // After module map parsing, this expands to:
1213 //
1214 // module stddef {
1215 // header "/path_to_builtin_dirs/stddef.h"
1216 // textual "stddef.h"
1217 // }
1218 //
1219 // It's common that libc++ and system modules will both define such
1220 // submodules. Make sure cached results for a builtin header won't
1221 // prevent other builtin modules to potentially enter the builtin header.
1222 // Note that builtins are header guarded and the decision to actually
1223 // enter them is postponed to the controlling macros logic below.
1224 bool TryEnterHdr = false;
1225 if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
1226 TryEnterHdr = File->getDir() == ModMap.getBuiltinDir() &&
1227 ModuleMap::isBuiltinHeader(
1228 llvm::sys::path::filename(File->getName()));
1229
1230 // Textual headers can be #imported from different modules. Since ObjC
1231 // headers find in the wild might rely only on #import and do not contain
1232 // controlling macros, be conservative and only try to enter textual headers
1233 // if such macro is present.
Bruno Cardoso Lopes4164dd92017-08-12 01:38:26 +00001234 if (!FileInfo.isModuleHeader &&
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001235 FileInfo.getControllingMacro(ExternalLookup))
1236 TryEnterHdr = true;
1237 return TryEnterHdr;
1238 };
1239
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001240 // If this is a #import directive, check that we have not already imported
1241 // this header.
1242 if (isImport) {
1243 // If this has already been imported, don't import it again.
1244 FileInfo.isImport = true;
Mike Stump11289f42009-09-09 15:08:12 +00001245
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001246 // Has this already been #import'ed or #include'd?
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001247 if (FileInfo.NumIncludes && !TryEnterImported())
1248 return false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001249 } else {
1250 // Otherwise, if this is a #include of a file that was previously #import'd
1251 // or if this is the second #include of a #pragma once file, ignore it.
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001252 if (FileInfo.isImport && !TryEnterImported())
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001253 return false;
1254 }
Mike Stump11289f42009-09-09 15:08:12 +00001255
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001256 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1257 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump11289f42009-09-09 15:08:12 +00001258 if (const IdentifierInfo *ControllingMacro
Richard Smithe70dadd2015-07-10 22:27:17 +00001259 = FileInfo.getControllingMacro(ExternalLookup)) {
1260 // If the header corresponds to a module, check whether the macro is already
1261 // defined in that module rather than checking in the current set of visible
1262 // modules.
1263 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1264 : PP.isMacroDefined(ControllingMacro)) {
Douglas Gregor99734e72009-04-25 23:30:02 +00001265 ++NumMultiIncludeFileOptzn;
1266 return false;
1267 }
Richard Smithe70dadd2015-07-10 22:27:17 +00001268 }
Mike Stump11289f42009-09-09 15:08:12 +00001269
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001270 // Increment the number of times this file has been included.
1271 ++FileInfo.NumIncludes;
Mike Stump11289f42009-09-09 15:08:12 +00001272
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001273 return true;
1274}
1275
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001276size_t HeaderSearch::getTotalMemory() const {
1277 return SearchDirs.capacity()
Ted Kremenekae63d102011-07-27 18:41:18 +00001278 + llvm::capacity_in_bytes(FileInfo)
1279 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001280 + LookupFileCache.getAllocator().getTotalMemory()
1281 + FrameworkMap.getAllocator().getTotalMemory();
1282}
Douglas Gregor9f93e382011-07-28 04:45:53 +00001283
1284StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
David Blaikie13156b62014-11-19 03:06:06 +00001285 return FrameworkNames.insert(Framework).first->first();
Douglas Gregor9f93e382011-07-28 04:45:53 +00001286}
Douglas Gregor718292f2011-11-11 19:10:28 +00001287
1288bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor963c5532013-06-21 16:28:10 +00001289 const DirectoryEntry *Root,
1290 bool IsSystem) {
Richard Smith47972af2015-06-16 00:08:24 +00001291 if (!HSOpts->ImplicitModuleMaps)
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +00001292 return false;
1293
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001294 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregor718292f2011-11-11 19:10:28 +00001295
1296 StringRef DirName = FileName;
1297 do {
1298 // Get the parent directory name.
1299 DirName = llvm::sys::path::parent_path(DirName);
1300 if (DirName.empty())
1301 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001302
Douglas Gregor718292f2011-11-11 19:10:28 +00001303 // Determine whether this directory exists.
1304 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1305 if (!Dir)
1306 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001307
Ben Langmuir984e1df2014-03-19 20:23:34 +00001308 // Try to load the module map file in this directory.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001309 switch (loadModuleMapFile(Dir, IsSystem,
1310 llvm::sys::path::extension(Dir->getName()) ==
1311 ".framework")) {
Douglas Gregor80b69042011-11-12 00:22:19 +00001312 case LMM_NewlyLoaded:
1313 case LMM_AlreadyLoaded:
Daniel Jasperca9f7382013-09-24 09:27:13 +00001314 // Success. All of the directories we stepped through inherit this module
1315 // map file.
1316 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1317 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1318 return true;
Daniel Jasper97da9172013-10-22 08:09:47 +00001319
1320 case LMM_NoDirectory:
1321 case LMM_InvalidModuleMap:
1322 break;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001323 }
1324
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001325 // If we hit the top of our search, we're done.
1326 if (Dir == Root)
1327 return false;
1328
Douglas Gregor718292f2011-11-11 19:10:28 +00001329 // Keep track of all of the directories we checked, so we can mark them as
1330 // having module maps if we eventually do find a module map.
1331 FixUpDirectories.push_back(Dir);
1332 } while (true);
Douglas Gregor718292f2011-11-11 19:10:28 +00001333}
1334
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001335ModuleMap::KnownHeader
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001336HeaderSearch::findModuleForHeader(const FileEntry *File,
1337 bool AllowTextual) const {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001338 if (ExternalSource) {
1339 // Make sure the external source has handled header info about this file,
1340 // which includes whether the file is part of a module.
Richard Smith386bb072015-08-18 23:42:23 +00001341 (void)getExistingFileInfo(File);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001342 }
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001343 return ModMap.findModuleForHeader(File, AllowTextual);
1344}
1345
1346static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1347 Module *RequestingModule,
1348 ModuleMap::KnownHeader *SuggestedModule) {
1349 ModuleMap::KnownHeader Module =
1350 HS.findModuleForHeader(File, /*AllowTextual*/true);
1351 if (SuggestedModule)
1352 *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1353 ? ModuleMap::KnownHeader()
1354 : Module;
1355
1356 // If this module specifies [no_undeclared_includes], we cannot find any
1357 // file that's in a non-dependency module.
1358 if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1359 HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/false);
1360 if (!RequestingModule->directlyUses(Module.getModule())) {
1361 return false;
1362 }
1363 }
1364
1365 return true;
Douglas Gregor718292f2011-11-11 19:10:28 +00001366}
1367
Richard Smith3d5b48c2015-10-16 21:42:56 +00001368bool HeaderSearch::findUsableModuleForHeader(
1369 const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1370 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001371 if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
Richard Smith3d5b48c2015-10-16 21:42:56 +00001372 // If there is a module that corresponds to this header, suggest it.
1373 hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001374 return suggestModule(*this, File, RequestingModule, SuggestedModule);
Richard Smith3d5b48c2015-10-16 21:42:56 +00001375 }
1376 return true;
1377}
1378
1379bool HeaderSearch::findUsableModuleForFrameworkHeader(
1380 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1381 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1382 // If we're supposed to suggest a module, look for one now.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001383 if (needModuleLookup(RequestingModule, SuggestedModule)) {
Richard Smith3d5b48c2015-10-16 21:42:56 +00001384 // Find the top-level framework based on this framework.
1385 SmallVector<std::string, 4> SubmodulePath;
1386 const DirectoryEntry *TopFrameworkDir
1387 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1388
1389 // Determine the name of the top-level framework.
1390 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1391
1392 // Load this framework module. If that succeeds, find the suggested module
1393 // for this header, if any.
1394 loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1395
1396 // FIXME: This can find a module not part of ModuleName, which is
1397 // important so that we're consistent about whether this header
1398 // corresponds to a module. Possibly we should lock down framework modules
1399 // so that this is not possible.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001400 return suggestModule(*this, File, RequestingModule, SuggestedModule);
Richard Smith3d5b48c2015-10-16 21:42:56 +00001401 }
1402 return true;
1403}
1404
Richard Smith9acb99e32014-12-10 03:09:48 +00001405static const FileEntry *getPrivateModuleMap(const FileEntry *File,
Ben Langmuir984e1df2014-03-19 20:23:34 +00001406 FileManager &FileMgr) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001407 StringRef Filename = llvm::sys::path::filename(File->getName());
1408 SmallString<128> PrivateFilename(File->getDir()->getName());
Ben Langmuir984e1df2014-03-19 20:23:34 +00001409 if (Filename == "module.map")
Douglas Gregor80306772011-12-07 21:25:07 +00001410 llvm::sys::path::append(PrivateFilename, "module_private.map");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001411 else if (Filename == "module.modulemap")
1412 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1413 else
1414 return nullptr;
1415 return FileMgr.getFile(PrivateFilename);
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001416}
1417
Richard Smith8128f332017-05-05 22:18:51 +00001418bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
Richard Smith8b706102017-05-31 20:56:55 +00001419 FileID ID, unsigned *Offset,
1420 StringRef OriginalModuleMapFile) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001421 // Find the directory for the module. For frameworks, that may require going
1422 // up from the 'Modules' directory.
1423 const DirectoryEntry *Dir = nullptr;
1424 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1425 Dir = FileMgr.getDirectory(".");
1426 else {
Richard Smith8b706102017-05-31 20:56:55 +00001427 if (!OriginalModuleMapFile.empty()) {
1428 // We're building a preprocessed module map. Find or invent the directory
1429 // that it originally occupied.
1430 Dir = FileMgr.getDirectory(
1431 llvm::sys::path::parent_path(OriginalModuleMapFile));
1432 if (!Dir) {
1433 auto *FakeFile = FileMgr.getVirtualFile(OriginalModuleMapFile, 0, 0);
1434 Dir = FakeFile->getDir();
1435 }
1436 } else {
1437 Dir = File->getDir();
1438 }
1439
Richard Smith9acb99e32014-12-10 03:09:48 +00001440 StringRef DirName(Dir->getName());
1441 if (llvm::sys::path::filename(DirName) == "Modules") {
1442 DirName = llvm::sys::path::parent_path(DirName);
1443 if (DirName.endswith(".framework"))
1444 Dir = FileMgr.getDirectory(DirName);
1445 // FIXME: This assert can fail if there's a race between the above check
1446 // and the removal of the directory.
1447 assert(Dir && "parent must exist");
1448 }
1449 }
1450
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001451 switch (loadModuleMapFileImpl(File, IsSystem, Dir, ID, Offset)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001452 case LMM_AlreadyLoaded:
1453 case LMM_NewlyLoaded:
1454 return false;
1455 case LMM_NoDirectory:
1456 case LMM_InvalidModuleMap:
1457 return true;
1458 }
Aaron Ballmand8de5b62014-03-20 14:22:33 +00001459 llvm_unreachable("Unknown load module map result");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001460}
1461
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001462HeaderSearch::LoadModuleMapResult
1463HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1464 const DirectoryEntry *Dir, FileID ID,
1465 unsigned *Offset) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001466 assert(File && "expected FileEntry");
1467
Richard Smith9887d792014-10-17 01:42:53 +00001468 // Check whether we've already loaded this module map, and mark it as being
1469 // loaded in case we recursively try to load it from itself.
1470 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1471 if (!AddResult.second)
1472 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001473
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001474 if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
Richard Smith9887d792014-10-17 01:42:53 +00001475 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001476 return LMM_InvalidModuleMap;
1477 }
1478
1479 // Try to load a corresponding private module map.
Richard Smith9acb99e32014-12-10 03:09:48 +00001480 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001481 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001482 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001483 return LMM_InvalidModuleMap;
1484 }
1485 }
1486
1487 // This directory has a module map.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001488 return LMM_NewlyLoaded;
1489}
1490
1491const FileEntry *
1492HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
Richard Smith47972af2015-06-16 00:08:24 +00001493 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001494 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001495 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1496 // module.map at the framework root is also accepted.
1497 SmallString<128> ModuleMapFileName(Dir->getName());
1498 if (IsFramework)
1499 llvm::sys::path::append(ModuleMapFileName, "Modules");
1500 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1501 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1502 return F;
1503
1504 // Continue to allow module.map
1505 ModuleMapFileName = Dir->getName();
1506 llvm::sys::path::append(ModuleMapFileName, "module.map");
1507 return FileMgr.getFile(ModuleMapFileName);
1508}
1509
1510Module *HeaderSearch::loadFrameworkModule(StringRef Name,
Douglas Gregor279a6c32012-01-29 17:08:11 +00001511 const DirectoryEntry *Dir,
1512 bool IsSystem) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00001513 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor56c64012011-11-17 01:41:17 +00001514 return Module;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001515
Douglas Gregor56c64012011-11-17 01:41:17 +00001516 // Try to load a module map file.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001517 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
Douglas Gregor56c64012011-11-17 01:41:17 +00001518 case LMM_InvalidModuleMap:
Ben Langmuira5254002015-07-02 13:19:48 +00001519 // Try to infer a module map from the framework directory.
1520 if (HSOpts->ImplicitModuleMaps)
1521 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
Douglas Gregor56c64012011-11-17 01:41:17 +00001522 break;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001523
Douglas Gregor56c64012011-11-17 01:41:17 +00001524 case LMM_AlreadyLoaded:
1525 case LMM_NoDirectory:
Craig Topperd2d442c2014-05-17 23:10:59 +00001526 return nullptr;
1527
Douglas Gregor56c64012011-11-17 01:41:17 +00001528 case LMM_NewlyLoaded:
Ben Langmuira5254002015-07-02 13:19:48 +00001529 break;
Douglas Gregor56c64012011-11-17 01:41:17 +00001530 }
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001531
Ben Langmuira5254002015-07-02 13:19:48 +00001532 return ModMap.findModule(Name);
Douglas Gregor56c64012011-11-17 01:41:17 +00001533}
1534
Douglas Gregor80b69042011-11-12 00:22:19 +00001535HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001536HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1537 bool IsFramework) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001538 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
Ben Langmuir984e1df2014-03-19 20:23:34 +00001539 return loadModuleMapFile(Dir, IsSystem, IsFramework);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001540
Douglas Gregor80b69042011-11-12 00:22:19 +00001541 return LMM_NoDirectory;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001542}
1543
Douglas Gregor80b69042011-11-12 00:22:19 +00001544HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001545HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1546 bool IsFramework) {
1547 auto KnownDir = DirectoryHasModuleMap.find(Dir);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001548 if (KnownDir != DirectoryHasModuleMap.end())
Richard Smith9887d792014-10-17 01:42:53 +00001549 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregore7ab3662011-12-07 02:23:45 +00001550
Ben Langmuir984e1df2014-03-19 20:23:34 +00001551 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001552 LoadModuleMapResult Result =
1553 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
Ben Langmuir984e1df2014-03-19 20:23:34 +00001554 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1555 // E.g. Foo.framework/Modules/module.modulemap
1556 // ^Dir ^ModuleMapFile
1557 if (Result == LMM_NewlyLoaded)
1558 DirectoryHasModuleMap[Dir] = true;
Richard Smith9887d792014-10-17 01:42:53 +00001559 else if (Result == LMM_InvalidModuleMap)
1560 DirectoryHasModuleMap[Dir] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001561 return Result;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001562 }
Douglas Gregor80b69042011-11-12 00:22:19 +00001563 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001564}
Douglas Gregor718292f2011-11-11 19:10:28 +00001565
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001566void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001567 Modules.clear();
Daniel Jasper21a0f552014-11-25 09:45:48 +00001568
Richard Smith47972af2015-06-16 00:08:24 +00001569 if (HSOpts->ImplicitModuleMaps) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001570 // Load module maps for each of the header search directories.
1571 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1572 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1573 if (SearchDirs[Idx].isFramework()) {
1574 std::error_code EC;
1575 SmallString<128> DirNative;
1576 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1577 DirNative);
1578
1579 // Search each of the ".framework" directories to load them as modules.
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001580 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1581 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001582 Dir != DirEnd && !EC; Dir.increment(EC)) {
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001583 if (llvm::sys::path::extension(Dir->getName()) != ".framework")
Daniel Jasper21a0f552014-11-25 09:45:48 +00001584 continue;
1585
1586 const DirectoryEntry *FrameworkDir =
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001587 FileMgr.getDirectory(Dir->getName());
Daniel Jasper21a0f552014-11-25 09:45:48 +00001588 if (!FrameworkDir)
1589 continue;
1590
1591 // Load this framework module.
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001592 loadFrameworkModule(llvm::sys::path::stem(Dir->getName()),
1593 FrameworkDir, IsSystem);
Daniel Jasper21a0f552014-11-25 09:45:48 +00001594 }
1595 continue;
Douglas Gregor07f43572012-01-29 18:15:03 +00001596 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001597
1598 // FIXME: Deal with header maps.
1599 if (SearchDirs[Idx].isHeaderMap())
1600 continue;
1601
1602 // Try to load a module map file for the search directory.
1603 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1604 /*IsFramework*/ false);
1605
1606 // Try to load module map files for immediate subdirectories of this
1607 // search directory.
1608 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor07f43572012-01-29 18:15:03 +00001609 }
Douglas Gregor07f43572012-01-29 18:15:03 +00001610 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001611
Douglas Gregor07f43572012-01-29 18:15:03 +00001612 // Populate the list of modules.
1613 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1614 MEnd = ModMap.module_end();
1615 M != MEnd; ++M) {
1616 Modules.push_back(M->getValue());
1617 }
1618}
Douglas Gregor0339a642013-03-21 01:08:50 +00001619
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001620void HeaderSearch::loadTopLevelSystemModules() {
Richard Smith47972af2015-06-16 00:08:24 +00001621 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001622 return;
1623
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001624 // Load module maps for each of the header search directories.
1625 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor299787f2013-11-01 23:08:38 +00001626 // We only care about normal header directories.
1627 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001628 continue;
1629 }
1630
1631 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001632 loadModuleMapFile(SearchDirs[Idx].getDir(),
Ben Langmuir984e1df2014-03-19 20:23:34 +00001633 SearchDirs[Idx].isSystemHeaderDirectory(),
1634 SearchDirs[Idx].isFramework());
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001635 }
1636}
1637
Douglas Gregor0339a642013-03-21 01:08:50 +00001638void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
Richard Smith47972af2015-06-16 00:08:24 +00001639 assert(HSOpts->ImplicitModuleMaps &&
Daniel Jasper21a0f552014-11-25 09:45:48 +00001640 "Should not be loading subdirectory module maps");
1641
Douglas Gregor0339a642013-03-21 01:08:50 +00001642 if (SearchDir.haveSearchedAllModuleMaps())
1643 return;
Rafael Espindolac0809172014-06-12 14:02:15 +00001644
1645 std::error_code EC;
Douglas Gregor0339a642013-03-21 01:08:50 +00001646 SmallString<128> DirNative;
1647 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001648 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1649 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Douglas Gregor0339a642013-03-21 01:08:50 +00001650 Dir != DirEnd && !EC; Dir.increment(EC)) {
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001651 bool IsFramework =
1652 llvm::sys::path::extension(Dir->getName()) == ".framework";
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001653 if (IsFramework == SearchDir.isFramework())
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001654 loadModuleMapFile(Dir->getName(), SearchDir.isSystemHeaderDirectory(),
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001655 SearchDir.isFramework());
Douglas Gregor0339a642013-03-21 01:08:50 +00001656 }
1657
1658 SearchDir.setSearchedAllModuleMaps(true);
1659}
Richard Smith4eb83932016-04-27 21:57:05 +00001660
1661std::string HeaderSearch::suggestPathToFileForDiagnostics(const FileEntry *File,
1662 bool *IsSystem) {
1663 // FIXME: We assume that the path name currently cached in the FileEntry is
Eric Liudffb1a82018-01-29 13:21:23 +00001664 // the most appropriate one for this analysis (and that it's spelled the
1665 // same way as the corresponding header search path).
1666 return suggestPathToFileForDiagnostics(File->getName(), /*BuildDir=*/"",
1667 IsSystem);
1668}
1669
1670std::string HeaderSearch::suggestPathToFileForDiagnostics(
1671 llvm::StringRef File, llvm::StringRef WorkingDir, bool *IsSystem) {
1672 using namespace llvm::sys;
Richard Smith4eb83932016-04-27 21:57:05 +00001673
1674 unsigned BestPrefixLength = 0;
1675 unsigned BestSearchDir;
1676
1677 for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1678 // FIXME: Support this search within frameworks and header maps.
1679 if (!SearchDirs[I].isNormalDir())
1680 continue;
1681
Mehdi Amini0df59d82016-10-11 07:31:29 +00001682 StringRef Dir = SearchDirs[I].getDir()->getName();
Eric Liudffb1a82018-01-29 13:21:23 +00001683 llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
1684 if (!WorkingDir.empty() && !path::is_absolute(Dir)) {
1685 auto err = fs::make_absolute(WorkingDir, DirPath);
1686 if (!err)
1687 path::remove_dots(DirPath, /*remove_dot_dot=*/true);
1688 Dir = DirPath;
1689 }
1690 for (auto NI = path::begin(File), NE = path::end(File),
1691 DI = path::begin(Dir), DE = path::end(Dir);
Richard Smith4eb83932016-04-27 21:57:05 +00001692 /*termination condition in loop*/; ++NI, ++DI) {
Eric Liudffb1a82018-01-29 13:21:23 +00001693 // '.' components in File are ignored.
Richard Smith4eb83932016-04-27 21:57:05 +00001694 while (NI != NE && *NI == ".")
1695 ++NI;
1696 if (NI == NE)
1697 break;
1698
1699 // '.' components in Dir are ignored.
1700 while (DI != DE && *DI == ".")
1701 ++DI;
1702 if (DI == DE) {
Eric Liudffb1a82018-01-29 13:21:23 +00001703 // Dir is a prefix of File, up to '.' components and choice of path
Richard Smith4eb83932016-04-27 21:57:05 +00001704 // separators.
Eric Liudffb1a82018-01-29 13:21:23 +00001705 unsigned PrefixLength = NI - path::begin(File);
Richard Smith4eb83932016-04-27 21:57:05 +00001706 if (PrefixLength > BestPrefixLength) {
1707 BestPrefixLength = PrefixLength;
1708 BestSearchDir = I;
1709 }
1710 break;
1711 }
1712
1713 if (*NI != *DI)
1714 break;
1715 }
1716 }
1717
1718 if (IsSystem)
1719 *IsSystem = BestPrefixLength ? BestSearchDir >= SystemDirIdx : false;
Eric Liudffb1a82018-01-29 13:21:23 +00001720 return File.drop_front(BestPrefixLength);
Richard Smith4eb83932016-04-27 21:57:05 +00001721}