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