1//===--- FileManager.cpp - File System Probing and Caching ----------------===//
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 FileManager interface.
10//
11//===----------------------------------------------------------------------===//
12//
13// TODO: This should index all interesting directories with dirent calls.
14// getdirentries ?
15// opendir/readdir_r/closedir ?
16//
17//===----------------------------------------------------------------------===//
18
19#include "clang/Basic/FileManager.h"
20#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/Config/llvm-config.h"
23#include "llvm/Support/Error.h"
24#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/IOSandbox.h"
26#include "llvm/Support/MemoryBuffer.h"
27#include "llvm/Support/Path.h"
28#include "llvm/Support/VirtualFileSystem.h"
29#include "llvm/Support/raw_ostream.h"
30#include <cassert>
31#include <climits>
32#include <cstdint>
33#include <cstdlib>
34#include <optional>
35#include <string>
36#include <utility>
37
38using namespace clang;
39
40#define DEBUG_TYPE "file-search"
41
42static void normalizeCacheKey(StringRef &Path,
43 std::optional<std::string> &Storage) {
44 using namespace llvm::sys::path;
45
46 // Drop trailing separators for non-root paths so that cache keys and `stat`
47 // queries use a single spelling. Keep root paths (`/`, `[A-Z]:\`) unchanged.
48 if (Path.size() > 1 && root_path(path: Path) != Path && is_separator(value: Path.back()))
49 Path = Path.drop_back();
50
51 // A bare drive path like "[A-Z]:" is drive-relative (current directory on the
52 // drive). As `[A-Z]:` is not a path specification, we must canonicalise it
53 // to `[A-Z]:.`.
54 if (is_style_windows(S: Style::native)) {
55 if (Path.size() > 1 && Path.back() == ':' &&
56 Path.equals_insensitive(RHS: root_name(path: Path))) {
57 Storage = Path.str() + ".";
58 Path = *Storage;
59 }
60 }
61}
62
63//===----------------------------------------------------------------------===//
64// Common logic.
65//===----------------------------------------------------------------------===//
66
67FileManager::FileManager(const FileSystemOptions &FSO)
68 : FileManager(FSO, nullptr) {}
69
70FileManager::FileManager(const FileSystemOptions &FSO,
71 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
72 : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
73 SeenFileEntries(64), NextFileUID(0) {
74 // If the caller doesn't provide a virtual file system, just grab the real
75 // file system.
76 if (!this->FS)
77 this->FS = llvm::vfs::getRealFileSystem();
78}
79
80void FileManager::setVirtualFileSystem(
81 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) {
82 this->FS = std::move(FS);
83}
84
85IntrusiveRefCntPtr<llvm::vfs::FileSystem>
86FileManager::getVirtualFileSystemPtr() const {
87 return FS;
88}
89
90FileManager::~FileManager() = default;
91
92llvm::ErrorOr<DirectoryEntryRef>
93FileManager::getDirectoryFromFile(StringRef Filename, bool CacheFailure) {
94 if (Filename.empty())
95 return make_error_code(e: std::errc::no_such_file_or_directory);
96
97 if (llvm::sys::path::is_separator(value: Filename[Filename.size() - 1]))
98 return make_error_code(e: std::errc::is_a_directory);
99
100 StringRef DirName = llvm::sys::path::parent_path(path: Filename);
101 // Use the current directory if file has no path component.
102 if (DirName.empty())
103 DirName = ".";
104
105 return getDirectoryRefImpl(DirName, CacheFailure);
106}
107
108DirectoryEntry *&FileManager::getRealDirEntry(const llvm::vfs::Status &Status) {
109 assert(Status.isDirectory() && "The directory should exist!");
110 // See if we have already opened a directory with the
111 // same inode (this occurs on Unix-like systems when one dir is
112 // symlinked to another, for example) or the same path (on
113 // Windows).
114 DirectoryEntry *&UDE = UniqueRealDirs[Status.getUniqueID()];
115
116 if (!UDE) {
117 // We don't have this directory yet, add it. We use the string
118 // key from the SeenDirEntries map as the string.
119 UDE = new (DirsAlloc.Allocate()) DirectoryEntry();
120 }
121 return UDE;
122}
123
124/// Add all ancestors of the given path (pointing to either a file or
125/// a directory) as virtual directories.
126void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
127 StringRef DirName = llvm::sys::path::parent_path(path: Path);
128 if (DirName.empty())
129 DirName = ".";
130
131 // Normalize the key for cache lookup/insert, but keep the original DirName
132 // for recursive processing since normalization can create paths that don't
133 // work well with parent_path() (e.g., "C:" -> "C:.").
134 std::optional<std::string> Storage;
135 StringRef OriginalDirName = DirName;
136 normalizeCacheKey(Path&: DirName, Storage);
137
138 auto &NamedDirEnt = *SeenDirEntries.insert(
139 KV: {DirName, std::errc::no_such_file_or_directory}).first;
140
141 // When caching a virtual directory, we always cache its ancestors
142 // at the same time. Therefore, if DirName is already in the cache,
143 // we don't need to recurse as its ancestors must also already be in
144 // the cache (or it's a known non-virtual directory).
145 if (NamedDirEnt.second)
146 return;
147
148 // Check to see if the directory exists.
149 llvm::vfs::Status Status;
150 auto statError =
151 getStatValue(Path: DirName, Status, isFile: false, F: nullptr /*directory lookup*/);
152 if (statError) {
153 // There's no real directory at the given path.
154 // Add the virtual directory to the cache.
155 auto *UDE = new (DirsAlloc.Allocate()) DirectoryEntry();
156 NamedDirEnt.second = *UDE;
157 VirtualDirectoryEntries.push_back(Elt: UDE);
158 } else {
159 // There is the real directory
160 DirectoryEntry *&UDE = getRealDirEntry(Status);
161 NamedDirEnt.second = *UDE;
162 }
163
164 // Recursively add the other ancestors.
165 addAncestorsAsVirtualDirs(Path: OriginalDirName);
166}
167
168llvm::ErrorOr<DirectoryEntryRef>
169FileManager::getDirectoryRefImpl(StringRef DirName, bool CacheFailure) {
170 std::optional<std::string> DirNameStr;
171 normalizeCacheKey(Path&: DirName, Storage&: DirNameStr);
172
173 ++NumDirLookups;
174
175 // See if there was already an entry in the map. Note that the map
176 // contains both virtual and real directories.
177 auto SeenDirInsertResult =
178 SeenDirEntries.insert(KV: {DirName, std::errc::no_such_file_or_directory});
179 if (!SeenDirInsertResult.second) {
180 if (SeenDirInsertResult.first->second)
181 return DirectoryEntryRef(*SeenDirInsertResult.first);
182 return SeenDirInsertResult.first->second.getError();
183 }
184
185 // We've not seen this before. Fill it in.
186 ++NumDirCacheMisses;
187 auto &NamedDirEnt = *SeenDirInsertResult.first;
188 assert(!NamedDirEnt.second && "should be newly-created");
189
190 // Get the null-terminated directory name as stored as the key of the
191 // SeenDirEntries map.
192 StringRef InterndDirName = NamedDirEnt.first();
193
194 // Check to see if the directory exists.
195 llvm::vfs::Status Status;
196 auto statError = getStatValue(Path: InterndDirName, Status, isFile: false,
197 F: nullptr /*directory lookup*/);
198 if (statError) {
199 // There's no real directory at the given path.
200 if (CacheFailure)
201 NamedDirEnt.second = statError;
202 else
203 SeenDirEntries.erase(Key: DirName);
204 return statError;
205 }
206
207 // It exists.
208 DirectoryEntry *&UDE = getRealDirEntry(Status);
209 NamedDirEnt.second = *UDE;
210
211 return DirectoryEntryRef(NamedDirEnt);
212}
213
214llvm::ErrorOr<FileEntryRef> FileManager::getFileRefImpl(StringRef Filename,
215 bool openFile,
216 bool CacheFailure,
217 bool IsText) {
218 ++NumFileLookups;
219
220 // See if there is already an entry in the map.
221 auto SeenFileInsertResult =
222 SeenFileEntries.insert(KV: {Filename, std::errc::no_such_file_or_directory});
223 if (!SeenFileInsertResult.second) {
224 if (!SeenFileInsertResult.first->second)
225 return SeenFileInsertResult.first->second.getError();
226 return FileEntryRef(*SeenFileInsertResult.first);
227 }
228
229 // We've not seen this before. Fill it in.
230 ++NumFileCacheMisses;
231 auto *NamedFileEnt = &*SeenFileInsertResult.first;
232 assert(!NamedFileEnt->second && "should be newly-created");
233
234 // Get the null-terminated file name as stored as the key of the
235 // SeenFileEntries map.
236 StringRef InterndFileName = NamedFileEnt->first();
237
238 // Look up the directory for the file. When looking up something like
239 // sys/foo.h we'll discover all of the search directories that have a 'sys'
240 // subdirectory. This will let us avoid having to waste time on known-to-fail
241 // searches when we go to find sys/bar.h, because all the search directories
242 // without a 'sys' subdir will get a cached failure result.
243 auto DirInfoOrErr = getDirectoryFromFile(Filename, CacheFailure);
244 if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist.
245 std::error_code Err = DirInfoOrErr.getError();
246 if (CacheFailure)
247 NamedFileEnt->second = Err;
248 else
249 SeenFileEntries.erase(Key: Filename);
250
251 return Err;
252 }
253 DirectoryEntryRef DirInfo = *DirInfoOrErr;
254
255 // FIXME: Use the directory info to prune this, before doing the stat syscall.
256 // FIXME: This will reduce the # syscalls.
257
258 // Check to see if the file exists.
259 std::unique_ptr<llvm::vfs::File> F;
260 llvm::vfs::Status Status;
261 auto statError = getStatValue(Path: InterndFileName, Status, isFile: true,
262 F: openFile ? &F : nullptr, IsText);
263 if (statError) {
264 // There's no real file at the given path.
265 if (CacheFailure)
266 NamedFileEnt->second = statError;
267 else
268 SeenFileEntries.erase(Key: Filename);
269
270 return statError;
271 }
272
273 assert((openFile || !F) && "undesired open file");
274
275 // It exists. See if we have already opened a file with the same inode.
276 // This occurs when one dir is symlinked to another, for example.
277 FileEntry *&UFE = UniqueRealFiles[Status.getUniqueID()];
278 bool ReusingEntry = UFE != nullptr;
279 if (!UFE)
280 UFE = new (FilesAlloc.Allocate()) FileEntry();
281
282 if (!Status.ExposesExternalVFSPath || Status.getName() == Filename) {
283 // Use the requested name. Set the FileEntry.
284 NamedFileEnt->second = FileEntryRef::MapValue(*UFE, DirInfo);
285 } else {
286 // Name mismatch. We need a redirect. First grab the actual entry we want
287 // to return.
288 //
289 // This redirection logic intentionally leaks the external name of a
290 // redirected file that uses 'use-external-name' in \a
291 // vfs::RedirectionFileSystem. This allows clang to report the external
292 // name to users (in diagnostics) and to tools that don't have access to
293 // the VFS (in debug info and dependency '.d' files).
294 //
295 // FIXME: This is pretty complex and has some very complicated interactions
296 // with the rest of clang. It's also inconsistent with how "real"
297 // filesystems behave and confuses parts of clang expect to see the
298 // name-as-accessed on the \a FileEntryRef.
299 //
300 // A potential plan to remove this is as follows -
301 // - Update callers such as `HeaderSearch::findUsableModuleForHeader()`
302 // to explicitly use the `getNameAsRequested()` rather than just using
303 // `getName()`.
304 // - Add a `FileManager::getExternalPath` API for explicitly getting the
305 // remapped external filename when there is one available. Adopt it in
306 // callers like diagnostics/deps reporting instead of calling
307 // `getName()` directly.
308 // - Switch the meaning of `FileEntryRef::getName()` to get the requested
309 // name, not the external name. Once that sticks, revert callers that
310 // want the requested name back to calling `getName()`.
311 // - Update the VFS to always return the requested name. This could also
312 // return the external name, or just have an API to request it
313 // lazily. The latter has the benefit of making accesses of the
314 // external path easily tracked, but may also require extra work than
315 // just returning up front.
316 // - (Optionally) Add an API to VFS to get the external filename lazily
317 // and update `FileManager::getExternalPath()` to use it instead. This
318 // has the benefit of making such accesses easily tracked, though isn't
319 // necessarily required (and could cause extra work than just adding to
320 // eg. `vfs::Status` up front).
321 auto &Redirection =
322 *SeenFileEntries
323 .insert(KV: {Status.getName(), FileEntryRef::MapValue(*UFE, DirInfo)})
324 .first;
325 assert(isa<FileEntry *>(Redirection.second->V) &&
326 "filename redirected to a non-canonical filename?");
327 assert(cast<FileEntry *>(Redirection.second->V) == UFE &&
328 "filename from getStatValue() refers to wrong file");
329
330 // Cache the redirection in the previously-inserted entry, still available
331 // in the tentative return value.
332 NamedFileEnt->second = FileEntryRef::MapValue(Redirection, DirInfo);
333 }
334
335 FileEntryRef ReturnedRef(*NamedFileEnt);
336 if (ReusingEntry) { // Already have an entry with this inode, return it.
337 return ReturnedRef;
338 }
339
340 // Otherwise, we don't have this file yet, add it.
341 UFE->Size = Status.getSize();
342 UFE->ModTime = llvm::sys::toTimeT(TP: Status.getLastModificationTime());
343 UFE->Dir = &DirInfo.getDirEntry();
344 UFE->UID = NextFileUID++;
345 UFE->UniqueID = Status.getUniqueID();
346 UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
347 UFE->IsDeviceFile =
348 Status.getType() == llvm::sys::fs::file_type::character_file;
349 UFE->File = std::move(F);
350
351 if (UFE->File) {
352 if (auto PathName = UFE->File->getName())
353 fillRealPathName(UFE, FileName: *PathName);
354 } else if (!openFile) {
355 // We should still fill the path even if we aren't opening the file.
356 fillRealPathName(UFE, FileName: InterndFileName);
357 }
358 return ReturnedRef;
359}
360
361llvm::Expected<FileEntryRef> FileManager::getSTDIN() {
362 // Only read stdin once.
363 if (STDIN)
364 return *STDIN;
365
366 auto ContentOrError = [] {
367 auto BypassSandbox = llvm::sys::sandbox::scopedDisable();
368 return llvm::MemoryBuffer::getSTDIN();
369 }();
370
371 if (!ContentOrError)
372 return llvm::createFileError(F: "-", EC: ContentOrError.getError());
373
374 auto Content = std::move(*ContentOrError);
375 STDIN = getVirtualFileRef(Filename: Content->getBufferIdentifier(),
376 Size: Content->getBufferSize(), ModificationTime: 0);
377 FileEntry &FE = const_cast<FileEntry &>(STDIN->getFileEntry());
378 FE.Content = std::move(Content);
379 FE.IsNamedPipe = true;
380 return *STDIN;
381}
382
383void FileManager::trackVFSUsage(bool Active) {
384 FS->visit(Callback: [Active](llvm::vfs::FileSystem &FileSys) {
385 if (auto *RFS = dyn_cast<llvm::vfs::RedirectingFileSystem>(Val: &FileSys))
386 RFS->setUsageTrackingActive(Active);
387 });
388}
389
390FileEntryRef FileManager::getVirtualFileRef(StringRef Filename, off_t Size,
391 time_t ModificationTime) {
392 ++NumFileLookups;
393
394 // See if there is already an entry in the map for an existing file.
395 auto &NamedFileEnt = *SeenFileEntries.insert(
396 KV: {Filename, std::errc::no_such_file_or_directory}).first;
397 if (NamedFileEnt.second) {
398 FileEntryRef::MapValue Value = *NamedFileEnt.second;
399 if (LLVM_LIKELY(isa<FileEntry *>(Value.V)))
400 return FileEntryRef(NamedFileEnt);
401 return FileEntryRef(*cast<const FileEntryRef::MapEntry *>(Val&: Value.V));
402 }
403
404 // We've not seen this before, or the file is cached as non-existent.
405 ++NumFileCacheMisses;
406 addAncestorsAsVirtualDirs(Path: Filename);
407 FileEntry *UFE = nullptr;
408
409 // Now that all ancestors of Filename are in the cache, the
410 // following call is guaranteed to find the DirectoryEntry from the
411 // cache. A virtual file can also have an empty filename, that could come
412 // from a source location preprocessor directive with an empty filename as
413 // an example, so we need to pretend it has a name to ensure a valid directory
414 // entry can be returned.
415 auto DirInfo = getDirectoryFromFile(Filename: Filename.empty() ? "." : Filename,
416 /*CacheFailure=*/true);
417 assert(DirInfo &&
418 "The directory of a virtual file should already be in the cache.");
419
420 // Check to see if the file exists. If so, drop the virtual file
421 llvm::vfs::Status Status;
422 const char *InterndFileName = NamedFileEnt.first().data();
423 if (!getStatValue(Path: InterndFileName, Status, isFile: true, F: nullptr)) {
424 Status = llvm::vfs::Status(
425 Status.getName(), Status.getUniqueID(),
426 llvm::sys::toTimePoint(T: ModificationTime),
427 Status.getUser(), Status.getGroup(), Size,
428 Status.getType(), Status.getPermissions());
429
430 auto &RealFE = UniqueRealFiles[Status.getUniqueID()];
431 if (RealFE) {
432 // If we had already opened this file, close it now so we don't
433 // leak the descriptor. We're not going to use the file
434 // descriptor anyway, since this is a virtual file.
435 if (RealFE->File)
436 RealFE->closeFile();
437 // If we already have an entry with this inode, return it.
438 //
439 // FIXME: Surely this should add a reference by the new name, and return
440 // it instead...
441 NamedFileEnt.second = FileEntryRef::MapValue(*RealFE, *DirInfo);
442 return FileEntryRef(NamedFileEnt);
443 }
444 // File exists, but no entry - create it.
445 RealFE = new (FilesAlloc.Allocate()) FileEntry();
446 RealFE->UniqueID = Status.getUniqueID();
447 RealFE->IsNamedPipe =
448 Status.getType() == llvm::sys::fs::file_type::fifo_file;
449 fillRealPathName(UFE: RealFE, FileName: Status.getName());
450
451 UFE = RealFE;
452 } else {
453 // File does not exist, create a virtual entry.
454 UFE = new (FilesAlloc.Allocate()) FileEntry();
455 VirtualFileEntries.push_back(Elt: UFE);
456 }
457
458 NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo);
459 UFE->Size = Size;
460 UFE->ModTime = ModificationTime;
461 UFE->Dir = &DirInfo->getDirEntry();
462 UFE->UID = NextFileUID++;
463 UFE->File.reset();
464 return FileEntryRef(NamedFileEnt);
465}
466
467OptionalFileEntryRef FileManager::getBypassFile(FileEntryRef VF) {
468 // Stat of the file and return nullptr if it doesn't exist.
469 llvm::vfs::Status Status;
470 if (getStatValue(Path: VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr))
471 return std::nullopt;
472
473 if (!SeenBypassFileEntries)
474 SeenBypassFileEntries = std::make_unique<
475 llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>>>();
476
477 // If we've already bypassed just use the existing one.
478 auto Insertion = SeenBypassFileEntries->insert(
479 KV: {VF.getName(), std::errc::no_such_file_or_directory});
480 if (!Insertion.second)
481 return FileEntryRef(*Insertion.first);
482
483 // Fill in the new entry from the stat.
484 FileEntry *BFE = new (FilesAlloc.Allocate()) FileEntry();
485 BypassFileEntries.push_back(Elt: BFE);
486 Insertion.first->second = FileEntryRef::MapValue(*BFE, VF.getDir());
487 BFE->Size = Status.getSize();
488 BFE->Dir = VF.getFileEntry().Dir;
489 BFE->ModTime = llvm::sys::toTimeT(TP: Status.getLastModificationTime());
490 BFE->UID = NextFileUID++;
491
492 // Save the entry in the bypass table and return.
493 return FileEntryRef(*Insertion.first);
494}
495
496bool FileManager::fixupRelativePath(const FileSystemOptions &FileSystemOpts,
497 SmallVectorImpl<char> &Path) {
498 StringRef pathRef(Path.data(), Path.size());
499
500 if (FileSystemOpts.WorkingDir.empty()
501 || llvm::sys::path::is_absolute(path: pathRef))
502 return false;
503
504 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
505 llvm::sys::path::append(path&: NewPath, a: pathRef);
506 Path = std::move(NewPath);
507 return true;
508}
509
510bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path,
511 bool Canonicalize) const {
512 bool Changed = FixupRelativePath(Path);
513
514 if (!llvm::sys::path::is_absolute(path: StringRef(Path.data(), Path.size()))) {
515 FS->makeAbsolute(Path);
516 Changed = true;
517 }
518
519 if (Canonicalize)
520 Changed |= llvm::sys::path::remove_dots(path&: Path);
521
522 return Changed;
523}
524
525void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
526 llvm::SmallString<128> AbsPath(FileName);
527 // This is not the same as `VFS::getRealPath()`, which resolves symlinks
528 // but can be very expensive on real file systems.
529 // FIXME: the semantic of RealPathName is unclear, and the name might be
530 // misleading. We need to clean up the interface here.
531 makeAbsolutePath(Path&: AbsPath);
532 llvm::sys::path::remove_dots(path&: AbsPath, /*remove_dot_dot=*/true);
533 UFE->RealPathName = std::string(AbsPath);
534}
535
536llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
537FileManager::getBufferForFile(FileEntryRef FE, bool isVolatile,
538 bool RequiresNullTerminator,
539 std::optional<int64_t> MaybeLimit, bool IsText) {
540 const FileEntry *Entry = &FE.getFileEntry();
541 // If the content is living on the file entry, return a reference to it.
542 if (Entry->Content)
543 return llvm::MemoryBuffer::getMemBuffer(Ref: Entry->Content->getMemBufferRef());
544
545 uint64_t FileSize = Entry->getSize();
546
547 if (MaybeLimit)
548 FileSize = *MaybeLimit;
549
550 // If there's a high enough chance that the file have changed since we
551 // got its size, force a stat before opening it.
552 if (isVolatile || Entry->isNamedPipe())
553 FileSize = -1;
554
555 StringRef Filename = FE.getName();
556 // If the file is already open, use the open file descriptor.
557 if (Entry->File) {
558 auto Result = Entry->File->getBuffer(Name: Filename, FileSize,
559 RequiresNullTerminator, IsVolatile: isVolatile);
560 Entry->closeFile();
561 return Result;
562 }
563
564 // Otherwise, open the file.
565 return getBufferForFileImpl(Filename, FileSize, isVolatile,
566 RequiresNullTerminator, IsText);
567}
568
569llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
570FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
571 bool isVolatile, bool RequiresNullTerminator,
572 bool IsText) const {
573 if (FileSystemOpts.WorkingDir.empty())
574 return FS->getBufferForFile(Name: Filename, FileSize, RequiresNullTerminator,
575 IsVolatile: isVolatile, IsText);
576
577 SmallString<128> FilePath(Filename);
578 FixupRelativePath(Path&: FilePath);
579 return FS->getBufferForFile(Name: FilePath, FileSize, RequiresNullTerminator,
580 IsVolatile: isVolatile, IsText);
581}
582
583std::error_code FileManager::getStatValue(StringRef Path,
584 llvm::vfs::Status &Status,
585 bool isFile,
586 std::unique_ptr<llvm::vfs::File> *F,
587 bool IsText) {
588 SmallString<128> FilePath;
589
590 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
591 // absolute!
592 if (!FileSystemOpts.WorkingDir.empty()) {
593 FilePath = Path;
594 FixupRelativePath(Path&: FilePath);
595 Path = FilePath;
596 }
597
598 bool isForDir = !isFile;
599 std::error_code RetCode;
600
601 if (isForDir || !F) {
602 // If this is a directory or a file descriptor is not needed, just go to the
603 // file system.
604 llvm::ErrorOr<llvm::vfs::Status> StatusOrErr = FS->status(Path);
605 if (!StatusOrErr) {
606 RetCode = StatusOrErr.getError();
607 } else {
608 Status = *StatusOrErr;
609 }
610 } else {
611 // We can always just use 'stat' here, but (for files) the client is asking
612 // whether the file exists because it wants to turn around and *open* it.
613 // It is more efficient to do "open+fstat" on success than it is to do
614 // "stat+open".
615 //
616 // Because of this, check to see if the file exists with 'open'. If the
617 // open succeeds, use fstat to get the stat info.
618 auto OwnedFile =
619 IsText ? FS->openFileForRead(Path) : FS->openFileForReadBinary(Path);
620
621 if (!OwnedFile) {
622 // If the open fails, our "stat" fails.
623 RetCode = OwnedFile.getError();
624 } else {
625 // Otherwise, the open succeeded. Do an fstat to get the information
626 // about the file. We'll end up returning the open file descriptor to the
627 // client to do what they please with it.
628 llvm::ErrorOr<llvm::vfs::Status> StatusOrErr = (*OwnedFile)->status();
629 if (StatusOrErr) {
630 Status = *StatusOrErr;
631 *F = std::move(*OwnedFile);
632 } else {
633 // fstat rarely fails. If it does, claim the initial open didn't
634 // succeed.
635 *F = nullptr;
636 RetCode = StatusOrErr.getError();
637 }
638 }
639 }
640
641 // If the path doesn't exist, return failure.
642 if (RetCode)
643 return RetCode;
644
645 // If the path exists, make sure that its "directoryness" matches the clients
646 // demands.
647 if (Status.isDirectory() != isForDir) {
648 // If not, close the file if opened.
649 if (F)
650 *F = nullptr;
651 return std::make_error_code(e: Status.isDirectory()
652 ? std::errc::is_a_directory
653 : std::errc::not_a_directory);
654 }
655
656 return std::error_code();
657}
658
659StringRef FileManager::getCanonicalName(DirectoryEntryRef Dir) {
660 return getCanonicalName(Entry: Dir, Name: Dir.getName());
661}
662
663StringRef FileManager::getCanonicalName(FileEntryRef File) {
664 return getCanonicalName(Entry: File, Name: File.getName());
665}
666
667StringRef FileManager::getCanonicalName(const void *Entry, StringRef Name) {
668 llvm::DenseMap<const void *, llvm::StringRef>::iterator Known =
669 CanonicalNames.find(Val: Entry);
670 if (Known != CanonicalNames.end())
671 return Known->second;
672
673 // Name comes from FileEntry/DirectoryEntry::getName(), so it is safe to
674 // store it in the DenseMap below.
675 StringRef CanonicalName(Name);
676
677 SmallString<256> AbsPathBuf;
678 SmallString<256> RealPathBuf;
679 if (!FS->getRealPath(Path: Name, Output&: RealPathBuf)) {
680 if (is_style_windows(S: llvm::sys::path::Style::native)) {
681 // For Windows paths, only use the real path if it doesn't resolve
682 // a substitute drive, as those are used to avoid MAX_PATH issues.
683 AbsPathBuf = Name;
684 if (!FS->makeAbsolute(Path&: AbsPathBuf)) {
685 if (llvm::sys::path::root_name(path: RealPathBuf) ==
686 llvm::sys::path::root_name(path: AbsPathBuf)) {
687 CanonicalName = RealPathBuf.str().copy(A&: CanonicalNameStorage);
688 } else {
689 // Fallback to using the absolute path.
690 // Simplifying /../ is semantically valid on Windows even in the
691 // presence of symbolic links.
692 llvm::sys::path::remove_dots(path&: AbsPathBuf, /*remove_dot_dot=*/true);
693 CanonicalName = AbsPathBuf.str().copy(A&: CanonicalNameStorage);
694 }
695 }
696 } else {
697 CanonicalName = RealPathBuf.str().copy(A&: CanonicalNameStorage);
698 }
699 }
700
701 CanonicalNames.insert(KV: {Entry, CanonicalName});
702 return CanonicalName;
703}
704
705void FileManager::AddStats(const FileManager &Other) {
706 assert(&Other != this && "Collecting stats into the same FileManager");
707 NumDirLookups += Other.NumDirLookups;
708 NumFileLookups += Other.NumFileLookups;
709 NumDirCacheMisses += Other.NumDirCacheMisses;
710 NumFileCacheMisses += Other.NumFileCacheMisses;
711}
712
713void FileManager::PrintStats() const {
714 llvm::errs() << "\n*** File Manager Stats:\n";
715 llvm::errs() << UniqueRealFiles.size() << " real files found, "
716 << UniqueRealDirs.size() << " real dirs found.\n";
717 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
718 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
719 llvm::errs() << NumDirLookups << " dir lookups, "
720 << NumDirCacheMisses << " dir cache misses.\n";
721 llvm::errs() << NumFileLookups << " file lookups, "
722 << NumFileCacheMisses << " file cache misses.\n";
723
724 getVirtualFileSystem().visit(Callback: [](llvm::vfs::FileSystem &VFS) {
725 if (auto *T = dyn_cast_or_null<llvm::vfs::TracingFileSystem>(Val: &VFS))
726 llvm::errs() << "\n*** Virtual File System Stats:\n"
727 << T->NumStatusCalls << " status() calls\n"
728 << T->NumOpenFileForReadCalls << " openFileForRead() calls\n"
729 << T->NumDirBeginCalls << " dir_begin() calls\n"
730 << T->NumGetRealPathCalls << " getRealPath() calls\n"
731 << T->NumExistsCalls << " exists() calls\n"
732 << T->NumIsLocalCalls << " isLocal() calls\n";
733 });
734
735 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
736}
737