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