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