xref: /llvm-project/clang/lib/Basic/FileManager.cpp (revision 0785f8d0bb70b1485573556d1315784ebd085af3)
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 "clang/Basic/FileSystemStatCache.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Config/llvm-config.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <algorithm>
29 #include <cassert>
30 #include <climits>
31 #include <cstdint>
32 #include <cstdlib>
33 #include <string>
34 #include <utility>
35 
36 using namespace clang;
37 
38 //===----------------------------------------------------------------------===//
39 // Common logic.
40 //===----------------------------------------------------------------------===//
41 
42 FileManager::FileManager(const FileSystemOptions &FSO,
43                          IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
44     : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
45       SeenFileEntries(64), NextFileUID(0) {
46   NumDirLookups = NumFileLookups = 0;
47   NumDirCacheMisses = NumFileCacheMisses = 0;
48 
49   // If the caller doesn't provide a virtual file system, just grab the real
50   // file system.
51   if (!this->FS)
52     this->FS = llvm::vfs::getRealFileSystem();
53 }
54 
55 FileManager::~FileManager() = default;
56 
57 void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
58   assert(statCache && "No stat cache provided?");
59   StatCache = std::move(statCache);
60 }
61 
62 void FileManager::clearStatCache() { StatCache.reset(); }
63 
64 /// Retrieve the directory that the given file name resides in.
65 /// Filename can point to either a real file or a virtual file.
66 static llvm::ErrorOr<const DirectoryEntry *>
67 getDirectoryFromFile(FileManager &FileMgr, StringRef Filename,
68                      bool CacheFailure) {
69   if (Filename.empty())
70     return std::errc::no_such_file_or_directory;
71 
72   if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
73     return std::errc::is_a_directory;
74 
75   StringRef DirName = llvm::sys::path::parent_path(Filename);
76   // Use the current directory if file has no path component.
77   if (DirName.empty())
78     DirName = ".";
79 
80   return FileMgr.getDirectory(DirName, CacheFailure);
81 }
82 
83 /// Add all ancestors of the given path (pointing to either a file or
84 /// a directory) as virtual directories.
85 void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
86   StringRef DirName = llvm::sys::path::parent_path(Path);
87   if (DirName.empty())
88     DirName = ".";
89 
90   auto &NamedDirEnt = *SeenDirEntries.insert(
91         {DirName, std::errc::no_such_file_or_directory}).first;
92 
93   // When caching a virtual directory, we always cache its ancestors
94   // at the same time.  Therefore, if DirName is already in the cache,
95   // we don't need to recurse as its ancestors must also already be in
96   // the cache (or it's a known non-virtual directory).
97   if (NamedDirEnt.second)
98     return;
99 
100   // Add the virtual directory to the cache.
101   auto UDE = std::make_unique<DirectoryEntry>();
102   UDE->Name = NamedDirEnt.first();
103   NamedDirEnt.second = *UDE.get();
104   VirtualDirectoryEntries.push_back(std::move(UDE));
105 
106   // Recursively add the other ancestors.
107   addAncestorsAsVirtualDirs(DirName);
108 }
109 
110 /// Converts a llvm::ErrorOr<T &> to an llvm::ErrorOr<T *> by promoting
111 /// the address of the inner reference to a pointer or by propagating the error.
112 template <typename T>
113 static llvm::ErrorOr<T *> promoteInnerReference(llvm::ErrorOr<T &> value) {
114   if (value) return &*value;
115   return value.getError();
116 }
117 
118 llvm::ErrorOr<const DirectoryEntry *>
119 FileManager::getDirectory(StringRef DirName, bool CacheFailure) {
120   // stat doesn't like trailing separators except for root directory.
121   // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
122   // (though it can strip '\\')
123   if (DirName.size() > 1 &&
124       DirName != llvm::sys::path::root_path(DirName) &&
125       llvm::sys::path::is_separator(DirName.back()))
126     DirName = DirName.substr(0, DirName.size()-1);
127 #ifdef _WIN32
128   // Fixing a problem with "clang C:test.c" on Windows.
129   // Stat("C:") does not recognize "C:" as a valid directory
130   std::string DirNameStr;
131   if (DirName.size() > 1 && DirName.back() == ':' &&
132       DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
133     DirNameStr = DirName.str() + '.';
134     DirName = DirNameStr;
135   }
136 #endif
137 
138   ++NumDirLookups;
139 
140   // See if there was already an entry in the map.  Note that the map
141   // contains both virtual and real directories.
142   auto SeenDirInsertResult =
143       SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory});
144   if (!SeenDirInsertResult.second)
145     return promoteInnerReference(SeenDirInsertResult.first->second);
146 
147   // We've not seen this before. Fill it in.
148   ++NumDirCacheMisses;
149   auto &NamedDirEnt = *SeenDirInsertResult.first;
150   assert(!NamedDirEnt.second && "should be newly-created");
151 
152   // Get the null-terminated directory name as stored as the key of the
153   // SeenDirEntries map.
154   StringRef InterndDirName = NamedDirEnt.first();
155 
156   // Check to see if the directory exists.
157   llvm::vfs::Status Status;
158   auto statError = getStatValue(InterndDirName, Status, false,
159                                 nullptr /*directory lookup*/);
160   if (statError) {
161     // There's no real directory at the given path.
162     if (CacheFailure)
163       NamedDirEnt.second = statError;
164     else
165       SeenDirEntries.erase(DirName);
166     return statError;
167   }
168 
169   // It exists.  See if we have already opened a directory with the
170   // same inode (this occurs on Unix-like systems when one dir is
171   // symlinked to another, for example) or the same path (on
172   // Windows).
173   DirectoryEntry &UDE = UniqueRealDirs[Status.getUniqueID()];
174 
175   NamedDirEnt.second = UDE;
176   if (UDE.getName().empty()) {
177     // We don't have this directory yet, add it.  We use the string
178     // key from the SeenDirEntries map as the string.
179     UDE.Name  = InterndDirName;
180   }
181 
182   return &UDE;
183 }
184 
185 llvm::ErrorOr<const FileEntry *>
186 FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) {
187   auto Result = getFileRef(Filename, openFile, CacheFailure);
188   if (Result)
189     return &Result->getFileEntry();
190   return llvm::errorToErrorCode(Result.takeError());
191 }
192 
193 llvm::Expected<FileEntryRef>
194 FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) {
195   ++NumFileLookups;
196 
197   // See if there is already an entry in the map.
198   auto SeenFileInsertResult =
199       SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
200   if (!SeenFileInsertResult.second) {
201     if (!SeenFileInsertResult.first->second)
202       return llvm::errorCodeToError(
203           SeenFileInsertResult.first->second.getError());
204     // Construct and return and FileEntryRef, unless it's a redirect to another
205     // filename.
206     SeenFileEntryOrRedirect Value = *SeenFileInsertResult.first->second;
207     FileEntry *FE;
208     if (LLVM_LIKELY(FE = Value.dyn_cast<FileEntry *>()))
209       return FileEntryRef(SeenFileInsertResult.first->first(), *FE);
210     return getFileRef(*Value.get<const StringRef *>(), openFile, CacheFailure);
211   }
212 
213   // We've not seen this before. Fill it in.
214   ++NumFileCacheMisses;
215   auto &NamedFileEnt = *SeenFileInsertResult.first;
216   assert(!NamedFileEnt.second && "should be newly-created");
217 
218   // Get the null-terminated file name as stored as the key of the
219   // SeenFileEntries map.
220   StringRef InterndFileName = NamedFileEnt.first();
221 
222   // Look up the directory for the file.  When looking up something like
223   // sys/foo.h we'll discover all of the search directories that have a 'sys'
224   // subdirectory.  This will let us avoid having to waste time on known-to-fail
225   // searches when we go to find sys/bar.h, because all the search directories
226   // without a 'sys' subdir will get a cached failure result.
227   auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure);
228   if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist.
229     if (CacheFailure)
230       NamedFileEnt.second = DirInfoOrErr.getError();
231     else
232       SeenFileEntries.erase(Filename);
233 
234     return llvm::errorCodeToError(DirInfoOrErr.getError());
235   }
236   const DirectoryEntry *DirInfo = *DirInfoOrErr;
237 
238   // FIXME: Use the directory info to prune this, before doing the stat syscall.
239   // FIXME: This will reduce the # syscalls.
240 
241   // Check to see if the file exists.
242   std::unique_ptr<llvm::vfs::File> F;
243   llvm::vfs::Status Status;
244   auto statError = getStatValue(InterndFileName, Status, true,
245                                 openFile ? &F : nullptr);
246   if (statError) {
247     // There's no real file at the given path.
248     if (CacheFailure)
249       NamedFileEnt.second = statError;
250     else
251       SeenFileEntries.erase(Filename);
252 
253     return llvm::errorCodeToError(statError);
254   }
255 
256   assert((openFile || !F) && "undesired open file");
257 
258   // It exists.  See if we have already opened a file with the same inode.
259   // This occurs when one dir is symlinked to another, for example.
260   FileEntry &UFE = UniqueRealFiles[Status.getUniqueID()];
261 
262   NamedFileEnt.second = &UFE;
263 
264   // If the name returned by getStatValue is different than Filename, re-intern
265   // the name.
266   if (Status.getName() != Filename) {
267     auto &NewNamedFileEnt =
268         *SeenFileEntries.insert({Status.getName(), &UFE}).first;
269     assert((*NewNamedFileEnt.second).get<FileEntry *>() == &UFE &&
270            "filename from getStatValue() refers to wrong file");
271     InterndFileName = NewNamedFileEnt.first().data();
272     // In addition to re-interning the name, construct a redirecting seen file
273     // entry, that will point to the name the filesystem actually wants to use.
274     StringRef *Redirect = new (CanonicalNameStorage) StringRef(InterndFileName);
275     NamedFileEnt.second = Redirect;
276   }
277 
278   if (UFE.isValid()) { // Already have an entry with this inode, return it.
279 
280     // FIXME: this hack ensures that if we look up a file by a virtual path in
281     // the VFS that the getDir() will have the virtual path, even if we found
282     // the file by a 'real' path first. This is required in order to find a
283     // module's structure when its headers/module map are mapped in the VFS.
284     // We should remove this as soon as we can properly support a file having
285     // multiple names.
286     if (DirInfo != UFE.Dir && Status.IsVFSMapped)
287       UFE.Dir = DirInfo;
288 
289     // Always update the name to use the last name by which a file was accessed.
290     // FIXME: Neither this nor always using the first name is correct; we want
291     // to switch towards a design where we return a FileName object that
292     // encapsulates both the name by which the file was accessed and the
293     // corresponding FileEntry.
294     // FIXME: The Name should be removed from FileEntry once all clients
295     // adopt FileEntryRef.
296     UFE.Name = InterndFileName;
297 
298     return FileEntryRef(InterndFileName, UFE);
299   }
300 
301   // Otherwise, we don't have this file yet, add it.
302   UFE.Name    = InterndFileName;
303   UFE.Size    = Status.getSize();
304   UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
305   UFE.Dir     = DirInfo;
306   UFE.UID     = NextFileUID++;
307   UFE.UniqueID = Status.getUniqueID();
308   UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
309   UFE.File = std::move(F);
310   UFE.IsValid = true;
311 
312   if (UFE.File) {
313     if (auto PathName = UFE.File->getName())
314       fillRealPathName(&UFE, *PathName);
315   } else if (!openFile) {
316     // We should still fill the path even if we aren't opening the file.
317     fillRealPathName(&UFE, InterndFileName);
318   }
319   return FileEntryRef(InterndFileName, UFE);
320 }
321 
322 const FileEntry *
323 FileManager::getVirtualFile(StringRef Filename, off_t Size,
324                             time_t ModificationTime) {
325   ++NumFileLookups;
326 
327   // See if there is already an entry in the map for an existing file.
328   auto &NamedFileEnt = *SeenFileEntries.insert(
329       {Filename, std::errc::no_such_file_or_directory}).first;
330   if (NamedFileEnt.second) {
331     SeenFileEntryOrRedirect Value = *NamedFileEnt.second;
332     FileEntry *FE;
333     if (LLVM_LIKELY(FE = Value.dyn_cast<FileEntry *>()))
334       return FE;
335     return getVirtualFile(*Value.get<const StringRef *>(), Size,
336                           ModificationTime);
337   }
338 
339   // We've not seen this before, or the file is cached as non-existent.
340   ++NumFileCacheMisses;
341   addAncestorsAsVirtualDirs(Filename);
342   FileEntry *UFE = nullptr;
343 
344   // Now that all ancestors of Filename are in the cache, the
345   // following call is guaranteed to find the DirectoryEntry from the
346   // cache.
347   auto DirInfo = getDirectoryFromFile(*this, Filename, /*CacheFailure=*/true);
348   assert(DirInfo &&
349          "The directory of a virtual file should already be in the cache.");
350 
351   // Check to see if the file exists. If so, drop the virtual file
352   llvm::vfs::Status Status;
353   const char *InterndFileName = NamedFileEnt.first().data();
354   if (!getStatValue(InterndFileName, Status, true, nullptr)) {
355     UFE = &UniqueRealFiles[Status.getUniqueID()];
356     Status = llvm::vfs::Status(
357       Status.getName(), Status.getUniqueID(),
358       llvm::sys::toTimePoint(ModificationTime),
359       Status.getUser(), Status.getGroup(), Size,
360       Status.getType(), Status.getPermissions());
361 
362     NamedFileEnt.second = UFE;
363 
364     // If we had already opened this file, close it now so we don't
365     // leak the descriptor. We're not going to use the file
366     // descriptor anyway, since this is a virtual file.
367     if (UFE->File)
368       UFE->closeFile();
369 
370     // If we already have an entry with this inode, return it.
371     if (UFE->isValid())
372       return UFE;
373 
374     UFE->UniqueID = Status.getUniqueID();
375     UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
376     fillRealPathName(UFE, Status.getName());
377   } else {
378     VirtualFileEntries.push_back(std::make_unique<FileEntry>());
379     UFE = VirtualFileEntries.back().get();
380     NamedFileEnt.second = UFE;
381   }
382 
383   UFE->Name    = InterndFileName;
384   UFE->Size    = Size;
385   UFE->ModTime = ModificationTime;
386   UFE->Dir     = *DirInfo;
387   UFE->UID     = NextFileUID++;
388   UFE->IsValid = true;
389   UFE->File.reset();
390   return UFE;
391 }
392 
393 bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
394   StringRef pathRef(path.data(), path.size());
395 
396   if (FileSystemOpts.WorkingDir.empty()
397       || llvm::sys::path::is_absolute(pathRef))
398     return false;
399 
400   SmallString<128> NewPath(FileSystemOpts.WorkingDir);
401   llvm::sys::path::append(NewPath, pathRef);
402   path = NewPath;
403   return true;
404 }
405 
406 bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
407   bool Changed = FixupRelativePath(Path);
408 
409   if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
410     FS->makeAbsolute(Path);
411     Changed = true;
412   }
413 
414   return Changed;
415 }
416 
417 void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
418   llvm::SmallString<128> AbsPath(FileName);
419   // This is not the same as `VFS::getRealPath()`, which resolves symlinks
420   // but can be very expensive on real file systems.
421   // FIXME: the semantic of RealPathName is unclear, and the name might be
422   // misleading. We need to clean up the interface here.
423   makeAbsolutePath(AbsPath);
424   llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
425   UFE->RealPathName = AbsPath.str();
426 }
427 
428 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
429 FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
430                               bool ShouldCloseOpenFile) {
431   uint64_t FileSize = Entry->getSize();
432   // If there's a high enough chance that the file have changed since we
433   // got its size, force a stat before opening it.
434   if (isVolatile)
435     FileSize = -1;
436 
437   StringRef Filename = Entry->getName();
438   // If the file is already open, use the open file descriptor.
439   if (Entry->File) {
440     auto Result =
441         Entry->File->getBuffer(Filename, FileSize,
442                                /*RequiresNullTerminator=*/true, isVolatile);
443     // FIXME: we need a set of APIs that can make guarantees about whether a
444     // FileEntry is open or not.
445     if (ShouldCloseOpenFile)
446       Entry->closeFile();
447     return Result;
448   }
449 
450   // Otherwise, open the file.
451   return getBufferForFileImpl(Filename, FileSize, isVolatile);
452 }
453 
454 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
455 FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
456                                   bool isVolatile) {
457   if (FileSystemOpts.WorkingDir.empty())
458     return FS->getBufferForFile(Filename, FileSize,
459                                 /*RequiresNullTerminator=*/true, isVolatile);
460 
461   SmallString<128> FilePath(Filename);
462   FixupRelativePath(FilePath);
463   return FS->getBufferForFile(FilePath, FileSize,
464                               /*RequiresNullTerminator=*/true, isVolatile);
465 }
466 
467 /// getStatValue - Get the 'stat' information for the specified path,
468 /// using the cache to accelerate it if possible.  This returns true
469 /// if the path points to a virtual file or does not exist, or returns
470 /// false if it's an existent real file.  If FileDescriptor is NULL,
471 /// do directory look-up instead of file look-up.
472 std::error_code
473 FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
474                           bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
475   // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
476   // absolute!
477   if (FileSystemOpts.WorkingDir.empty())
478     return FileSystemStatCache::get(Path, Status, isFile, F,
479                                     StatCache.get(), *FS);
480 
481   SmallString<128> FilePath(Path);
482   FixupRelativePath(FilePath);
483 
484   return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
485                                   StatCache.get(), *FS);
486 }
487 
488 std::error_code
489 FileManager::getNoncachedStatValue(StringRef Path,
490                                    llvm::vfs::Status &Result) {
491   SmallString<128> FilePath(Path);
492   FixupRelativePath(FilePath);
493 
494   llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
495   if (!S)
496     return S.getError();
497   Result = *S;
498   return std::error_code();
499 }
500 
501 void FileManager::GetUniqueIDMapping(
502                    SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
503   UIDToFiles.clear();
504   UIDToFiles.resize(NextFileUID);
505 
506   // Map file entries
507   for (llvm::StringMap<llvm::ErrorOr<SeenFileEntryOrRedirect>,
508                        llvm::BumpPtrAllocator>::const_iterator
509            FE = SeenFileEntries.begin(),
510            FEEnd = SeenFileEntries.end();
511        FE != FEEnd; ++FE)
512     if (llvm::ErrorOr<SeenFileEntryOrRedirect> Entry = FE->getValue()) {
513       if (const auto *FE = (*Entry).dyn_cast<FileEntry *>())
514         UIDToFiles[FE->getUID()] = FE;
515     }
516 
517   // Map virtual file entries
518   for (const auto &VFE : VirtualFileEntries)
519     UIDToFiles[VFE->getUID()] = VFE.get();
520 }
521 
522 void FileManager::modifyFileEntry(FileEntry *File,
523                                   off_t Size, time_t ModificationTime) {
524   File->Size = Size;
525   File->ModTime = ModificationTime;
526 }
527 
528 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
529   // FIXME: use llvm::sys::fs::canonical() when it gets implemented
530   llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
531     = CanonicalDirNames.find(Dir);
532   if (Known != CanonicalDirNames.end())
533     return Known->second;
534 
535   StringRef CanonicalName(Dir->getName());
536 
537   SmallString<4096> CanonicalNameBuf;
538   if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
539     CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
540 
541   CanonicalDirNames.insert({Dir, CanonicalName});
542   return CanonicalName;
543 }
544 
545 void FileManager::PrintStats() const {
546   llvm::errs() << "\n*** File Manager Stats:\n";
547   llvm::errs() << UniqueRealFiles.size() << " real files found, "
548                << UniqueRealDirs.size() << " real dirs found.\n";
549   llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
550                << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
551   llvm::errs() << NumDirLookups << " dir lookups, "
552                << NumDirCacheMisses << " dir cache misses.\n";
553   llvm::errs() << NumFileLookups << " file lookups, "
554                << NumFileCacheMisses << " file cache misses.\n";
555 
556   //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
557 }
558