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