xref: /llvm-project/clang/lib/Basic/FileManager.cpp (revision 2b3d49b610bd2a45884115edcb21110bfa325f51)
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   ++NumFileLookups;
188 
189   // See if there is already an entry in the map.
190   auto SeenFileInsertResult =
191       SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
192   if (!SeenFileInsertResult.second)
193     return promoteInnerReference(SeenFileInsertResult.first->second);
194 
195   // We've not seen this before. Fill it in.
196   ++NumFileCacheMisses;
197   auto &NamedFileEnt = *SeenFileInsertResult.first;
198   assert(!NamedFileEnt.second && "should be newly-created");
199 
200   // Get the null-terminated file name as stored as the key of the
201   // SeenFileEntries map.
202   StringRef InterndFileName = NamedFileEnt.first();
203 
204   // Look up the directory for the file.  When looking up something like
205   // sys/foo.h we'll discover all of the search directories that have a 'sys'
206   // subdirectory.  This will let us avoid having to waste time on known-to-fail
207   // searches when we go to find sys/bar.h, because all the search directories
208   // without a 'sys' subdir will get a cached failure result.
209   auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure);
210   if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist.
211     if (CacheFailure)
212       NamedFileEnt.second = DirInfoOrErr.getError();
213     else
214       SeenFileEntries.erase(Filename);
215 
216     return DirInfoOrErr.getError();
217   }
218   const DirectoryEntry *DirInfo = *DirInfoOrErr;
219 
220   // FIXME: Use the directory info to prune this, before doing the stat syscall.
221   // FIXME: This will reduce the # syscalls.
222 
223   // Check to see if the file exists.
224   std::unique_ptr<llvm::vfs::File> F;
225   llvm::vfs::Status Status;
226   auto statError = getStatValue(InterndFileName, Status, true,
227                                 openFile ? &F : nullptr);
228   if (statError) {
229     // There's no real file at the given path.
230     if (CacheFailure)
231       NamedFileEnt.second = statError;
232     else
233       SeenFileEntries.erase(Filename);
234 
235     return statError;
236   }
237 
238   assert((openFile || !F) && "undesired open file");
239 
240   // It exists.  See if we have already opened a file with the same inode.
241   // This occurs when one dir is symlinked to another, for example.
242   FileEntry &UFE = UniqueRealFiles[Status.getUniqueID()];
243 
244   NamedFileEnt.second = UFE;
245 
246   // If the name returned by getStatValue is different than Filename, re-intern
247   // the name.
248   if (Status.getName() != Filename) {
249     auto &NamedFileEnt =
250       *SeenFileEntries.insert({Status.getName(), UFE}).first;
251     assert(&*NamedFileEnt.second == &UFE &&
252            "filename from getStatValue() refers to wrong file");
253     InterndFileName = NamedFileEnt.first().data();
254   }
255 
256   if (UFE.isValid()) { // Already have an entry with this inode, return it.
257 
258     // FIXME: this hack ensures that if we look up a file by a virtual path in
259     // the VFS that the getDir() will have the virtual path, even if we found
260     // the file by a 'real' path first. This is required in order to find a
261     // module's structure when its headers/module map are mapped in the VFS.
262     // We should remove this as soon as we can properly support a file having
263     // multiple names.
264     if (DirInfo != UFE.Dir && Status.IsVFSMapped)
265       UFE.Dir = DirInfo;
266 
267     // Always update the name to use the last name by which a file was accessed.
268     // FIXME: Neither this nor always using the first name is correct; we want
269     // to switch towards a design where we return a FileName object that
270     // encapsulates both the name by which the file was accessed and the
271     // corresponding FileEntry.
272     UFE.Name = InterndFileName;
273 
274     return &UFE;
275   }
276 
277   // Otherwise, we don't have this file yet, add it.
278   UFE.Name    = InterndFileName;
279   UFE.Size    = Status.getSize();
280   UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
281   UFE.Dir     = DirInfo;
282   UFE.UID     = NextFileUID++;
283   UFE.UniqueID = Status.getUniqueID();
284   UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
285   UFE.File = std::move(F);
286   UFE.IsValid = true;
287 
288   if (UFE.File) {
289     if (auto PathName = UFE.File->getName())
290       fillRealPathName(&UFE, *PathName);
291   } else if (!openFile) {
292     // We should still fill the path even if we aren't opening the file.
293     fillRealPathName(&UFE, InterndFileName);
294   }
295   return &UFE;
296 }
297 
298 const FileEntry *
299 FileManager::getVirtualFile(StringRef Filename, off_t Size,
300                             time_t ModificationTime) {
301   ++NumFileLookups;
302 
303   // See if there is already an entry in the map for an existing file.
304   auto &NamedFileEnt = *SeenFileEntries.insert(
305       {Filename, std::errc::no_such_file_or_directory}).first;
306   if (NamedFileEnt.second)
307     return &*NamedFileEnt.second;
308 
309   // We've not seen this before, or the file is cached as non-existent.
310   ++NumFileCacheMisses;
311   addAncestorsAsVirtualDirs(Filename);
312   FileEntry *UFE = nullptr;
313 
314   // Now that all ancestors of Filename are in the cache, the
315   // following call is guaranteed to find the DirectoryEntry from the
316   // cache.
317   auto DirInfo = getDirectoryFromFile(*this, Filename, /*CacheFailure=*/true);
318   assert(DirInfo &&
319          "The directory of a virtual file should already be in the cache.");
320 
321   // Check to see if the file exists. If so, drop the virtual file
322   llvm::vfs::Status Status;
323   const char *InterndFileName = NamedFileEnt.first().data();
324   if (!getStatValue(InterndFileName, Status, true, nullptr)) {
325     UFE = &UniqueRealFiles[Status.getUniqueID()];
326     Status = llvm::vfs::Status(
327       Status.getName(), Status.getUniqueID(),
328       llvm::sys::toTimePoint(ModificationTime),
329       Status.getUser(), Status.getGroup(), Size,
330       Status.getType(), Status.getPermissions());
331 
332     NamedFileEnt.second = *UFE;
333 
334     // If we had already opened this file, close it now so we don't
335     // leak the descriptor. We're not going to use the file
336     // descriptor anyway, since this is a virtual file.
337     if (UFE->File)
338       UFE->closeFile();
339 
340     // If we already have an entry with this inode, return it.
341     if (UFE->isValid())
342       return UFE;
343 
344     UFE->UniqueID = Status.getUniqueID();
345     UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
346     fillRealPathName(UFE, Status.getName());
347   } else {
348     VirtualFileEntries.push_back(std::make_unique<FileEntry>());
349     UFE = VirtualFileEntries.back().get();
350     NamedFileEnt.second = *UFE;
351   }
352 
353   UFE->Name    = InterndFileName;
354   UFE->Size    = Size;
355   UFE->ModTime = ModificationTime;
356   UFE->Dir     = *DirInfo;
357   UFE->UID     = NextFileUID++;
358   UFE->IsValid = true;
359   UFE->File.reset();
360   return UFE;
361 }
362 
363 bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
364   StringRef pathRef(path.data(), path.size());
365 
366   if (FileSystemOpts.WorkingDir.empty()
367       || llvm::sys::path::is_absolute(pathRef))
368     return false;
369 
370   SmallString<128> NewPath(FileSystemOpts.WorkingDir);
371   llvm::sys::path::append(NewPath, pathRef);
372   path = NewPath;
373   return true;
374 }
375 
376 bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
377   bool Changed = FixupRelativePath(Path);
378 
379   if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
380     FS->makeAbsolute(Path);
381     Changed = true;
382   }
383 
384   return Changed;
385 }
386 
387 void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
388   llvm::SmallString<128> AbsPath(FileName);
389   // This is not the same as `VFS::getRealPath()`, which resolves symlinks
390   // but can be very expensive on real file systems.
391   // FIXME: the semantic of RealPathName is unclear, and the name might be
392   // misleading. We need to clean up the interface here.
393   makeAbsolutePath(AbsPath);
394   llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
395   UFE->RealPathName = AbsPath.str();
396 }
397 
398 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
399 FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
400                               bool ShouldCloseOpenFile) {
401   uint64_t FileSize = Entry->getSize();
402   // If there's a high enough chance that the file have changed since we
403   // got its size, force a stat before opening it.
404   if (isVolatile)
405     FileSize = -1;
406 
407   StringRef Filename = Entry->getName();
408   // If the file is already open, use the open file descriptor.
409   if (Entry->File) {
410     auto Result =
411         Entry->File->getBuffer(Filename, FileSize,
412                                /*RequiresNullTerminator=*/true, isVolatile);
413     // FIXME: we need a set of APIs that can make guarantees about whether a
414     // FileEntry is open or not.
415     if (ShouldCloseOpenFile)
416       Entry->closeFile();
417     return Result;
418   }
419 
420   // Otherwise, open the file.
421 
422   if (FileSystemOpts.WorkingDir.empty())
423     return FS->getBufferForFile(Filename, FileSize,
424                                 /*RequiresNullTerminator=*/true, isVolatile);
425 
426   SmallString<128> FilePath(Entry->getName());
427   FixupRelativePath(FilePath);
428   return FS->getBufferForFile(FilePath, FileSize,
429                               /*RequiresNullTerminator=*/true, isVolatile);
430 }
431 
432 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
433 FileManager::getBufferForFile(StringRef Filename, bool isVolatile) {
434   if (FileSystemOpts.WorkingDir.empty())
435     return FS->getBufferForFile(Filename, -1, true, isVolatile);
436 
437   SmallString<128> FilePath(Filename);
438   FixupRelativePath(FilePath);
439   return FS->getBufferForFile(FilePath.c_str(), -1, true, isVolatile);
440 }
441 
442 /// getStatValue - Get the 'stat' information for the specified path,
443 /// using the cache to accelerate it if possible.  This returns true
444 /// if the path points to a virtual file or does not exist, or returns
445 /// false if it's an existent real file.  If FileDescriptor is NULL,
446 /// do directory look-up instead of file look-up.
447 std::error_code
448 FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
449                           bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
450   // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
451   // absolute!
452   if (FileSystemOpts.WorkingDir.empty())
453     return FileSystemStatCache::get(Path, Status, isFile, F,
454                                     StatCache.get(), *FS);
455 
456   SmallString<128> FilePath(Path);
457   FixupRelativePath(FilePath);
458 
459   return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
460                                   StatCache.get(), *FS);
461 }
462 
463 std::error_code
464 FileManager::getNoncachedStatValue(StringRef Path,
465                                    llvm::vfs::Status &Result) {
466   SmallString<128> FilePath(Path);
467   FixupRelativePath(FilePath);
468 
469   llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
470   if (!S)
471     return S.getError();
472   Result = *S;
473   return std::error_code();
474 }
475 
476 void FileManager::invalidateCache(const FileEntry *Entry) {
477   assert(Entry && "Cannot invalidate a NULL FileEntry");
478 
479   SeenFileEntries.erase(Entry->getName());
480 
481   // FileEntry invalidation should not block future optimizations in the file
482   // caches. Possible alternatives are cache truncation (invalidate last N) or
483   // invalidation of the whole cache.
484   //
485   // FIXME: This is broken. We sometimes have the same FileEntry* shared
486   // betweeen multiple SeenFileEntries, so this can leave dangling pointers.
487   UniqueRealFiles.erase(Entry->getUniqueID());
488 }
489 
490 void FileManager::GetUniqueIDMapping(
491                    SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
492   UIDToFiles.clear();
493   UIDToFiles.resize(NextFileUID);
494 
495   // Map file entries
496   for (llvm::StringMap<llvm::ErrorOr<FileEntry &>,
497                        llvm::BumpPtrAllocator>::const_iterator
498          FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
499        FE != FEEnd; ++FE)
500     if (auto Entry = FE->getValue()) {
501       UIDToFiles[Entry->getUID()] = &*Entry;
502     }
503 
504   // Map virtual file entries
505   for (const auto &VFE : VirtualFileEntries)
506     UIDToFiles[VFE->getUID()] = VFE.get();
507 }
508 
509 void FileManager::modifyFileEntry(FileEntry *File,
510                                   off_t Size, time_t ModificationTime) {
511   File->Size = Size;
512   File->ModTime = ModificationTime;
513 }
514 
515 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
516   // FIXME: use llvm::sys::fs::canonical() when it gets implemented
517   llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
518     = CanonicalDirNames.find(Dir);
519   if (Known != CanonicalDirNames.end())
520     return Known->second;
521 
522   StringRef CanonicalName(Dir->getName());
523 
524   SmallString<4096> CanonicalNameBuf;
525   if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
526     CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
527 
528   CanonicalDirNames.insert({Dir, CanonicalName});
529   return CanonicalName;
530 }
531 
532 void FileManager::PrintStats() const {
533   llvm::errs() << "\n*** File Manager Stats:\n";
534   llvm::errs() << UniqueRealFiles.size() << " real files found, "
535                << UniqueRealDirs.size() << " real dirs found.\n";
536   llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
537                << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
538   llvm::errs() << NumDirLookups << " dir lookups, "
539                << NumDirCacheMisses << " dir cache misses.\n";
540   llvm::errs() << NumFileLookups << " file lookups, "
541                << NumFileCacheMisses << " file cache misses.\n";
542 
543   //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
544 }
545