/src/llvm-project/clang/lib/Lex/HeaderSearch.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===- HeaderSearch.cpp - Resolve Header File Locations -------------------===// |
2 | | // |
3 | | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | | // See https://llvm.org/LICENSE.txt for license information. |
5 | | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | // |
9 | | // This file implements the DirectoryLookup and HeaderSearch interfaces. |
10 | | // |
11 | | //===----------------------------------------------------------------------===// |
12 | | |
13 | | #include "clang/Lex/HeaderSearch.h" |
14 | | #include "clang/Basic/Diagnostic.h" |
15 | | #include "clang/Basic/FileManager.h" |
16 | | #include "clang/Basic/IdentifierTable.h" |
17 | | #include "clang/Basic/Module.h" |
18 | | #include "clang/Basic/SourceManager.h" |
19 | | #include "clang/Lex/DirectoryLookup.h" |
20 | | #include "clang/Lex/ExternalPreprocessorSource.h" |
21 | | #include "clang/Lex/HeaderMap.h" |
22 | | #include "clang/Lex/HeaderSearchOptions.h" |
23 | | #include "clang/Lex/LexDiagnostic.h" |
24 | | #include "clang/Lex/ModuleMap.h" |
25 | | #include "clang/Lex/Preprocessor.h" |
26 | | #include "llvm/ADT/APInt.h" |
27 | | #include "llvm/ADT/Hashing.h" |
28 | | #include "llvm/ADT/SmallString.h" |
29 | | #include "llvm/ADT/SmallVector.h" |
30 | | #include "llvm/ADT/Statistic.h" |
31 | | #include "llvm/ADT/StringRef.h" |
32 | | #include "llvm/ADT/STLExtras.h" |
33 | | #include "llvm/Support/Allocator.h" |
34 | | #include "llvm/Support/Capacity.h" |
35 | | #include "llvm/Support/Errc.h" |
36 | | #include "llvm/Support/ErrorHandling.h" |
37 | | #include "llvm/Support/FileSystem.h" |
38 | | #include "llvm/Support/Path.h" |
39 | | #include "llvm/Support/VirtualFileSystem.h" |
40 | | #include <algorithm> |
41 | | #include <cassert> |
42 | | #include <cstddef> |
43 | | #include <cstdio> |
44 | | #include <cstring> |
45 | | #include <string> |
46 | | #include <system_error> |
47 | | #include <utility> |
48 | | |
49 | | using namespace clang; |
50 | | |
51 | | #define DEBUG_TYPE "file-search" |
52 | | |
53 | | ALWAYS_ENABLED_STATISTIC(NumIncluded, "Number of attempted #includes."); |
54 | | ALWAYS_ENABLED_STATISTIC( |
55 | | NumMultiIncludeFileOptzn, |
56 | | "Number of #includes skipped due to the multi-include optimization."); |
57 | | ALWAYS_ENABLED_STATISTIC(NumFrameworkLookups, "Number of framework lookups."); |
58 | | ALWAYS_ENABLED_STATISTIC(NumSubFrameworkLookups, |
59 | | "Number of subframework lookups."); |
60 | | |
61 | | const IdentifierInfo * |
62 | 0 | HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) { |
63 | 0 | if (ControllingMacro) { |
64 | 0 | if (ControllingMacro->isOutOfDate()) { |
65 | 0 | assert(External && "We must have an external source if we have a " |
66 | 0 | "controlling macro that is out of date."); |
67 | 0 | External->updateOutOfDateIdentifier( |
68 | 0 | *const_cast<IdentifierInfo *>(ControllingMacro)); |
69 | 0 | } |
70 | 0 | return ControllingMacro; |
71 | 0 | } |
72 | | |
73 | 0 | if (!ControllingMacroID || !External) |
74 | 0 | return nullptr; |
75 | | |
76 | 0 | ControllingMacro = External->GetIdentifier(ControllingMacroID); |
77 | 0 | return ControllingMacro; |
78 | 0 | } |
79 | | |
80 | 0 | ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() = default; |
81 | | |
82 | | HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts, |
83 | | SourceManager &SourceMgr, DiagnosticsEngine &Diags, |
84 | | const LangOptions &LangOpts, |
85 | | const TargetInfo *Target) |
86 | | : HSOpts(std::move(HSOpts)), Diags(Diags), |
87 | | FileMgr(SourceMgr.getFileManager()), FrameworkMap(64), |
88 | 46 | ModMap(SourceMgr, Diags, LangOpts, Target, *this) {} |
89 | | |
90 | 0 | void HeaderSearch::PrintStats() { |
91 | 0 | llvm::errs() << "\n*** HeaderSearch Stats:\n" |
92 | 0 | << FileInfo.size() << " files tracked.\n"; |
93 | 0 | unsigned NumOnceOnlyFiles = 0; |
94 | 0 | for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) |
95 | 0 | NumOnceOnlyFiles += (FileInfo[i].isPragmaOnce || FileInfo[i].isImport); |
96 | 0 | llvm::errs() << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n"; |
97 | |
|
98 | 0 | llvm::errs() << " " << NumIncluded << " #include/#include_next/#import.\n" |
99 | 0 | << " " << NumMultiIncludeFileOptzn |
100 | 0 | << " #includes skipped due to the multi-include optimization.\n"; |
101 | |
|
102 | 0 | llvm::errs() << NumFrameworkLookups << " framework lookups.\n" |
103 | 0 | << NumSubFrameworkLookups << " subframework lookups.\n"; |
104 | 0 | } |
105 | | |
106 | | void HeaderSearch::SetSearchPaths( |
107 | | std::vector<DirectoryLookup> dirs, unsigned int angledDirIdx, |
108 | | unsigned int systemDirIdx, |
109 | 46 | llvm::DenseMap<unsigned int, unsigned int> searchDirToHSEntry) { |
110 | 46 | assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() && |
111 | 46 | "Directory indices are unordered"); |
112 | 0 | SearchDirs = std::move(dirs); |
113 | 46 | SearchDirsUsage.assign(SearchDirs.size(), false); |
114 | 46 | AngledDirIdx = angledDirIdx; |
115 | 46 | SystemDirIdx = systemDirIdx; |
116 | 46 | SearchDirToHSEntry = std::move(searchDirToHSEntry); |
117 | | //LookupFileCache.clear(); |
118 | 46 | indexInitialHeaderMaps(); |
119 | 46 | } |
120 | | |
121 | 0 | void HeaderSearch::AddSearchPath(const DirectoryLookup &dir, bool isAngled) { |
122 | 0 | unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx; |
123 | 0 | SearchDirs.insert(SearchDirs.begin() + idx, dir); |
124 | 0 | SearchDirsUsage.insert(SearchDirsUsage.begin() + idx, false); |
125 | 0 | if (!isAngled) |
126 | 0 | AngledDirIdx++; |
127 | 0 | SystemDirIdx++; |
128 | 0 | } |
129 | | |
130 | 0 | std::vector<bool> HeaderSearch::computeUserEntryUsage() const { |
131 | 0 | std::vector<bool> UserEntryUsage(HSOpts->UserEntries.size()); |
132 | 0 | for (unsigned I = 0, E = SearchDirsUsage.size(); I < E; ++I) { |
133 | | // Check whether this DirectoryLookup has been successfully used. |
134 | 0 | if (SearchDirsUsage[I]) { |
135 | 0 | auto UserEntryIdxIt = SearchDirToHSEntry.find(I); |
136 | | // Check whether this DirectoryLookup maps to a HeaderSearch::UserEntry. |
137 | 0 | if (UserEntryIdxIt != SearchDirToHSEntry.end()) |
138 | 0 | UserEntryUsage[UserEntryIdxIt->second] = true; |
139 | 0 | } |
140 | 0 | } |
141 | 0 | return UserEntryUsage; |
142 | 0 | } |
143 | | |
144 | | /// CreateHeaderMap - This method returns a HeaderMap for the specified |
145 | | /// FileEntry, uniquing them through the 'HeaderMaps' datastructure. |
146 | 0 | const HeaderMap *HeaderSearch::CreateHeaderMap(FileEntryRef FE) { |
147 | | // We expect the number of headermaps to be small, and almost always empty. |
148 | | // If it ever grows, use of a linear search should be re-evaluated. |
149 | 0 | if (!HeaderMaps.empty()) { |
150 | 0 | for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i) |
151 | | // Pointer equality comparison of FileEntries works because they are |
152 | | // already uniqued by inode. |
153 | 0 | if (HeaderMaps[i].first == FE) |
154 | 0 | return HeaderMaps[i].second.get(); |
155 | 0 | } |
156 | | |
157 | 0 | if (std::unique_ptr<HeaderMap> HM = HeaderMap::Create(FE, FileMgr)) { |
158 | 0 | HeaderMaps.emplace_back(FE, std::move(HM)); |
159 | 0 | return HeaderMaps.back().second.get(); |
160 | 0 | } |
161 | | |
162 | 0 | return nullptr; |
163 | 0 | } |
164 | | |
165 | | /// Get filenames for all registered header maps. |
166 | | void HeaderSearch::getHeaderMapFileNames( |
167 | 0 | SmallVectorImpl<std::string> &Names) const { |
168 | 0 | for (auto &HM : HeaderMaps) |
169 | 0 | Names.push_back(std::string(HM.first.getName())); |
170 | 0 | } |
171 | | |
172 | 0 | std::string HeaderSearch::getCachedModuleFileName(Module *Module) { |
173 | 0 | OptionalFileEntryRef ModuleMap = |
174 | 0 | getModuleMap().getModuleMapFileForUniquing(Module); |
175 | | // The ModuleMap maybe a nullptr, when we load a cached C++ module without |
176 | | // *.modulemap file. In this case, just return an empty string. |
177 | 0 | if (!ModuleMap) |
178 | 0 | return {}; |
179 | 0 | return getCachedModuleFileName(Module->Name, ModuleMap->getNameAsRequested()); |
180 | 0 | } |
181 | | |
182 | | std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName, |
183 | 0 | bool FileMapOnly) { |
184 | | // First check the module name to pcm file map. |
185 | 0 | auto i(HSOpts->PrebuiltModuleFiles.find(ModuleName)); |
186 | 0 | if (i != HSOpts->PrebuiltModuleFiles.end()) |
187 | 0 | return i->second; |
188 | | |
189 | 0 | if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty()) |
190 | 0 | return {}; |
191 | | |
192 | | // Then go through each prebuilt module directory and try to find the pcm |
193 | | // file. |
194 | 0 | for (const std::string &Dir : HSOpts->PrebuiltModulePaths) { |
195 | 0 | SmallString<256> Result(Dir); |
196 | 0 | llvm::sys::fs::make_absolute(Result); |
197 | 0 | if (ModuleName.contains(':')) |
198 | | // The separator of C++20 modules partitions (':') is not good for file |
199 | | // systems, here clang and gcc choose '-' by default since it is not a |
200 | | // valid character of C++ indentifiers. So we could avoid conflicts. |
201 | 0 | llvm::sys::path::append(Result, ModuleName.split(':').first + "-" + |
202 | 0 | ModuleName.split(':').second + |
203 | 0 | ".pcm"); |
204 | 0 | else |
205 | 0 | llvm::sys::path::append(Result, ModuleName + ".pcm"); |
206 | 0 | if (getFileMgr().getFile(Result.str())) |
207 | 0 | return std::string(Result); |
208 | 0 | } |
209 | | |
210 | 0 | return {}; |
211 | 0 | } |
212 | | |
213 | 0 | std::string HeaderSearch::getPrebuiltImplicitModuleFileName(Module *Module) { |
214 | 0 | OptionalFileEntryRef ModuleMap = |
215 | 0 | getModuleMap().getModuleMapFileForUniquing(Module); |
216 | 0 | StringRef ModuleName = Module->Name; |
217 | 0 | StringRef ModuleMapPath = ModuleMap->getName(); |
218 | 0 | StringRef ModuleCacheHash = HSOpts->DisableModuleHash ? "" : getModuleHash(); |
219 | 0 | for (const std::string &Dir : HSOpts->PrebuiltModulePaths) { |
220 | 0 | SmallString<256> CachePath(Dir); |
221 | 0 | llvm::sys::fs::make_absolute(CachePath); |
222 | 0 | llvm::sys::path::append(CachePath, ModuleCacheHash); |
223 | 0 | std::string FileName = |
224 | 0 | getCachedModuleFileNameImpl(ModuleName, ModuleMapPath, CachePath); |
225 | 0 | if (!FileName.empty() && getFileMgr().getFile(FileName)) |
226 | 0 | return FileName; |
227 | 0 | } |
228 | 0 | return {}; |
229 | 0 | } |
230 | | |
231 | | std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName, |
232 | 0 | StringRef ModuleMapPath) { |
233 | 0 | return getCachedModuleFileNameImpl(ModuleName, ModuleMapPath, |
234 | 0 | getModuleCachePath()); |
235 | 0 | } |
236 | | |
237 | | std::string HeaderSearch::getCachedModuleFileNameImpl(StringRef ModuleName, |
238 | | StringRef ModuleMapPath, |
239 | 0 | StringRef CachePath) { |
240 | | // If we don't have a module cache path or aren't supposed to use one, we |
241 | | // can't do anything. |
242 | 0 | if (CachePath.empty()) |
243 | 0 | return {}; |
244 | | |
245 | 0 | SmallString<256> Result(CachePath); |
246 | 0 | llvm::sys::fs::make_absolute(Result); |
247 | |
|
248 | 0 | if (HSOpts->DisableModuleHash) { |
249 | 0 | llvm::sys::path::append(Result, ModuleName + ".pcm"); |
250 | 0 | } else { |
251 | | // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should |
252 | | // ideally be globally unique to this particular module. Name collisions |
253 | | // in the hash are safe (because any translation unit can only import one |
254 | | // module with each name), but result in a loss of caching. |
255 | | // |
256 | | // To avoid false-negatives, we form as canonical a path as we can, and map |
257 | | // to lower-case in case we're on a case-insensitive file system. |
258 | 0 | SmallString<128> CanonicalPath(ModuleMapPath); |
259 | 0 | if (getModuleMap().canonicalizeModuleMapPath(CanonicalPath)) |
260 | 0 | return {}; |
261 | | |
262 | 0 | llvm::hash_code Hash = llvm::hash_combine(CanonicalPath.str().lower()); |
263 | |
|
264 | 0 | SmallString<128> HashStr; |
265 | 0 | llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36); |
266 | 0 | llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm"); |
267 | 0 | } |
268 | 0 | return Result.str().str(); |
269 | 0 | } |
270 | | |
271 | | Module *HeaderSearch::lookupModule(StringRef ModuleName, |
272 | | SourceLocation ImportLoc, bool AllowSearch, |
273 | 0 | bool AllowExtraModuleMapSearch) { |
274 | | // Look in the module map to determine if there is a module by this name. |
275 | 0 | Module *Module = ModMap.findModule(ModuleName); |
276 | 0 | if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps) |
277 | 0 | return Module; |
278 | | |
279 | 0 | StringRef SearchName = ModuleName; |
280 | 0 | Module = lookupModule(ModuleName, SearchName, ImportLoc, |
281 | 0 | AllowExtraModuleMapSearch); |
282 | | |
283 | | // The facility for "private modules" -- adjacent, optional module maps named |
284 | | // module.private.modulemap that are supposed to define private submodules -- |
285 | | // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private. |
286 | | // |
287 | | // Foo.Private is now deprecated in favor of Foo_Private. Users of FooPrivate |
288 | | // should also rename to Foo_Private. Representing private as submodules |
289 | | // could force building unwanted dependencies into the parent module and cause |
290 | | // dependency cycles. |
291 | 0 | if (!Module && SearchName.consume_back("_Private")) |
292 | 0 | Module = lookupModule(ModuleName, SearchName, ImportLoc, |
293 | 0 | AllowExtraModuleMapSearch); |
294 | 0 | if (!Module && SearchName.consume_back("Private")) |
295 | 0 | Module = lookupModule(ModuleName, SearchName, ImportLoc, |
296 | 0 | AllowExtraModuleMapSearch); |
297 | 0 | return Module; |
298 | 0 | } |
299 | | |
300 | | Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName, |
301 | | SourceLocation ImportLoc, |
302 | 0 | bool AllowExtraModuleMapSearch) { |
303 | 0 | Module *Module = nullptr; |
304 | | |
305 | | // Look through the various header search paths to load any available module |
306 | | // maps, searching for a module map that describes this module. |
307 | 0 | for (DirectoryLookup &Dir : search_dir_range()) { |
308 | 0 | if (Dir.isFramework()) { |
309 | | // Search for or infer a module map for a framework. Here we use |
310 | | // SearchName rather than ModuleName, to permit finding private modules |
311 | | // named FooPrivate in buggy frameworks named Foo. |
312 | 0 | SmallString<128> FrameworkDirName; |
313 | 0 | FrameworkDirName += Dir.getFrameworkDirRef()->getName(); |
314 | 0 | llvm::sys::path::append(FrameworkDirName, SearchName + ".framework"); |
315 | 0 | if (auto FrameworkDir = |
316 | 0 | FileMgr.getOptionalDirectoryRef(FrameworkDirName)) { |
317 | 0 | bool IsSystem = Dir.getDirCharacteristic() != SrcMgr::C_User; |
318 | 0 | Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem); |
319 | 0 | if (Module) |
320 | 0 | break; |
321 | 0 | } |
322 | 0 | } |
323 | | |
324 | | // FIXME: Figure out how header maps and module maps will work together. |
325 | | |
326 | | // Only deal with normal search directories. |
327 | 0 | if (!Dir.isNormalDir()) |
328 | 0 | continue; |
329 | | |
330 | 0 | bool IsSystem = Dir.isSystemHeaderDirectory(); |
331 | | // Only returns std::nullopt if not a normal directory, which we just |
332 | | // checked |
333 | 0 | DirectoryEntryRef NormalDir = *Dir.getDirRef(); |
334 | | // Search for a module map file in this directory. |
335 | 0 | if (loadModuleMapFile(NormalDir, IsSystem, |
336 | 0 | /*IsFramework*/false) == LMM_NewlyLoaded) { |
337 | | // We just loaded a module map file; check whether the module is |
338 | | // available now. |
339 | 0 | Module = ModMap.findModule(ModuleName); |
340 | 0 | if (Module) |
341 | 0 | break; |
342 | 0 | } |
343 | | |
344 | | // Search for a module map in a subdirectory with the same name as the |
345 | | // module. |
346 | 0 | SmallString<128> NestedModuleMapDirName; |
347 | 0 | NestedModuleMapDirName = Dir.getDirRef()->getName(); |
348 | 0 | llvm::sys::path::append(NestedModuleMapDirName, ModuleName); |
349 | 0 | if (loadModuleMapFile(NestedModuleMapDirName, IsSystem, |
350 | 0 | /*IsFramework*/false) == LMM_NewlyLoaded){ |
351 | | // If we just loaded a module map file, look for the module again. |
352 | 0 | Module = ModMap.findModule(ModuleName); |
353 | 0 | if (Module) |
354 | 0 | break; |
355 | 0 | } |
356 | | |
357 | | // If we've already performed the exhaustive search for module maps in this |
358 | | // search directory, don't do it again. |
359 | 0 | if (Dir.haveSearchedAllModuleMaps()) |
360 | 0 | continue; |
361 | | |
362 | | // Load all module maps in the immediate subdirectories of this search |
363 | | // directory if ModuleName was from @import. |
364 | 0 | if (AllowExtraModuleMapSearch) |
365 | 0 | loadSubdirectoryModuleMaps(Dir); |
366 | | |
367 | | // Look again for the module. |
368 | 0 | Module = ModMap.findModule(ModuleName); |
369 | 0 | if (Module) |
370 | 0 | break; |
371 | 0 | } |
372 | |
|
373 | 0 | return Module; |
374 | 0 | } |
375 | | |
376 | 46 | void HeaderSearch::indexInitialHeaderMaps() { |
377 | 46 | llvm::StringMap<unsigned, llvm::BumpPtrAllocator> Index(SearchDirs.size()); |
378 | | |
379 | | // Iterate over all filename keys and associate them with the index i. |
380 | 46 | for (unsigned i = 0; i != SearchDirs.size(); ++i) { |
381 | 0 | auto &Dir = SearchDirs[i]; |
382 | | |
383 | | // We're concerned with only the initial contiguous run of header |
384 | | // maps within SearchDirs, which can be 99% of SearchDirs when |
385 | | // SearchDirs.size() is ~10000. |
386 | 0 | if (!Dir.isHeaderMap()) { |
387 | 0 | SearchDirHeaderMapIndex = std::move(Index); |
388 | 0 | FirstNonHeaderMapSearchDirIdx = i; |
389 | 0 | break; |
390 | 0 | } |
391 | | |
392 | | // Give earlier keys precedence over identical later keys. |
393 | 0 | auto Callback = [&](StringRef Filename) { |
394 | 0 | Index.try_emplace(Filename.lower(), i); |
395 | 0 | }; |
396 | 0 | Dir.getHeaderMap()->forEachKey(Callback); |
397 | 0 | } |
398 | 46 | } |
399 | | |
400 | | //===----------------------------------------------------------------------===// |
401 | | // File lookup within a DirectoryLookup scope |
402 | | //===----------------------------------------------------------------------===// |
403 | | |
404 | | /// getName - Return the directory or filename corresponding to this lookup |
405 | | /// object. |
406 | 0 | StringRef DirectoryLookup::getName() const { |
407 | 0 | if (isNormalDir()) |
408 | 0 | return getDirRef()->getName(); |
409 | 0 | if (isFramework()) |
410 | 0 | return getFrameworkDirRef()->getName(); |
411 | 0 | assert(isHeaderMap() && "Unknown DirectoryLookup"); |
412 | 0 | return getHeaderMap()->getFileName(); |
413 | 0 | } |
414 | | |
415 | | OptionalFileEntryRef HeaderSearch::getFileAndSuggestModule( |
416 | | StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir, |
417 | | bool IsSystemHeaderDir, Module *RequestingModule, |
418 | | ModuleMap::KnownHeader *SuggestedModule, bool OpenFile /*=true*/, |
419 | 0 | bool CacheFailures /*=true*/) { |
420 | | // If we have a module map that might map this header, load it and |
421 | | // check whether we'll have a suggestion for a module. |
422 | 0 | auto File = getFileMgr().getFileRef(FileName, OpenFile, CacheFailures); |
423 | 0 | if (!File) { |
424 | | // For rare, surprising errors (e.g. "out of file handles"), diag the EC |
425 | | // message. |
426 | 0 | std::error_code EC = llvm::errorToErrorCode(File.takeError()); |
427 | 0 | if (EC != llvm::errc::no_such_file_or_directory && |
428 | 0 | EC != llvm::errc::invalid_argument && |
429 | 0 | EC != llvm::errc::is_a_directory && EC != llvm::errc::not_a_directory) { |
430 | 0 | Diags.Report(IncludeLoc, diag::err_cannot_open_file) |
431 | 0 | << FileName << EC.message(); |
432 | 0 | } |
433 | 0 | return std::nullopt; |
434 | 0 | } |
435 | | |
436 | | // If there is a module that corresponds to this header, suggest it. |
437 | 0 | if (!findUsableModuleForHeader( |
438 | 0 | *File, Dir ? Dir : File->getFileEntry().getDir(), RequestingModule, |
439 | 0 | SuggestedModule, IsSystemHeaderDir)) |
440 | 0 | return std::nullopt; |
441 | | |
442 | 0 | return *File; |
443 | 0 | } |
444 | | |
445 | | /// LookupFile - Lookup the specified file in this search path, returning it |
446 | | /// if it exists or returning null if not. |
447 | | OptionalFileEntryRef DirectoryLookup::LookupFile( |
448 | | StringRef &Filename, HeaderSearch &HS, SourceLocation IncludeLoc, |
449 | | SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, |
450 | | Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule, |
451 | | bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound, |
452 | | bool &IsInHeaderMap, SmallVectorImpl<char> &MappedName, |
453 | 0 | bool OpenFile) const { |
454 | 0 | InUserSpecifiedSystemFramework = false; |
455 | 0 | IsInHeaderMap = false; |
456 | 0 | MappedName.clear(); |
457 | |
|
458 | 0 | SmallString<1024> TmpDir; |
459 | 0 | if (isNormalDir()) { |
460 | | // Concatenate the requested file onto the directory. |
461 | 0 | TmpDir = getDirRef()->getName(); |
462 | 0 | llvm::sys::path::append(TmpDir, Filename); |
463 | 0 | if (SearchPath) { |
464 | 0 | StringRef SearchPathRef(getDirRef()->getName()); |
465 | 0 | SearchPath->clear(); |
466 | 0 | SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); |
467 | 0 | } |
468 | 0 | if (RelativePath) { |
469 | 0 | RelativePath->clear(); |
470 | 0 | RelativePath->append(Filename.begin(), Filename.end()); |
471 | 0 | } |
472 | |
|
473 | 0 | return HS.getFileAndSuggestModule( |
474 | 0 | TmpDir, IncludeLoc, getDir(), isSystemHeaderDirectory(), |
475 | 0 | RequestingModule, SuggestedModule, OpenFile); |
476 | 0 | } |
477 | | |
478 | 0 | if (isFramework()) |
479 | 0 | return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath, |
480 | 0 | RequestingModule, SuggestedModule, |
481 | 0 | InUserSpecifiedSystemFramework, IsFrameworkFound); |
482 | | |
483 | 0 | assert(isHeaderMap() && "Unknown directory lookup"); |
484 | 0 | const HeaderMap *HM = getHeaderMap(); |
485 | 0 | SmallString<1024> Path; |
486 | 0 | StringRef Dest = HM->lookupFilename(Filename, Path); |
487 | 0 | if (Dest.empty()) |
488 | 0 | return std::nullopt; |
489 | | |
490 | 0 | IsInHeaderMap = true; |
491 | |
|
492 | 0 | auto FixupSearchPathAndFindUsableModule = |
493 | 0 | [&](FileEntryRef File) -> OptionalFileEntryRef { |
494 | 0 | if (SearchPath) { |
495 | 0 | StringRef SearchPathRef(getName()); |
496 | 0 | SearchPath->clear(); |
497 | 0 | SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); |
498 | 0 | } |
499 | 0 | if (RelativePath) { |
500 | 0 | RelativePath->clear(); |
501 | 0 | RelativePath->append(Filename.begin(), Filename.end()); |
502 | 0 | } |
503 | 0 | if (!HS.findUsableModuleForHeader(File, File.getFileEntry().getDir(), |
504 | 0 | RequestingModule, SuggestedModule, |
505 | 0 | isSystemHeaderDirectory())) { |
506 | 0 | return std::nullopt; |
507 | 0 | } |
508 | 0 | return File; |
509 | 0 | }; |
510 | | |
511 | | // Check if the headermap maps the filename to a framework include |
512 | | // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the |
513 | | // framework include. |
514 | 0 | if (llvm::sys::path::is_relative(Dest)) { |
515 | 0 | MappedName.append(Dest.begin(), Dest.end()); |
516 | 0 | Filename = StringRef(MappedName.begin(), MappedName.size()); |
517 | 0 | Dest = HM->lookupFilename(Filename, Path); |
518 | 0 | } |
519 | |
|
520 | 0 | if (auto Res = HS.getFileMgr().getOptionalFileRef(Dest, OpenFile)) { |
521 | 0 | return FixupSearchPathAndFindUsableModule(*Res); |
522 | 0 | } |
523 | | |
524 | | // Header maps need to be marked as used whenever the filename matches. |
525 | | // The case where the target file **exists** is handled by callee of this |
526 | | // function as part of the regular logic that applies to include search paths. |
527 | | // The case where the target file **does not exist** is handled here: |
528 | 0 | HS.noteLookupUsage(HS.searchDirIdx(*this), IncludeLoc); |
529 | 0 | return std::nullopt; |
530 | 0 | } |
531 | | |
532 | | /// Given a framework directory, find the top-most framework directory. |
533 | | /// |
534 | | /// \param FileMgr The file manager to use for directory lookups. |
535 | | /// \param DirName The name of the framework directory. |
536 | | /// \param SubmodulePath Will be populated with the submodule path from the |
537 | | /// returned top-level module to the originally named framework. |
538 | | static OptionalDirectoryEntryRef |
539 | | getTopFrameworkDir(FileManager &FileMgr, StringRef DirName, |
540 | 0 | SmallVectorImpl<std::string> &SubmodulePath) { |
541 | 0 | assert(llvm::sys::path::extension(DirName) == ".framework" && |
542 | 0 | "Not a framework directory"); |
543 | | |
544 | | // Note: as an egregious but useful hack we use the real path here, because |
545 | | // frameworks moving between top-level frameworks to embedded frameworks tend |
546 | | // to be symlinked, and we base the logical structure of modules on the |
547 | | // physical layout. In particular, we need to deal with crazy includes like |
548 | | // |
549 | | // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h> |
550 | | // |
551 | | // where 'Bar' used to be embedded in 'Foo', is now a top-level framework |
552 | | // which one should access with, e.g., |
553 | | // |
554 | | // #include <Bar/Wibble.h> |
555 | | // |
556 | | // Similar issues occur when a top-level framework has moved into an |
557 | | // embedded framework. |
558 | 0 | auto TopFrameworkDir = FileMgr.getOptionalDirectoryRef(DirName); |
559 | |
|
560 | 0 | if (TopFrameworkDir) |
561 | 0 | DirName = FileMgr.getCanonicalName(*TopFrameworkDir); |
562 | 0 | do { |
563 | | // Get the parent directory name. |
564 | 0 | DirName = llvm::sys::path::parent_path(DirName); |
565 | 0 | if (DirName.empty()) |
566 | 0 | break; |
567 | | |
568 | | // Determine whether this directory exists. |
569 | 0 | auto Dir = FileMgr.getOptionalDirectoryRef(DirName); |
570 | 0 | if (!Dir) |
571 | 0 | break; |
572 | | |
573 | | // If this is a framework directory, then we're a subframework of this |
574 | | // framework. |
575 | 0 | if (llvm::sys::path::extension(DirName) == ".framework") { |
576 | 0 | SubmodulePath.push_back(std::string(llvm::sys::path::stem(DirName))); |
577 | 0 | TopFrameworkDir = *Dir; |
578 | 0 | } |
579 | 0 | } while (true); |
580 | | |
581 | 0 | return TopFrameworkDir; |
582 | 0 | } |
583 | | |
584 | | static bool needModuleLookup(Module *RequestingModule, |
585 | 0 | bool HasSuggestedModule) { |
586 | 0 | return HasSuggestedModule || |
587 | 0 | (RequestingModule && RequestingModule->NoUndeclaredIncludes); |
588 | 0 | } |
589 | | |
590 | | /// DoFrameworkLookup - Do a lookup of the specified file in the current |
591 | | /// DirectoryLookup, which is a framework directory. |
592 | | OptionalFileEntryRef DirectoryLookup::DoFrameworkLookup( |
593 | | StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath, |
594 | | SmallVectorImpl<char> *RelativePath, Module *RequestingModule, |
595 | | ModuleMap::KnownHeader *SuggestedModule, |
596 | 0 | bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound) const { |
597 | 0 | FileManager &FileMgr = HS.getFileMgr(); |
598 | | |
599 | | // Framework names must have a '/' in the filename. |
600 | 0 | size_t SlashPos = Filename.find('/'); |
601 | 0 | if (SlashPos == StringRef::npos) |
602 | 0 | return std::nullopt; |
603 | | |
604 | | // Find out if this is the home for the specified framework, by checking |
605 | | // HeaderSearch. Possible answers are yes/no and unknown. |
606 | 0 | FrameworkCacheEntry &CacheEntry = |
607 | 0 | HS.LookupFrameworkCache(Filename.substr(0, SlashPos)); |
608 | | |
609 | | // If it is known and in some other directory, fail. |
610 | 0 | if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDirRef()) |
611 | 0 | return std::nullopt; |
612 | | |
613 | | // Otherwise, construct the path to this framework dir. |
614 | | |
615 | | // FrameworkName = "/System/Library/Frameworks/" |
616 | 0 | SmallString<1024> FrameworkName; |
617 | 0 | FrameworkName += getFrameworkDirRef()->getName(); |
618 | 0 | if (FrameworkName.empty() || FrameworkName.back() != '/') |
619 | 0 | FrameworkName.push_back('/'); |
620 | | |
621 | | // FrameworkName = "/System/Library/Frameworks/Cocoa" |
622 | 0 | StringRef ModuleName(Filename.begin(), SlashPos); |
623 | 0 | FrameworkName += ModuleName; |
624 | | |
625 | | // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/" |
626 | 0 | FrameworkName += ".framework/"; |
627 | | |
628 | | // If the cache entry was unresolved, populate it now. |
629 | 0 | if (!CacheEntry.Directory) { |
630 | 0 | ++NumFrameworkLookups; |
631 | | |
632 | | // If the framework dir doesn't exist, we fail. |
633 | 0 | auto Dir = FileMgr.getDirectory(FrameworkName); |
634 | 0 | if (!Dir) |
635 | 0 | return std::nullopt; |
636 | | |
637 | | // Otherwise, if it does, remember that this is the right direntry for this |
638 | | // framework. |
639 | 0 | CacheEntry.Directory = getFrameworkDirRef(); |
640 | | |
641 | | // If this is a user search directory, check if the framework has been |
642 | | // user-specified as a system framework. |
643 | 0 | if (getDirCharacteristic() == SrcMgr::C_User) { |
644 | 0 | SmallString<1024> SystemFrameworkMarker(FrameworkName); |
645 | 0 | SystemFrameworkMarker += ".system_framework"; |
646 | 0 | if (llvm::sys::fs::exists(SystemFrameworkMarker)) { |
647 | 0 | CacheEntry.IsUserSpecifiedSystemFramework = true; |
648 | 0 | } |
649 | 0 | } |
650 | 0 | } |
651 | | |
652 | | // Set out flags. |
653 | 0 | InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework; |
654 | 0 | IsFrameworkFound = CacheEntry.Directory.has_value(); |
655 | |
|
656 | 0 | if (RelativePath) { |
657 | 0 | RelativePath->clear(); |
658 | 0 | RelativePath->append(Filename.begin()+SlashPos+1, Filename.end()); |
659 | 0 | } |
660 | | |
661 | | // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h" |
662 | 0 | unsigned OrigSize = FrameworkName.size(); |
663 | |
|
664 | 0 | FrameworkName += "Headers/"; |
665 | |
|
666 | 0 | if (SearchPath) { |
667 | 0 | SearchPath->clear(); |
668 | | // Without trailing '/'. |
669 | 0 | SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1); |
670 | 0 | } |
671 | |
|
672 | 0 | FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end()); |
673 | |
|
674 | 0 | auto File = |
675 | 0 | FileMgr.getOptionalFileRef(FrameworkName, /*OpenFile=*/!SuggestedModule); |
676 | 0 | if (!File) { |
677 | | // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h" |
678 | 0 | const char *Private = "Private"; |
679 | 0 | FrameworkName.insert(FrameworkName.begin()+OrigSize, Private, |
680 | 0 | Private+strlen(Private)); |
681 | 0 | if (SearchPath) |
682 | 0 | SearchPath->insert(SearchPath->begin()+OrigSize, Private, |
683 | 0 | Private+strlen(Private)); |
684 | |
|
685 | 0 | File = FileMgr.getOptionalFileRef(FrameworkName, |
686 | 0 | /*OpenFile=*/!SuggestedModule); |
687 | 0 | } |
688 | | |
689 | | // If we found the header and are allowed to suggest a module, do so now. |
690 | 0 | if (File && needModuleLookup(RequestingModule, SuggestedModule)) { |
691 | | // Find the framework in which this header occurs. |
692 | 0 | StringRef FrameworkPath = File->getDir().getName(); |
693 | 0 | bool FoundFramework = false; |
694 | 0 | do { |
695 | | // Determine whether this directory exists. |
696 | 0 | auto Dir = FileMgr.getDirectory(FrameworkPath); |
697 | 0 | if (!Dir) |
698 | 0 | break; |
699 | | |
700 | | // If this is a framework directory, then we're a subframework of this |
701 | | // framework. |
702 | 0 | if (llvm::sys::path::extension(FrameworkPath) == ".framework") { |
703 | 0 | FoundFramework = true; |
704 | 0 | break; |
705 | 0 | } |
706 | | |
707 | | // Get the parent directory name. |
708 | 0 | FrameworkPath = llvm::sys::path::parent_path(FrameworkPath); |
709 | 0 | if (FrameworkPath.empty()) |
710 | 0 | break; |
711 | 0 | } while (true); |
712 | | |
713 | 0 | bool IsSystem = getDirCharacteristic() != SrcMgr::C_User; |
714 | 0 | if (FoundFramework) { |
715 | 0 | if (!HS.findUsableModuleForFrameworkHeader(*File, FrameworkPath, |
716 | 0 | RequestingModule, |
717 | 0 | SuggestedModule, IsSystem)) |
718 | 0 | return std::nullopt; |
719 | 0 | } else { |
720 | 0 | if (!HS.findUsableModuleForHeader(*File, getDir(), RequestingModule, |
721 | 0 | SuggestedModule, IsSystem)) |
722 | 0 | return std::nullopt; |
723 | 0 | } |
724 | 0 | } |
725 | 0 | if (File) |
726 | 0 | return *File; |
727 | 0 | return std::nullopt; |
728 | 0 | } |
729 | | |
730 | | void HeaderSearch::cacheLookupSuccess(LookupFileCacheInfo &CacheLookup, |
731 | | ConstSearchDirIterator HitIt, |
732 | 0 | SourceLocation Loc) { |
733 | 0 | CacheLookup.HitIt = HitIt; |
734 | 0 | noteLookupUsage(HitIt.Idx, Loc); |
735 | 0 | } |
736 | | |
737 | 0 | void HeaderSearch::noteLookupUsage(unsigned HitIdx, SourceLocation Loc) { |
738 | 0 | SearchDirsUsage[HitIdx] = true; |
739 | |
|
740 | 0 | auto UserEntryIdxIt = SearchDirToHSEntry.find(HitIdx); |
741 | 0 | if (UserEntryIdxIt != SearchDirToHSEntry.end()) |
742 | 0 | Diags.Report(Loc, diag::remark_pp_search_path_usage) |
743 | 0 | << HSOpts->UserEntries[UserEntryIdxIt->second].Path; |
744 | 0 | } |
745 | | |
746 | 46 | void HeaderSearch::setTarget(const TargetInfo &Target) { |
747 | 46 | ModMap.setTarget(Target); |
748 | 46 | } |
749 | | |
750 | | //===----------------------------------------------------------------------===// |
751 | | // Header File Location. |
752 | | //===----------------------------------------------------------------------===// |
753 | | |
754 | | /// Return true with a diagnostic if the file that MSVC would have found |
755 | | /// fails to match the one that Clang would have found with MSVC header search |
756 | | /// disabled. |
757 | | static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags, |
758 | | OptionalFileEntryRef MSFE, |
759 | | const FileEntry *FE, |
760 | 0 | SourceLocation IncludeLoc) { |
761 | 0 | if (MSFE && FE != *MSFE) { |
762 | 0 | Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName(); |
763 | 0 | return true; |
764 | 0 | } |
765 | 0 | return false; |
766 | 0 | } |
767 | | |
768 | 0 | static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) { |
769 | 0 | assert(!Str.empty()); |
770 | 0 | char *CopyStr = Alloc.Allocate<char>(Str.size()+1); |
771 | 0 | std::copy(Str.begin(), Str.end(), CopyStr); |
772 | 0 | CopyStr[Str.size()] = '\0'; |
773 | 0 | return CopyStr; |
774 | 0 | } |
775 | | |
776 | | static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader, |
777 | | SmallVectorImpl<char> &FrameworkName, |
778 | 0 | SmallVectorImpl<char> &IncludeSpelling) { |
779 | 0 | using namespace llvm::sys; |
780 | 0 | path::const_iterator I = path::begin(Path); |
781 | 0 | path::const_iterator E = path::end(Path); |
782 | 0 | IsPrivateHeader = false; |
783 | | |
784 | | // Detect different types of framework style paths: |
785 | | // |
786 | | // ...Foo.framework/{Headers,PrivateHeaders} |
787 | | // ...Foo.framework/Versions/{A,Current}/{Headers,PrivateHeaders} |
788 | | // ...Foo.framework/Frameworks/Nested.framework/{Headers,PrivateHeaders} |
789 | | // ...<other variations with 'Versions' like in the above path> |
790 | | // |
791 | | // and some other variations among these lines. |
792 | 0 | int FoundComp = 0; |
793 | 0 | while (I != E) { |
794 | 0 | if (*I == "Headers") { |
795 | 0 | ++FoundComp; |
796 | 0 | } else if (*I == "PrivateHeaders") { |
797 | 0 | ++FoundComp; |
798 | 0 | IsPrivateHeader = true; |
799 | 0 | } else if (I->ends_with(".framework")) { |
800 | 0 | StringRef Name = I->drop_back(10); // Drop .framework |
801 | | // Need to reset the strings and counter to support nested frameworks. |
802 | 0 | FrameworkName.clear(); |
803 | 0 | FrameworkName.append(Name.begin(), Name.end()); |
804 | 0 | IncludeSpelling.clear(); |
805 | 0 | IncludeSpelling.append(Name.begin(), Name.end()); |
806 | 0 | FoundComp = 1; |
807 | 0 | } else if (FoundComp >= 2) { |
808 | 0 | IncludeSpelling.push_back('/'); |
809 | 0 | IncludeSpelling.append(I->begin(), I->end()); |
810 | 0 | } |
811 | 0 | ++I; |
812 | 0 | } |
813 | |
|
814 | 0 | return !FrameworkName.empty() && FoundComp >= 2; |
815 | 0 | } |
816 | | |
817 | | static void |
818 | | diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc, |
819 | | StringRef Includer, StringRef IncludeFilename, |
820 | | FileEntryRef IncludeFE, bool isAngled = false, |
821 | 0 | bool FoundByHeaderMap = false) { |
822 | 0 | bool IsIncluderPrivateHeader = false; |
823 | 0 | SmallString<128> FromFramework, ToFramework; |
824 | 0 | SmallString<128> FromIncludeSpelling, ToIncludeSpelling; |
825 | 0 | if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework, |
826 | 0 | FromIncludeSpelling)) |
827 | 0 | return; |
828 | 0 | bool IsIncludeePrivateHeader = false; |
829 | 0 | bool IsIncludeeInFramework = |
830 | 0 | isFrameworkStylePath(IncludeFE.getName(), IsIncludeePrivateHeader, |
831 | 0 | ToFramework, ToIncludeSpelling); |
832 | |
|
833 | 0 | if (!isAngled && !FoundByHeaderMap) { |
834 | 0 | SmallString<128> NewInclude("<"); |
835 | 0 | if (IsIncludeeInFramework) { |
836 | 0 | NewInclude += ToIncludeSpelling; |
837 | 0 | NewInclude += ">"; |
838 | 0 | } else { |
839 | 0 | NewInclude += IncludeFilename; |
840 | 0 | NewInclude += ">"; |
841 | 0 | } |
842 | 0 | Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header) |
843 | 0 | << IncludeFilename |
844 | 0 | << FixItHint::CreateReplacement(IncludeLoc, NewInclude); |
845 | 0 | } |
846 | | |
847 | | // Headers in Foo.framework/Headers should not include headers |
848 | | // from Foo.framework/PrivateHeaders, since this violates public/private |
849 | | // API boundaries and can cause modular dependency cycles. |
850 | 0 | if (!IsIncluderPrivateHeader && IsIncludeeInFramework && |
851 | 0 | IsIncludeePrivateHeader && FromFramework == ToFramework) |
852 | 0 | Diags.Report(IncludeLoc, diag::warn_framework_include_private_from_public) |
853 | 0 | << IncludeFilename; |
854 | 0 | } |
855 | | |
856 | | /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file, |
857 | | /// return null on failure. isAngled indicates whether the file reference is |
858 | | /// for system \#include's or not (i.e. using <> instead of ""). Includers, if |
859 | | /// non-empty, indicates where the \#including file(s) are, in case a relative |
860 | | /// search is needed. Microsoft mode will pass all \#including files. |
861 | | OptionalFileEntryRef HeaderSearch::LookupFile( |
862 | | StringRef Filename, SourceLocation IncludeLoc, bool isAngled, |
863 | | ConstSearchDirIterator FromDir, ConstSearchDirIterator *CurDirArg, |
864 | | ArrayRef<std::pair<OptionalFileEntryRef, DirectoryEntryRef>> Includers, |
865 | | SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, |
866 | | Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule, |
867 | | bool *IsMapped, bool *IsFrameworkFound, bool SkipCache, |
868 | 0 | bool BuildSystemModule, bool OpenFile, bool CacheFailures) { |
869 | 0 | ConstSearchDirIterator CurDirLocal = nullptr; |
870 | 0 | ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal; |
871 | |
|
872 | 0 | if (IsMapped) |
873 | 0 | *IsMapped = false; |
874 | |
|
875 | 0 | if (IsFrameworkFound) |
876 | 0 | *IsFrameworkFound = false; |
877 | |
|
878 | 0 | if (SuggestedModule) |
879 | 0 | *SuggestedModule = ModuleMap::KnownHeader(); |
880 | | |
881 | | // If 'Filename' is absolute, check to see if it exists and no searching. |
882 | 0 | if (llvm::sys::path::is_absolute(Filename)) { |
883 | 0 | CurDir = nullptr; |
884 | | |
885 | | // If this was an #include_next "/absolute/file", fail. |
886 | 0 | if (FromDir) |
887 | 0 | return std::nullopt; |
888 | | |
889 | 0 | if (SearchPath) |
890 | 0 | SearchPath->clear(); |
891 | 0 | if (RelativePath) { |
892 | 0 | RelativePath->clear(); |
893 | 0 | RelativePath->append(Filename.begin(), Filename.end()); |
894 | 0 | } |
895 | | // Otherwise, just return the file. |
896 | 0 | return getFileAndSuggestModule(Filename, IncludeLoc, nullptr, |
897 | 0 | /*IsSystemHeaderDir*/ false, |
898 | 0 | RequestingModule, SuggestedModule, OpenFile, |
899 | 0 | CacheFailures); |
900 | 0 | } |
901 | | |
902 | | // This is the header that MSVC's header search would have found. |
903 | 0 | ModuleMap::KnownHeader MSSuggestedModule; |
904 | 0 | OptionalFileEntryRef MSFE; |
905 | | |
906 | | // Check to see if the file is in the #includer's directory. This cannot be |
907 | | // based on CurDir, because each includer could be a #include of a |
908 | | // subdirectory (#include "foo/bar.h") and a subsequent include of "baz.h" |
909 | | // should resolve to "whatever/foo/baz.h". This search is not done for <> |
910 | | // headers. |
911 | 0 | if (!Includers.empty() && !isAngled) { |
912 | 0 | SmallString<1024> TmpDir; |
913 | 0 | bool First = true; |
914 | 0 | for (const auto &IncluderAndDir : Includers) { |
915 | 0 | OptionalFileEntryRef Includer = IncluderAndDir.first; |
916 | | |
917 | | // Concatenate the requested file onto the directory. |
918 | 0 | TmpDir = IncluderAndDir.second.getName(); |
919 | 0 | llvm::sys::path::append(TmpDir, Filename); |
920 | | |
921 | | // FIXME: We don't cache the result of getFileInfo across the call to |
922 | | // getFileAndSuggestModule, because it's a reference to an element of |
923 | | // a container that could be reallocated across this call. |
924 | | // |
925 | | // If we have no includer, that means we're processing a #include |
926 | | // from a module build. We should treat this as a system header if we're |
927 | | // building a [system] module. |
928 | 0 | bool IncluderIsSystemHeader = |
929 | 0 | Includer ? getFileInfo(*Includer).DirInfo != SrcMgr::C_User : |
930 | 0 | BuildSystemModule; |
931 | 0 | if (OptionalFileEntryRef FE = getFileAndSuggestModule( |
932 | 0 | TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader, |
933 | 0 | RequestingModule, SuggestedModule)) { |
934 | 0 | if (!Includer) { |
935 | 0 | assert(First && "only first includer can have no file"); |
936 | 0 | return FE; |
937 | 0 | } |
938 | | |
939 | | // Leave CurDir unset. |
940 | | // This file is a system header or C++ unfriendly if the old file is. |
941 | | // |
942 | | // Note that we only use one of FromHFI/ToHFI at once, due to potential |
943 | | // reallocation of the underlying vector potentially making the first |
944 | | // reference binding dangling. |
945 | 0 | HeaderFileInfo &FromHFI = getFileInfo(*Includer); |
946 | 0 | unsigned DirInfo = FromHFI.DirInfo; |
947 | 0 | bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader; |
948 | 0 | StringRef Framework = FromHFI.Framework; |
949 | |
|
950 | 0 | HeaderFileInfo &ToHFI = getFileInfo(*FE); |
951 | 0 | ToHFI.DirInfo = DirInfo; |
952 | 0 | ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader; |
953 | 0 | ToHFI.Framework = Framework; |
954 | |
|
955 | 0 | if (SearchPath) { |
956 | 0 | StringRef SearchPathRef(IncluderAndDir.second.getName()); |
957 | 0 | SearchPath->clear(); |
958 | 0 | SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); |
959 | 0 | } |
960 | 0 | if (RelativePath) { |
961 | 0 | RelativePath->clear(); |
962 | 0 | RelativePath->append(Filename.begin(), Filename.end()); |
963 | 0 | } |
964 | 0 | if (First) { |
965 | 0 | diagnoseFrameworkInclude(Diags, IncludeLoc, |
966 | 0 | IncluderAndDir.second.getName(), Filename, |
967 | 0 | *FE); |
968 | 0 | return FE; |
969 | 0 | } |
970 | | |
971 | | // Otherwise, we found the path via MSVC header search rules. If |
972 | | // -Wmsvc-include is enabled, we have to keep searching to see if we |
973 | | // would've found this header in -I or -isystem directories. |
974 | 0 | if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) { |
975 | 0 | return FE; |
976 | 0 | } else { |
977 | 0 | MSFE = FE; |
978 | 0 | if (SuggestedModule) { |
979 | 0 | MSSuggestedModule = *SuggestedModule; |
980 | 0 | *SuggestedModule = ModuleMap::KnownHeader(); |
981 | 0 | } |
982 | 0 | break; |
983 | 0 | } |
984 | 0 | } |
985 | 0 | First = false; |
986 | 0 | } |
987 | 0 | } |
988 | | |
989 | 0 | CurDir = nullptr; |
990 | | |
991 | | // If this is a system #include, ignore the user #include locs. |
992 | 0 | ConstSearchDirIterator It = |
993 | 0 | isAngled ? angled_dir_begin() : search_dir_begin(); |
994 | | |
995 | | // If this is a #include_next request, start searching after the directory the |
996 | | // file was found in. |
997 | 0 | if (FromDir) |
998 | 0 | It = FromDir; |
999 | | |
1000 | | // Cache all of the lookups performed by this method. Many headers are |
1001 | | // multiply included, and the "pragma once" optimization prevents them from |
1002 | | // being relex/pp'd, but they would still have to search through a |
1003 | | // (potentially huge) series of SearchDirs to find it. |
1004 | 0 | LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename]; |
1005 | |
|
1006 | 0 | ConstSearchDirIterator NextIt = std::next(It); |
1007 | |
|
1008 | 0 | if (!SkipCache) { |
1009 | 0 | if (CacheLookup.StartIt == NextIt && |
1010 | 0 | CacheLookup.RequestingModule == RequestingModule) { |
1011 | | // HIT: Skip querying potentially lots of directories for this lookup. |
1012 | 0 | if (CacheLookup.HitIt) |
1013 | 0 | It = CacheLookup.HitIt; |
1014 | 0 | if (CacheLookup.MappedName) { |
1015 | 0 | Filename = CacheLookup.MappedName; |
1016 | 0 | if (IsMapped) |
1017 | 0 | *IsMapped = true; |
1018 | 0 | } |
1019 | 0 | } else { |
1020 | | // MISS: This is the first query, or the previous query didn't match |
1021 | | // our search start. We will fill in our found location below, so prime |
1022 | | // the start point value. |
1023 | 0 | CacheLookup.reset(RequestingModule, /*NewStartIt=*/NextIt); |
1024 | |
|
1025 | 0 | if (It == search_dir_begin() && FirstNonHeaderMapSearchDirIdx > 0) { |
1026 | | // Handle cold misses of user includes in the presence of many header |
1027 | | // maps. We avoid searching perhaps thousands of header maps by |
1028 | | // jumping directly to the correct one or jumping beyond all of them. |
1029 | 0 | auto Iter = SearchDirHeaderMapIndex.find(Filename.lower()); |
1030 | 0 | if (Iter == SearchDirHeaderMapIndex.end()) |
1031 | | // Not in index => Skip to first SearchDir after initial header maps |
1032 | 0 | It = search_dir_nth(FirstNonHeaderMapSearchDirIdx); |
1033 | 0 | else |
1034 | | // In index => Start with a specific header map |
1035 | 0 | It = search_dir_nth(Iter->second); |
1036 | 0 | } |
1037 | 0 | } |
1038 | 0 | } else { |
1039 | 0 | CacheLookup.reset(RequestingModule, /*NewStartIt=*/NextIt); |
1040 | 0 | } |
1041 | |
|
1042 | 0 | SmallString<64> MappedName; |
1043 | | |
1044 | | // Check each directory in sequence to see if it contains this file. |
1045 | 0 | for (; It != search_dir_end(); ++It) { |
1046 | 0 | bool InUserSpecifiedSystemFramework = false; |
1047 | 0 | bool IsInHeaderMap = false; |
1048 | 0 | bool IsFrameworkFoundInDir = false; |
1049 | 0 | OptionalFileEntryRef File = It->LookupFile( |
1050 | 0 | Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule, |
1051 | 0 | SuggestedModule, InUserSpecifiedSystemFramework, IsFrameworkFoundInDir, |
1052 | 0 | IsInHeaderMap, MappedName, OpenFile); |
1053 | 0 | if (!MappedName.empty()) { |
1054 | 0 | assert(IsInHeaderMap && "MappedName should come from a header map"); |
1055 | 0 | CacheLookup.MappedName = |
1056 | 0 | copyString(MappedName, LookupFileCache.getAllocator()); |
1057 | 0 | } |
1058 | 0 | if (IsMapped) |
1059 | | // A filename is mapped when a header map remapped it to a relative path |
1060 | | // used in subsequent header search or to an absolute path pointing to an |
1061 | | // existing file. |
1062 | 0 | *IsMapped |= (!MappedName.empty() || (IsInHeaderMap && File)); |
1063 | 0 | if (IsFrameworkFound) |
1064 | | // Because we keep a filename remapped for subsequent search directory |
1065 | | // lookups, ignore IsFrameworkFoundInDir after the first remapping and not |
1066 | | // just for remapping in a current search directory. |
1067 | 0 | *IsFrameworkFound |= (IsFrameworkFoundInDir && !CacheLookup.MappedName); |
1068 | 0 | if (!File) |
1069 | 0 | continue; |
1070 | | |
1071 | 0 | CurDir = It; |
1072 | |
|
1073 | 0 | IncludeNames[*File] = Filename; |
1074 | | |
1075 | | // This file is a system header or C++ unfriendly if the dir is. |
1076 | 0 | HeaderFileInfo &HFI = getFileInfo(*File); |
1077 | 0 | HFI.DirInfo = CurDir->getDirCharacteristic(); |
1078 | | |
1079 | | // If the directory characteristic is User but this framework was |
1080 | | // user-specified to be treated as a system framework, promote the |
1081 | | // characteristic. |
1082 | 0 | if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework) |
1083 | 0 | HFI.DirInfo = SrcMgr::C_System; |
1084 | | |
1085 | | // If the filename matches a known system header prefix, override |
1086 | | // whether the file is a system header. |
1087 | 0 | for (unsigned j = SystemHeaderPrefixes.size(); j; --j) { |
1088 | 0 | if (Filename.starts_with(SystemHeaderPrefixes[j - 1].first)) { |
1089 | 0 | HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System |
1090 | 0 | : SrcMgr::C_User; |
1091 | 0 | break; |
1092 | 0 | } |
1093 | 0 | } |
1094 | | |
1095 | | // Set the `Framework` info if this file is in a header map with framework |
1096 | | // style include spelling or found in a framework dir. The header map case |
1097 | | // is possible when building frameworks which use header maps. |
1098 | 0 | if (CurDir->isHeaderMap() && isAngled) { |
1099 | 0 | size_t SlashPos = Filename.find('/'); |
1100 | 0 | if (SlashPos != StringRef::npos) |
1101 | 0 | HFI.Framework = |
1102 | 0 | getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos)); |
1103 | 0 | if (CurDir->isIndexHeaderMap()) |
1104 | 0 | HFI.IndexHeaderMapHeader = 1; |
1105 | 0 | } else if (CurDir->isFramework()) { |
1106 | 0 | size_t SlashPos = Filename.find('/'); |
1107 | 0 | if (SlashPos != StringRef::npos) |
1108 | 0 | HFI.Framework = |
1109 | 0 | getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos)); |
1110 | 0 | } |
1111 | |
|
1112 | 0 | if (checkMSVCHeaderSearch(Diags, MSFE, &File->getFileEntry(), IncludeLoc)) { |
1113 | 0 | if (SuggestedModule) |
1114 | 0 | *SuggestedModule = MSSuggestedModule; |
1115 | 0 | return MSFE; |
1116 | 0 | } |
1117 | | |
1118 | 0 | bool FoundByHeaderMap = !IsMapped ? false : *IsMapped; |
1119 | 0 | if (!Includers.empty()) |
1120 | 0 | diagnoseFrameworkInclude(Diags, IncludeLoc, |
1121 | 0 | Includers.front().second.getName(), Filename, |
1122 | 0 | *File, isAngled, FoundByHeaderMap); |
1123 | | |
1124 | | // Remember this location for the next lookup we do. |
1125 | 0 | cacheLookupSuccess(CacheLookup, It, IncludeLoc); |
1126 | 0 | return File; |
1127 | 0 | } |
1128 | | |
1129 | | // If we are including a file with a quoted include "foo.h" from inside |
1130 | | // a header in a framework that is currently being built, and we couldn't |
1131 | | // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where |
1132 | | // "Foo" is the name of the framework in which the including header was found. |
1133 | 0 | if (!Includers.empty() && Includers.front().first && !isAngled && |
1134 | 0 | !Filename.contains('/')) { |
1135 | 0 | HeaderFileInfo &IncludingHFI = getFileInfo(*Includers.front().first); |
1136 | 0 | if (IncludingHFI.IndexHeaderMapHeader) { |
1137 | 0 | SmallString<128> ScratchFilename; |
1138 | 0 | ScratchFilename += IncludingHFI.Framework; |
1139 | 0 | ScratchFilename += '/'; |
1140 | 0 | ScratchFilename += Filename; |
1141 | |
|
1142 | 0 | OptionalFileEntryRef File = LookupFile( |
1143 | 0 | ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, &CurDir, |
1144 | 0 | Includers.front(), SearchPath, RelativePath, RequestingModule, |
1145 | 0 | SuggestedModule, IsMapped, /*IsFrameworkFound=*/nullptr); |
1146 | |
|
1147 | 0 | if (checkMSVCHeaderSearch(Diags, MSFE, |
1148 | 0 | File ? &File->getFileEntry() : nullptr, |
1149 | 0 | IncludeLoc)) { |
1150 | 0 | if (SuggestedModule) |
1151 | 0 | *SuggestedModule = MSSuggestedModule; |
1152 | 0 | return MSFE; |
1153 | 0 | } |
1154 | | |
1155 | 0 | cacheLookupSuccess(LookupFileCache[Filename], |
1156 | 0 | LookupFileCache[ScratchFilename].HitIt, IncludeLoc); |
1157 | | // FIXME: SuggestedModule. |
1158 | 0 | return File; |
1159 | 0 | } |
1160 | 0 | } |
1161 | | |
1162 | 0 | if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) { |
1163 | 0 | if (SuggestedModule) |
1164 | 0 | *SuggestedModule = MSSuggestedModule; |
1165 | 0 | return MSFE; |
1166 | 0 | } |
1167 | | |
1168 | | // Otherwise, didn't find it. Remember we didn't find this. |
1169 | 0 | CacheLookup.HitIt = search_dir_end(); |
1170 | 0 | return std::nullopt; |
1171 | 0 | } |
1172 | | |
1173 | | /// LookupSubframeworkHeader - Look up a subframework for the specified |
1174 | | /// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from |
1175 | | /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox |
1176 | | /// is a subframework within Carbon.framework. If so, return the FileEntry |
1177 | | /// for the designated file, otherwise return null. |
1178 | | OptionalFileEntryRef HeaderSearch::LookupSubframeworkHeader( |
1179 | | StringRef Filename, FileEntryRef ContextFileEnt, |
1180 | | SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, |
1181 | 0 | Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule) { |
1182 | | // Framework names must have a '/' in the filename. Find it. |
1183 | | // FIXME: Should we permit '\' on Windows? |
1184 | 0 | size_t SlashPos = Filename.find('/'); |
1185 | 0 | if (SlashPos == StringRef::npos) |
1186 | 0 | return std::nullopt; |
1187 | | |
1188 | | // Look up the base framework name of the ContextFileEnt. |
1189 | 0 | StringRef ContextName = ContextFileEnt.getName(); |
1190 | | |
1191 | | // If the context info wasn't a framework, couldn't be a subframework. |
1192 | 0 | const unsigned DotFrameworkLen = 10; |
1193 | 0 | auto FrameworkPos = ContextName.find(".framework"); |
1194 | 0 | if (FrameworkPos == StringRef::npos || |
1195 | 0 | (ContextName[FrameworkPos + DotFrameworkLen] != '/' && |
1196 | 0 | ContextName[FrameworkPos + DotFrameworkLen] != '\\')) |
1197 | 0 | return std::nullopt; |
1198 | | |
1199 | 0 | SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() + |
1200 | 0 | FrameworkPos + |
1201 | 0 | DotFrameworkLen + 1); |
1202 | | |
1203 | | // Append Frameworks/HIToolbox.framework/ |
1204 | 0 | FrameworkName += "Frameworks/"; |
1205 | 0 | FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos); |
1206 | 0 | FrameworkName += ".framework/"; |
1207 | |
|
1208 | 0 | auto &CacheLookup = |
1209 | 0 | *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos), |
1210 | 0 | FrameworkCacheEntry())).first; |
1211 | | |
1212 | | // Some other location? |
1213 | 0 | if (CacheLookup.second.Directory && |
1214 | 0 | CacheLookup.first().size() == FrameworkName.size() && |
1215 | 0 | memcmp(CacheLookup.first().data(), &FrameworkName[0], |
1216 | 0 | CacheLookup.first().size()) != 0) |
1217 | 0 | return std::nullopt; |
1218 | | |
1219 | | // Cache subframework. |
1220 | 0 | if (!CacheLookup.second.Directory) { |
1221 | 0 | ++NumSubFrameworkLookups; |
1222 | | |
1223 | | // If the framework dir doesn't exist, we fail. |
1224 | 0 | auto Dir = FileMgr.getOptionalDirectoryRef(FrameworkName); |
1225 | 0 | if (!Dir) |
1226 | 0 | return std::nullopt; |
1227 | | |
1228 | | // Otherwise, if it does, remember that this is the right direntry for this |
1229 | | // framework. |
1230 | 0 | CacheLookup.second.Directory = Dir; |
1231 | 0 | } |
1232 | | |
1233 | | |
1234 | 0 | if (RelativePath) { |
1235 | 0 | RelativePath->clear(); |
1236 | 0 | RelativePath->append(Filename.begin()+SlashPos+1, Filename.end()); |
1237 | 0 | } |
1238 | | |
1239 | | // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h" |
1240 | 0 | SmallString<1024> HeadersFilename(FrameworkName); |
1241 | 0 | HeadersFilename += "Headers/"; |
1242 | 0 | if (SearchPath) { |
1243 | 0 | SearchPath->clear(); |
1244 | | // Without trailing '/'. |
1245 | 0 | SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1); |
1246 | 0 | } |
1247 | |
|
1248 | 0 | HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end()); |
1249 | 0 | auto File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true); |
1250 | 0 | if (!File) { |
1251 | | // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h" |
1252 | 0 | HeadersFilename = FrameworkName; |
1253 | 0 | HeadersFilename += "PrivateHeaders/"; |
1254 | 0 | if (SearchPath) { |
1255 | 0 | SearchPath->clear(); |
1256 | | // Without trailing '/'. |
1257 | 0 | SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1); |
1258 | 0 | } |
1259 | |
|
1260 | 0 | HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end()); |
1261 | 0 | File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true); |
1262 | |
|
1263 | 0 | if (!File) |
1264 | 0 | return std::nullopt; |
1265 | 0 | } |
1266 | | |
1267 | | // This file is a system header or C++ unfriendly if the old file is. |
1268 | | // |
1269 | | // Note that the temporary 'DirInfo' is required here, as either call to |
1270 | | // getFileInfo could resize the vector and we don't want to rely on order |
1271 | | // of evaluation. |
1272 | 0 | unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo; |
1273 | 0 | getFileInfo(*File).DirInfo = DirInfo; |
1274 | |
|
1275 | 0 | FrameworkName.pop_back(); // remove the trailing '/' |
1276 | 0 | if (!findUsableModuleForFrameworkHeader(*File, FrameworkName, |
1277 | 0 | RequestingModule, SuggestedModule, |
1278 | 0 | /*IsSystem*/ false)) |
1279 | 0 | return std::nullopt; |
1280 | | |
1281 | 0 | return *File; |
1282 | 0 | } |
1283 | | |
1284 | | //===----------------------------------------------------------------------===// |
1285 | | // File Info Management. |
1286 | | //===----------------------------------------------------------------------===// |
1287 | | |
1288 | | /// Merge the header file info provided by \p OtherHFI into the current |
1289 | | /// header file info (\p HFI) |
1290 | | static void mergeHeaderFileInfo(HeaderFileInfo &HFI, |
1291 | 0 | const HeaderFileInfo &OtherHFI) { |
1292 | 0 | assert(OtherHFI.External && "expected to merge external HFI"); |
1293 | | |
1294 | 0 | HFI.isImport |= OtherHFI.isImport; |
1295 | 0 | HFI.isPragmaOnce |= OtherHFI.isPragmaOnce; |
1296 | 0 | HFI.isModuleHeader |= OtherHFI.isModuleHeader; |
1297 | |
|
1298 | 0 | if (!HFI.ControllingMacro && !HFI.ControllingMacroID) { |
1299 | 0 | HFI.ControllingMacro = OtherHFI.ControllingMacro; |
1300 | 0 | HFI.ControllingMacroID = OtherHFI.ControllingMacroID; |
1301 | 0 | } |
1302 | |
|
1303 | 0 | HFI.DirInfo = OtherHFI.DirInfo; |
1304 | 0 | HFI.External = (!HFI.IsValid || HFI.External); |
1305 | 0 | HFI.IsValid = true; |
1306 | 0 | HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader; |
1307 | |
|
1308 | 0 | if (HFI.Framework.empty()) |
1309 | 0 | HFI.Framework = OtherHFI.Framework; |
1310 | 0 | } |
1311 | | |
1312 | | /// getFileInfo - Return the HeaderFileInfo structure for the specified |
1313 | | /// FileEntry. |
1314 | 46 | HeaderFileInfo &HeaderSearch::getFileInfo(FileEntryRef FE) { |
1315 | 46 | if (FE.getUID() >= FileInfo.size()) |
1316 | 46 | FileInfo.resize(FE.getUID() + 1); |
1317 | | |
1318 | 46 | HeaderFileInfo *HFI = &FileInfo[FE.getUID()]; |
1319 | | // FIXME: Use a generation count to check whether this is really up to date. |
1320 | 46 | if (ExternalSource && !HFI->Resolved) { |
1321 | 0 | auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE); |
1322 | 0 | if (ExternalHFI.IsValid) { |
1323 | 0 | HFI->Resolved = true; |
1324 | 0 | if (ExternalHFI.External) |
1325 | 0 | mergeHeaderFileInfo(*HFI, ExternalHFI); |
1326 | 0 | } |
1327 | 0 | } |
1328 | | |
1329 | 46 | HFI->IsValid = true; |
1330 | | // We have local information about this header file, so it's no longer |
1331 | | // strictly external. |
1332 | 46 | HFI->External = false; |
1333 | 46 | return *HFI; |
1334 | 46 | } |
1335 | | |
1336 | | const HeaderFileInfo * |
1337 | 0 | HeaderSearch::getExistingFileInfo(FileEntryRef FE, bool WantExternal) const { |
1338 | | // If we have an external source, ensure we have the latest information. |
1339 | | // FIXME: Use a generation count to check whether this is really up to date. |
1340 | 0 | HeaderFileInfo *HFI; |
1341 | 0 | if (ExternalSource) { |
1342 | 0 | if (FE.getUID() >= FileInfo.size()) { |
1343 | 0 | if (!WantExternal) |
1344 | 0 | return nullptr; |
1345 | 0 | FileInfo.resize(FE.getUID() + 1); |
1346 | 0 | } |
1347 | | |
1348 | 0 | HFI = &FileInfo[FE.getUID()]; |
1349 | 0 | if (!WantExternal && (!HFI->IsValid || HFI->External)) |
1350 | 0 | return nullptr; |
1351 | 0 | if (!HFI->Resolved) { |
1352 | 0 | auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE); |
1353 | 0 | if (ExternalHFI.IsValid) { |
1354 | 0 | HFI->Resolved = true; |
1355 | 0 | if (ExternalHFI.External) |
1356 | 0 | mergeHeaderFileInfo(*HFI, ExternalHFI); |
1357 | 0 | } |
1358 | 0 | } |
1359 | 0 | } else if (FE.getUID() >= FileInfo.size()) { |
1360 | 0 | return nullptr; |
1361 | 0 | } else { |
1362 | 0 | HFI = &FileInfo[FE.getUID()]; |
1363 | 0 | } |
1364 | | |
1365 | 0 | if (!HFI->IsValid || (HFI->External && !WantExternal)) |
1366 | 0 | return nullptr; |
1367 | | |
1368 | 0 | return HFI; |
1369 | 0 | } |
1370 | | |
1371 | 0 | bool HeaderSearch::isFileMultipleIncludeGuarded(FileEntryRef File) const { |
1372 | | // Check if we've entered this file and found an include guard or #pragma |
1373 | | // once. Note that we dor't check for #import, because that's not a property |
1374 | | // of the file itself. |
1375 | 0 | if (auto *HFI = getExistingFileInfo(File)) |
1376 | 0 | return HFI->isPragmaOnce || HFI->ControllingMacro || |
1377 | 0 | HFI->ControllingMacroID; |
1378 | 0 | return false; |
1379 | 0 | } |
1380 | | |
1381 | | void HeaderSearch::MarkFileModuleHeader(FileEntryRef FE, |
1382 | | ModuleMap::ModuleHeaderRole Role, |
1383 | 0 | bool isCompilingModuleHeader) { |
1384 | 0 | bool isModularHeader = ModuleMap::isModular(Role); |
1385 | | |
1386 | | // Don't mark the file info as non-external if there's nothing to change. |
1387 | 0 | if (!isCompilingModuleHeader) { |
1388 | 0 | if (!isModularHeader) |
1389 | 0 | return; |
1390 | 0 | auto *HFI = getExistingFileInfo(FE); |
1391 | 0 | if (HFI && HFI->isModuleHeader) |
1392 | 0 | return; |
1393 | 0 | } |
1394 | | |
1395 | 0 | auto &HFI = getFileInfo(FE); |
1396 | 0 | HFI.isModuleHeader |= isModularHeader; |
1397 | 0 | HFI.isCompilingModuleHeader |= isCompilingModuleHeader; |
1398 | 0 | } |
1399 | | |
1400 | | bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP, |
1401 | | FileEntryRef File, bool isImport, |
1402 | | bool ModulesEnabled, Module *M, |
1403 | 0 | bool &IsFirstIncludeOfFile) { |
1404 | 0 | ++NumIncluded; // Count # of attempted #includes. |
1405 | |
|
1406 | 0 | IsFirstIncludeOfFile = false; |
1407 | | |
1408 | | // Get information about this file. |
1409 | 0 | HeaderFileInfo &FileInfo = getFileInfo(File); |
1410 | | |
1411 | | // FIXME: this is a workaround for the lack of proper modules-aware support |
1412 | | // for #import / #pragma once |
1413 | 0 | auto TryEnterImported = [&]() -> bool { |
1414 | 0 | if (!ModulesEnabled) |
1415 | 0 | return false; |
1416 | | // Ensure FileInfo bits are up to date. |
1417 | 0 | ModMap.resolveHeaderDirectives(File); |
1418 | | // Modules with builtins are special; multiple modules use builtins as |
1419 | | // modular headers, example: |
1420 | | // |
1421 | | // module stddef { header "stddef.h" export * } |
1422 | | // |
1423 | | // After module map parsing, this expands to: |
1424 | | // |
1425 | | // module stddef { |
1426 | | // header "/path_to_builtin_dirs/stddef.h" |
1427 | | // textual "stddef.h" |
1428 | | // } |
1429 | | // |
1430 | | // It's common that libc++ and system modules will both define such |
1431 | | // submodules. Make sure cached results for a builtin header won't |
1432 | | // prevent other builtin modules from potentially entering the builtin |
1433 | | // header. Note that builtins are header guarded and the decision to |
1434 | | // actually enter them is postponed to the controlling macros logic below. |
1435 | 0 | bool TryEnterHdr = false; |
1436 | 0 | if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader) |
1437 | 0 | TryEnterHdr = ModMap.isBuiltinHeader(File); |
1438 | | |
1439 | | // Textual headers can be #imported from different modules. Since ObjC |
1440 | | // headers find in the wild might rely only on #import and do not contain |
1441 | | // controlling macros, be conservative and only try to enter textual headers |
1442 | | // if such macro is present. |
1443 | 0 | if (!FileInfo.isModuleHeader && |
1444 | 0 | FileInfo.getControllingMacro(ExternalLookup)) |
1445 | 0 | TryEnterHdr = true; |
1446 | 0 | return TryEnterHdr; |
1447 | 0 | }; |
1448 | | |
1449 | | // If this is a #import directive, check that we have not already imported |
1450 | | // this header. |
1451 | 0 | if (isImport) { |
1452 | | // If this has already been imported, don't import it again. |
1453 | 0 | FileInfo.isImport = true; |
1454 | | |
1455 | | // Has this already been #import'ed or #include'd? |
1456 | 0 | if (PP.alreadyIncluded(File) && !TryEnterImported()) |
1457 | 0 | return false; |
1458 | 0 | } else { |
1459 | | // Otherwise, if this is a #include of a file that was previously #import'd |
1460 | | // or if this is the second #include of a #pragma once file, ignore it. |
1461 | 0 | if ((FileInfo.isPragmaOnce || FileInfo.isImport) && !TryEnterImported()) |
1462 | 0 | return false; |
1463 | 0 | } |
1464 | | |
1465 | | // Next, check to see if the file is wrapped with #ifndef guards. If so, and |
1466 | | // if the macro that guards it is defined, we know the #include has no effect. |
1467 | 0 | if (const IdentifierInfo *ControllingMacro |
1468 | 0 | = FileInfo.getControllingMacro(ExternalLookup)) { |
1469 | | // If the header corresponds to a module, check whether the macro is already |
1470 | | // defined in that module rather than checking in the current set of visible |
1471 | | // modules. |
1472 | 0 | if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M) |
1473 | 0 | : PP.isMacroDefined(ControllingMacro)) { |
1474 | 0 | ++NumMultiIncludeFileOptzn; |
1475 | 0 | return false; |
1476 | 0 | } |
1477 | 0 | } |
1478 | | |
1479 | 0 | IsFirstIncludeOfFile = PP.markIncluded(File); |
1480 | |
|
1481 | 0 | return true; |
1482 | 0 | } |
1483 | | |
1484 | 0 | size_t HeaderSearch::getTotalMemory() const { |
1485 | 0 | return SearchDirs.capacity() |
1486 | 0 | + llvm::capacity_in_bytes(FileInfo) |
1487 | 0 | + llvm::capacity_in_bytes(HeaderMaps) |
1488 | 0 | + LookupFileCache.getAllocator().getTotalMemory() |
1489 | 0 | + FrameworkMap.getAllocator().getTotalMemory(); |
1490 | 0 | } |
1491 | | |
1492 | 0 | unsigned HeaderSearch::searchDirIdx(const DirectoryLookup &DL) const { |
1493 | 0 | return &DL - &*SearchDirs.begin(); |
1494 | 0 | } |
1495 | | |
1496 | 0 | StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) { |
1497 | 0 | return FrameworkNames.insert(Framework).first->first(); |
1498 | 0 | } |
1499 | | |
1500 | 0 | StringRef HeaderSearch::getIncludeNameForHeader(const FileEntry *File) const { |
1501 | 0 | auto It = IncludeNames.find(File); |
1502 | 0 | if (It == IncludeNames.end()) |
1503 | 0 | return {}; |
1504 | 0 | return It->second; |
1505 | 0 | } |
1506 | | |
1507 | | bool HeaderSearch::hasModuleMap(StringRef FileName, |
1508 | | const DirectoryEntry *Root, |
1509 | 0 | bool IsSystem) { |
1510 | 0 | if (!HSOpts->ImplicitModuleMaps) |
1511 | 0 | return false; |
1512 | | |
1513 | 0 | SmallVector<const DirectoryEntry *, 2> FixUpDirectories; |
1514 | |
|
1515 | 0 | StringRef DirName = FileName; |
1516 | 0 | do { |
1517 | | // Get the parent directory name. |
1518 | 0 | DirName = llvm::sys::path::parent_path(DirName); |
1519 | 0 | if (DirName.empty()) |
1520 | 0 | return false; |
1521 | | |
1522 | | // Determine whether this directory exists. |
1523 | 0 | auto Dir = FileMgr.getOptionalDirectoryRef(DirName); |
1524 | 0 | if (!Dir) |
1525 | 0 | return false; |
1526 | | |
1527 | | // Try to load the module map file in this directory. |
1528 | 0 | switch (loadModuleMapFile(*Dir, IsSystem, |
1529 | 0 | llvm::sys::path::extension(Dir->getName()) == |
1530 | 0 | ".framework")) { |
1531 | 0 | case LMM_NewlyLoaded: |
1532 | 0 | case LMM_AlreadyLoaded: |
1533 | | // Success. All of the directories we stepped through inherit this module |
1534 | | // map file. |
1535 | 0 | for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I) |
1536 | 0 | DirectoryHasModuleMap[FixUpDirectories[I]] = true; |
1537 | 0 | return true; |
1538 | | |
1539 | 0 | case LMM_NoDirectory: |
1540 | 0 | case LMM_InvalidModuleMap: |
1541 | 0 | break; |
1542 | 0 | } |
1543 | | |
1544 | | // If we hit the top of our search, we're done. |
1545 | 0 | if (*Dir == Root) |
1546 | 0 | return false; |
1547 | | |
1548 | | // Keep track of all of the directories we checked, so we can mark them as |
1549 | | // having module maps if we eventually do find a module map. |
1550 | 0 | FixUpDirectories.push_back(*Dir); |
1551 | 0 | } while (true); |
1552 | 0 | } |
1553 | | |
1554 | | ModuleMap::KnownHeader |
1555 | | HeaderSearch::findModuleForHeader(FileEntryRef File, bool AllowTextual, |
1556 | 0 | bool AllowExcluded) const { |
1557 | 0 | if (ExternalSource) { |
1558 | | // Make sure the external source has handled header info about this file, |
1559 | | // which includes whether the file is part of a module. |
1560 | 0 | (void)getExistingFileInfo(File); |
1561 | 0 | } |
1562 | 0 | return ModMap.findModuleForHeader(File, AllowTextual, AllowExcluded); |
1563 | 0 | } |
1564 | | |
1565 | | ArrayRef<ModuleMap::KnownHeader> |
1566 | 0 | HeaderSearch::findAllModulesForHeader(FileEntryRef File) const { |
1567 | 0 | if (ExternalSource) { |
1568 | | // Make sure the external source has handled header info about this file, |
1569 | | // which includes whether the file is part of a module. |
1570 | 0 | (void)getExistingFileInfo(File); |
1571 | 0 | } |
1572 | 0 | return ModMap.findAllModulesForHeader(File); |
1573 | 0 | } |
1574 | | |
1575 | | ArrayRef<ModuleMap::KnownHeader> |
1576 | 0 | HeaderSearch::findResolvedModulesForHeader(FileEntryRef File) const { |
1577 | 0 | if (ExternalSource) { |
1578 | | // Make sure the external source has handled header info about this file, |
1579 | | // which includes whether the file is part of a module. |
1580 | 0 | (void)getExistingFileInfo(File); |
1581 | 0 | } |
1582 | 0 | return ModMap.findResolvedModulesForHeader(File); |
1583 | 0 | } |
1584 | | |
1585 | | static bool suggestModule(HeaderSearch &HS, FileEntryRef File, |
1586 | | Module *RequestingModule, |
1587 | 0 | ModuleMap::KnownHeader *SuggestedModule) { |
1588 | 0 | ModuleMap::KnownHeader Module = |
1589 | 0 | HS.findModuleForHeader(File, /*AllowTextual*/true); |
1590 | | |
1591 | | // If this module specifies [no_undeclared_includes], we cannot find any |
1592 | | // file that's in a non-dependency module. |
1593 | 0 | if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) { |
1594 | 0 | HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/ false); |
1595 | 0 | if (!RequestingModule->directlyUses(Module.getModule())) { |
1596 | | // Builtin headers are a special case. Multiple modules can use the same |
1597 | | // builtin as a modular header (see also comment in |
1598 | | // ShouldEnterIncludeFile()), so the builtin header may have been |
1599 | | // "claimed" by an unrelated module. This shouldn't prevent us from |
1600 | | // including the builtin header textually in this module. |
1601 | 0 | if (HS.getModuleMap().isBuiltinHeader(File)) { |
1602 | 0 | if (SuggestedModule) |
1603 | 0 | *SuggestedModule = ModuleMap::KnownHeader(); |
1604 | 0 | return true; |
1605 | 0 | } |
1606 | | // TODO: Add this module (or just its module map file) into something like |
1607 | | // `RequestingModule->AffectingClangModules`. |
1608 | 0 | return false; |
1609 | 0 | } |
1610 | 0 | } |
1611 | | |
1612 | 0 | if (SuggestedModule) |
1613 | 0 | *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader) |
1614 | 0 | ? ModuleMap::KnownHeader() |
1615 | 0 | : Module; |
1616 | |
|
1617 | 0 | return true; |
1618 | 0 | } |
1619 | | |
1620 | | bool HeaderSearch::findUsableModuleForHeader( |
1621 | | FileEntryRef File, const DirectoryEntry *Root, Module *RequestingModule, |
1622 | 0 | ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) { |
1623 | 0 | if (needModuleLookup(RequestingModule, SuggestedModule)) { |
1624 | | // If there is a module that corresponds to this header, suggest it. |
1625 | 0 | hasModuleMap(File.getNameAsRequested(), Root, IsSystemHeaderDir); |
1626 | 0 | return suggestModule(*this, File, RequestingModule, SuggestedModule); |
1627 | 0 | } |
1628 | 0 | return true; |
1629 | 0 | } |
1630 | | |
1631 | | bool HeaderSearch::findUsableModuleForFrameworkHeader( |
1632 | | FileEntryRef File, StringRef FrameworkName, Module *RequestingModule, |
1633 | 0 | ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) { |
1634 | | // If we're supposed to suggest a module, look for one now. |
1635 | 0 | if (needModuleLookup(RequestingModule, SuggestedModule)) { |
1636 | | // Find the top-level framework based on this framework. |
1637 | 0 | SmallVector<std::string, 4> SubmodulePath; |
1638 | 0 | OptionalDirectoryEntryRef TopFrameworkDir = |
1639 | 0 | ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath); |
1640 | 0 | assert(TopFrameworkDir && "Could not find the top-most framework dir"); |
1641 | | |
1642 | | // Determine the name of the top-level framework. |
1643 | 0 | StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName()); |
1644 | | |
1645 | | // Load this framework module. If that succeeds, find the suggested module |
1646 | | // for this header, if any. |
1647 | 0 | loadFrameworkModule(ModuleName, *TopFrameworkDir, IsSystemFramework); |
1648 | | |
1649 | | // FIXME: This can find a module not part of ModuleName, which is |
1650 | | // important so that we're consistent about whether this header |
1651 | | // corresponds to a module. Possibly we should lock down framework modules |
1652 | | // so that this is not possible. |
1653 | 0 | return suggestModule(*this, File, RequestingModule, SuggestedModule); |
1654 | 0 | } |
1655 | 0 | return true; |
1656 | 0 | } |
1657 | | |
1658 | | static OptionalFileEntryRef getPrivateModuleMap(FileEntryRef File, |
1659 | | FileManager &FileMgr, |
1660 | 0 | DiagnosticsEngine &Diags) { |
1661 | 0 | StringRef Filename = llvm::sys::path::filename(File.getName()); |
1662 | 0 | SmallString<128> PrivateFilename(File.getDir().getName()); |
1663 | 0 | if (Filename == "module.map") |
1664 | 0 | llvm::sys::path::append(PrivateFilename, "module_private.map"); |
1665 | 0 | else if (Filename == "module.modulemap") |
1666 | 0 | llvm::sys::path::append(PrivateFilename, "module.private.modulemap"); |
1667 | 0 | else |
1668 | 0 | return std::nullopt; |
1669 | 0 | auto PMMFile = FileMgr.getOptionalFileRef(PrivateFilename); |
1670 | 0 | if (PMMFile) { |
1671 | 0 | if (Filename == "module.map") |
1672 | 0 | Diags.Report(diag::warn_deprecated_module_dot_map) |
1673 | 0 | << PrivateFilename << 1 |
1674 | 0 | << File.getDir().getName().ends_with(".framework"); |
1675 | 0 | } |
1676 | 0 | return PMMFile; |
1677 | 0 | } |
1678 | | |
1679 | | bool HeaderSearch::loadModuleMapFile(FileEntryRef File, bool IsSystem, |
1680 | | FileID ID, unsigned *Offset, |
1681 | 0 | StringRef OriginalModuleMapFile) { |
1682 | | // Find the directory for the module. For frameworks, that may require going |
1683 | | // up from the 'Modules' directory. |
1684 | 0 | OptionalDirectoryEntryRef Dir; |
1685 | 0 | if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) { |
1686 | 0 | Dir = FileMgr.getOptionalDirectoryRef("."); |
1687 | 0 | } else { |
1688 | 0 | if (!OriginalModuleMapFile.empty()) { |
1689 | | // We're building a preprocessed module map. Find or invent the directory |
1690 | | // that it originally occupied. |
1691 | 0 | Dir = FileMgr.getOptionalDirectoryRef( |
1692 | 0 | llvm::sys::path::parent_path(OriginalModuleMapFile)); |
1693 | 0 | if (!Dir) { |
1694 | 0 | auto FakeFile = FileMgr.getVirtualFileRef(OriginalModuleMapFile, 0, 0); |
1695 | 0 | Dir = FakeFile.getDir(); |
1696 | 0 | } |
1697 | 0 | } else { |
1698 | 0 | Dir = File.getDir(); |
1699 | 0 | } |
1700 | |
|
1701 | 0 | assert(Dir && "parent must exist"); |
1702 | 0 | StringRef DirName(Dir->getName()); |
1703 | 0 | if (llvm::sys::path::filename(DirName) == "Modules") { |
1704 | 0 | DirName = llvm::sys::path::parent_path(DirName); |
1705 | 0 | if (DirName.ends_with(".framework")) |
1706 | 0 | if (auto MaybeDir = FileMgr.getOptionalDirectoryRef(DirName)) |
1707 | 0 | Dir = *MaybeDir; |
1708 | | // FIXME: This assert can fail if there's a race between the above check |
1709 | | // and the removal of the directory. |
1710 | 0 | assert(Dir && "parent must exist"); |
1711 | 0 | } |
1712 | 0 | } |
1713 | | |
1714 | 0 | assert(Dir && "module map home directory must exist"); |
1715 | 0 | switch (loadModuleMapFileImpl(File, IsSystem, *Dir, ID, Offset)) { |
1716 | 0 | case LMM_AlreadyLoaded: |
1717 | 0 | case LMM_NewlyLoaded: |
1718 | 0 | return false; |
1719 | 0 | case LMM_NoDirectory: |
1720 | 0 | case LMM_InvalidModuleMap: |
1721 | 0 | return true; |
1722 | 0 | } |
1723 | 0 | llvm_unreachable("Unknown load module map result"); |
1724 | 0 | } |
1725 | | |
1726 | | HeaderSearch::LoadModuleMapResult |
1727 | | HeaderSearch::loadModuleMapFileImpl(FileEntryRef File, bool IsSystem, |
1728 | | DirectoryEntryRef Dir, FileID ID, |
1729 | 0 | unsigned *Offset) { |
1730 | | // Check whether we've already loaded this module map, and mark it as being |
1731 | | // loaded in case we recursively try to load it from itself. |
1732 | 0 | auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true)); |
1733 | 0 | if (!AddResult.second) |
1734 | 0 | return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap; |
1735 | | |
1736 | 0 | if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) { |
1737 | 0 | LoadedModuleMaps[File] = false; |
1738 | 0 | return LMM_InvalidModuleMap; |
1739 | 0 | } |
1740 | | |
1741 | | // Try to load a corresponding private module map. |
1742 | 0 | if (OptionalFileEntryRef PMMFile = |
1743 | 0 | getPrivateModuleMap(File, FileMgr, Diags)) { |
1744 | 0 | if (ModMap.parseModuleMapFile(*PMMFile, IsSystem, Dir)) { |
1745 | 0 | LoadedModuleMaps[File] = false; |
1746 | 0 | return LMM_InvalidModuleMap; |
1747 | 0 | } |
1748 | 0 | } |
1749 | | |
1750 | | // This directory has a module map. |
1751 | 0 | return LMM_NewlyLoaded; |
1752 | 0 | } |
1753 | | |
1754 | | OptionalFileEntryRef |
1755 | 0 | HeaderSearch::lookupModuleMapFile(DirectoryEntryRef Dir, bool IsFramework) { |
1756 | 0 | if (!HSOpts->ImplicitModuleMaps) |
1757 | 0 | return std::nullopt; |
1758 | | // For frameworks, the preferred spelling is Modules/module.modulemap, but |
1759 | | // module.map at the framework root is also accepted. |
1760 | 0 | SmallString<128> ModuleMapFileName(Dir.getName()); |
1761 | 0 | if (IsFramework) |
1762 | 0 | llvm::sys::path::append(ModuleMapFileName, "Modules"); |
1763 | 0 | llvm::sys::path::append(ModuleMapFileName, "module.modulemap"); |
1764 | 0 | if (auto F = FileMgr.getOptionalFileRef(ModuleMapFileName)) |
1765 | 0 | return *F; |
1766 | | |
1767 | | // Continue to allow module.map, but warn it's deprecated. |
1768 | 0 | ModuleMapFileName = Dir.getName(); |
1769 | 0 | llvm::sys::path::append(ModuleMapFileName, "module.map"); |
1770 | 0 | if (auto F = FileMgr.getOptionalFileRef(ModuleMapFileName)) { |
1771 | 0 | Diags.Report(diag::warn_deprecated_module_dot_map) |
1772 | 0 | << ModuleMapFileName << 0 << IsFramework; |
1773 | 0 | return *F; |
1774 | 0 | } |
1775 | | |
1776 | | // For frameworks, allow to have a private module map with a preferred |
1777 | | // spelling when a public module map is absent. |
1778 | 0 | if (IsFramework) { |
1779 | 0 | ModuleMapFileName = Dir.getName(); |
1780 | 0 | llvm::sys::path::append(ModuleMapFileName, "Modules", |
1781 | 0 | "module.private.modulemap"); |
1782 | 0 | if (auto F = FileMgr.getOptionalFileRef(ModuleMapFileName)) |
1783 | 0 | return *F; |
1784 | 0 | } |
1785 | 0 | return std::nullopt; |
1786 | 0 | } |
1787 | | |
1788 | | Module *HeaderSearch::loadFrameworkModule(StringRef Name, DirectoryEntryRef Dir, |
1789 | 0 | bool IsSystem) { |
1790 | | // Try to load a module map file. |
1791 | 0 | switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) { |
1792 | 0 | case LMM_InvalidModuleMap: |
1793 | | // Try to infer a module map from the framework directory. |
1794 | 0 | if (HSOpts->ImplicitModuleMaps) |
1795 | 0 | ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr); |
1796 | 0 | break; |
1797 | | |
1798 | 0 | case LMM_NoDirectory: |
1799 | 0 | return nullptr; |
1800 | | |
1801 | 0 | case LMM_AlreadyLoaded: |
1802 | 0 | case LMM_NewlyLoaded: |
1803 | 0 | break; |
1804 | 0 | } |
1805 | | |
1806 | 0 | return ModMap.findModule(Name); |
1807 | 0 | } |
1808 | | |
1809 | | HeaderSearch::LoadModuleMapResult |
1810 | | HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem, |
1811 | 0 | bool IsFramework) { |
1812 | 0 | if (auto Dir = FileMgr.getOptionalDirectoryRef(DirName)) |
1813 | 0 | return loadModuleMapFile(*Dir, IsSystem, IsFramework); |
1814 | | |
1815 | 0 | return LMM_NoDirectory; |
1816 | 0 | } |
1817 | | |
1818 | | HeaderSearch::LoadModuleMapResult |
1819 | | HeaderSearch::loadModuleMapFile(DirectoryEntryRef Dir, bool IsSystem, |
1820 | 0 | bool IsFramework) { |
1821 | 0 | auto KnownDir = DirectoryHasModuleMap.find(Dir); |
1822 | 0 | if (KnownDir != DirectoryHasModuleMap.end()) |
1823 | 0 | return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap; |
1824 | | |
1825 | 0 | if (OptionalFileEntryRef ModuleMapFile = |
1826 | 0 | lookupModuleMapFile(Dir, IsFramework)) { |
1827 | 0 | LoadModuleMapResult Result = |
1828 | 0 | loadModuleMapFileImpl(*ModuleMapFile, IsSystem, Dir); |
1829 | | // Add Dir explicitly in case ModuleMapFile is in a subdirectory. |
1830 | | // E.g. Foo.framework/Modules/module.modulemap |
1831 | | // ^Dir ^ModuleMapFile |
1832 | 0 | if (Result == LMM_NewlyLoaded) |
1833 | 0 | DirectoryHasModuleMap[Dir] = true; |
1834 | 0 | else if (Result == LMM_InvalidModuleMap) |
1835 | 0 | DirectoryHasModuleMap[Dir] = false; |
1836 | 0 | return Result; |
1837 | 0 | } |
1838 | 0 | return LMM_InvalidModuleMap; |
1839 | 0 | } |
1840 | | |
1841 | 0 | void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) { |
1842 | 0 | Modules.clear(); |
1843 | |
|
1844 | 0 | if (HSOpts->ImplicitModuleMaps) { |
1845 | | // Load module maps for each of the header search directories. |
1846 | 0 | for (DirectoryLookup &DL : search_dir_range()) { |
1847 | 0 | bool IsSystem = DL.isSystemHeaderDirectory(); |
1848 | 0 | if (DL.isFramework()) { |
1849 | 0 | std::error_code EC; |
1850 | 0 | SmallString<128> DirNative; |
1851 | 0 | llvm::sys::path::native(DL.getFrameworkDirRef()->getName(), DirNative); |
1852 | | |
1853 | | // Search each of the ".framework" directories to load them as modules. |
1854 | 0 | llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem(); |
1855 | 0 | for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), |
1856 | 0 | DirEnd; |
1857 | 0 | Dir != DirEnd && !EC; Dir.increment(EC)) { |
1858 | 0 | if (llvm::sys::path::extension(Dir->path()) != ".framework") |
1859 | 0 | continue; |
1860 | | |
1861 | 0 | auto FrameworkDir = FileMgr.getOptionalDirectoryRef(Dir->path()); |
1862 | 0 | if (!FrameworkDir) |
1863 | 0 | continue; |
1864 | | |
1865 | | // Load this framework module. |
1866 | 0 | loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir, |
1867 | 0 | IsSystem); |
1868 | 0 | } |
1869 | 0 | continue; |
1870 | 0 | } |
1871 | | |
1872 | | // FIXME: Deal with header maps. |
1873 | 0 | if (DL.isHeaderMap()) |
1874 | 0 | continue; |
1875 | | |
1876 | | // Try to load a module map file for the search directory. |
1877 | 0 | loadModuleMapFile(*DL.getDirRef(), IsSystem, /*IsFramework*/ false); |
1878 | | |
1879 | | // Try to load module map files for immediate subdirectories of this |
1880 | | // search directory. |
1881 | 0 | loadSubdirectoryModuleMaps(DL); |
1882 | 0 | } |
1883 | 0 | } |
1884 | | |
1885 | | // Populate the list of modules. |
1886 | 0 | llvm::transform(ModMap.modules(), std::back_inserter(Modules), |
1887 | 0 | [](const auto &NameAndMod) { return NameAndMod.second; }); |
1888 | 0 | } |
1889 | | |
1890 | 0 | void HeaderSearch::loadTopLevelSystemModules() { |
1891 | 0 | if (!HSOpts->ImplicitModuleMaps) |
1892 | 0 | return; |
1893 | | |
1894 | | // Load module maps for each of the header search directories. |
1895 | 0 | for (const DirectoryLookup &DL : search_dir_range()) { |
1896 | | // We only care about normal header directories. |
1897 | 0 | if (!DL.isNormalDir()) |
1898 | 0 | continue; |
1899 | | |
1900 | | // Try to load a module map file for the search directory. |
1901 | 0 | loadModuleMapFile(*DL.getDirRef(), DL.isSystemHeaderDirectory(), |
1902 | 0 | DL.isFramework()); |
1903 | 0 | } |
1904 | 0 | } |
1905 | | |
1906 | 0 | void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) { |
1907 | 0 | assert(HSOpts->ImplicitModuleMaps && |
1908 | 0 | "Should not be loading subdirectory module maps"); |
1909 | | |
1910 | 0 | if (SearchDir.haveSearchedAllModuleMaps()) |
1911 | 0 | return; |
1912 | | |
1913 | 0 | std::error_code EC; |
1914 | 0 | SmallString<128> Dir = SearchDir.getDirRef()->getName(); |
1915 | 0 | FileMgr.makeAbsolutePath(Dir); |
1916 | 0 | SmallString<128> DirNative; |
1917 | 0 | llvm::sys::path::native(Dir, DirNative); |
1918 | 0 | llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem(); |
1919 | 0 | for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; |
1920 | 0 | Dir != DirEnd && !EC; Dir.increment(EC)) { |
1921 | 0 | if (Dir->type() == llvm::sys::fs::file_type::regular_file) |
1922 | 0 | continue; |
1923 | 0 | bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework"; |
1924 | 0 | if (IsFramework == SearchDir.isFramework()) |
1925 | 0 | loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(), |
1926 | 0 | SearchDir.isFramework()); |
1927 | 0 | } |
1928 | |
|
1929 | 0 | SearchDir.setSearchedAllModuleMaps(true); |
1930 | 0 | } |
1931 | | |
1932 | | std::string HeaderSearch::suggestPathToFileForDiagnostics( |
1933 | 0 | FileEntryRef File, llvm::StringRef MainFile, bool *IsAngled) const { |
1934 | 0 | return suggestPathToFileForDiagnostics(File.getName(), /*WorkingDir=*/"", |
1935 | 0 | MainFile, IsAngled); |
1936 | 0 | } |
1937 | | |
1938 | | std::string HeaderSearch::suggestPathToFileForDiagnostics( |
1939 | | llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile, |
1940 | 0 | bool *IsAngled) const { |
1941 | 0 | using namespace llvm::sys; |
1942 | |
|
1943 | 0 | llvm::SmallString<32> FilePath = File; |
1944 | | // remove_dots switches to backslashes on windows as a side-effect! |
1945 | | // We always want to suggest forward slashes for includes. |
1946 | | // (not remove_dots(..., posix) as that misparses windows paths). |
1947 | 0 | path::remove_dots(FilePath, /*remove_dot_dot=*/true); |
1948 | 0 | path::native(FilePath, path::Style::posix); |
1949 | 0 | File = FilePath; |
1950 | |
|
1951 | 0 | unsigned BestPrefixLength = 0; |
1952 | | // Checks whether `Dir` is a strict path prefix of `File`. If so and that's |
1953 | | // the longest prefix we've seen so for it, returns true and updates the |
1954 | | // `BestPrefixLength` accordingly. |
1955 | 0 | auto CheckDir = [&](llvm::SmallString<32> Dir) -> bool { |
1956 | 0 | if (!WorkingDir.empty() && !path::is_absolute(Dir)) |
1957 | 0 | fs::make_absolute(WorkingDir, Dir); |
1958 | 0 | path::remove_dots(Dir, /*remove_dot_dot=*/true); |
1959 | 0 | for (auto NI = path::begin(File), NE = path::end(File), |
1960 | 0 | DI = path::begin(Dir), DE = path::end(Dir); |
1961 | 0 | NI != NE; ++NI, ++DI) { |
1962 | 0 | if (DI == DE) { |
1963 | | // Dir is a prefix of File, up to choice of path separators. |
1964 | 0 | unsigned PrefixLength = NI - path::begin(File); |
1965 | 0 | if (PrefixLength > BestPrefixLength) { |
1966 | 0 | BestPrefixLength = PrefixLength; |
1967 | 0 | return true; |
1968 | 0 | } |
1969 | 0 | break; |
1970 | 0 | } |
1971 | | |
1972 | | // Consider all path separators equal. |
1973 | 0 | if (NI->size() == 1 && DI->size() == 1 && |
1974 | 0 | path::is_separator(NI->front()) && path::is_separator(DI->front())) |
1975 | 0 | continue; |
1976 | | |
1977 | | // Special case Apple .sdk folders since the search path is typically a |
1978 | | // symlink like `iPhoneSimulator14.5.sdk` while the file is instead |
1979 | | // located in `iPhoneSimulator.sdk` (the real folder). |
1980 | 0 | if (NI->ends_with(".sdk") && DI->ends_with(".sdk")) { |
1981 | 0 | StringRef NBasename = path::stem(*NI); |
1982 | 0 | StringRef DBasename = path::stem(*DI); |
1983 | 0 | if (DBasename.starts_with(NBasename)) |
1984 | 0 | continue; |
1985 | 0 | } |
1986 | | |
1987 | 0 | if (*NI != *DI) |
1988 | 0 | break; |
1989 | 0 | } |
1990 | 0 | return false; |
1991 | 0 | }; |
1992 | |
|
1993 | 0 | bool BestPrefixIsFramework = false; |
1994 | 0 | for (const DirectoryLookup &DL : search_dir_range()) { |
1995 | 0 | if (DL.isNormalDir()) { |
1996 | 0 | StringRef Dir = DL.getDirRef()->getName(); |
1997 | 0 | if (CheckDir(Dir)) { |
1998 | 0 | if (IsAngled) |
1999 | 0 | *IsAngled = BestPrefixLength && isSystem(DL.getDirCharacteristic()); |
2000 | 0 | BestPrefixIsFramework = false; |
2001 | 0 | } |
2002 | 0 | } else if (DL.isFramework()) { |
2003 | 0 | StringRef Dir = DL.getFrameworkDirRef()->getName(); |
2004 | 0 | if (CheckDir(Dir)) { |
2005 | | // Framework includes by convention use <>. |
2006 | 0 | if (IsAngled) |
2007 | 0 | *IsAngled = BestPrefixLength; |
2008 | 0 | BestPrefixIsFramework = true; |
2009 | 0 | } |
2010 | 0 | } |
2011 | 0 | } |
2012 | | |
2013 | | // Try to shorten include path using TUs directory, if we couldn't find any |
2014 | | // suitable prefix in include search paths. |
2015 | 0 | if (!BestPrefixLength && CheckDir(path::parent_path(MainFile))) { |
2016 | 0 | if (IsAngled) |
2017 | 0 | *IsAngled = false; |
2018 | 0 | BestPrefixIsFramework = false; |
2019 | 0 | } |
2020 | | |
2021 | | // Try resolving resulting filename via reverse search in header maps, |
2022 | | // key from header name is user preferred name for the include file. |
2023 | 0 | StringRef Filename = File.drop_front(BestPrefixLength); |
2024 | 0 | for (const DirectoryLookup &DL : search_dir_range()) { |
2025 | 0 | if (!DL.isHeaderMap()) |
2026 | 0 | continue; |
2027 | | |
2028 | 0 | StringRef SpelledFilename = |
2029 | 0 | DL.getHeaderMap()->reverseLookupFilename(Filename); |
2030 | 0 | if (!SpelledFilename.empty()) { |
2031 | 0 | Filename = SpelledFilename; |
2032 | 0 | BestPrefixIsFramework = false; |
2033 | 0 | break; |
2034 | 0 | } |
2035 | 0 | } |
2036 | | |
2037 | | // If the best prefix is a framework path, we need to compute the proper |
2038 | | // include spelling for the framework header. |
2039 | 0 | bool IsPrivateHeader; |
2040 | 0 | SmallString<128> FrameworkName, IncludeSpelling; |
2041 | 0 | if (BestPrefixIsFramework && |
2042 | 0 | isFrameworkStylePath(Filename, IsPrivateHeader, FrameworkName, |
2043 | 0 | IncludeSpelling)) { |
2044 | 0 | Filename = IncludeSpelling; |
2045 | 0 | } |
2046 | 0 | return path::convert_to_slash(Filename); |
2047 | 0 | } |