xref: /llvm-project/clang/lib/Basic/FileManager.cpp (revision ab86fbe4250bf81f46025f9d1b50dfa1c07da9c5)
1 //===--- FileManager.cpp - File System Probing and Caching ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the FileManager interface.
11 //
12 //===----------------------------------------------------------------------===//
13 //
14 // TODO: This should index all interesting directories with dirent calls.
15 //  getdirentries ?
16 //  opendir/readdir_r/closedir ?
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "clang/Basic/FileManager.h"
21 #include "clang/Basic/FileSystemStatCache.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/Config/llvm-config.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 <map>
29 #include <set>
30 #include <string>
31 #include <system_error>
32 
33 using namespace clang;
34 
35 /// NON_EXISTENT_DIR - A special value distinct from null that is used to
36 /// represent a dir name that doesn't exist on the disk.
37 #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
38 
39 /// NON_EXISTENT_FILE - A special value distinct from null that is used to
40 /// represent a filename that doesn't exist on the disk.
41 #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
42 
43 //===----------------------------------------------------------------------===//
44 // Common logic.
45 //===----------------------------------------------------------------------===//
46 
47 FileManager::FileManager(const FileSystemOptions &FSO,
48                          IntrusiveRefCntPtr<vfs::FileSystem> FS)
49   : FS(FS), FileSystemOpts(FSO),
50     SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
51   NumDirLookups = NumFileLookups = 0;
52   NumDirCacheMisses = NumFileCacheMisses = 0;
53 
54   // If the caller doesn't provide a virtual file system, just grab the real
55   // file system.
56   if (!FS)
57     this->FS = vfs::getRealFileSystem();
58 }
59 
60 FileManager::~FileManager() {
61   for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
62     delete VirtualFileEntries[i];
63   for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
64     delete VirtualDirectoryEntries[i];
65 }
66 
67 void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache,
68                                bool AtBeginning) {
69   assert(statCache && "No stat cache provided?");
70   if (AtBeginning || !StatCache.get()) {
71     statCache->setNextStatCache(std::move(StatCache));
72     StatCache = std::move(statCache);
73     return;
74   }
75 
76   FileSystemStatCache *LastCache = StatCache.get();
77   while (LastCache->getNextStatCache())
78     LastCache = LastCache->getNextStatCache();
79 
80   LastCache->setNextStatCache(std::move(statCache));
81 }
82 
83 void FileManager::removeStatCache(FileSystemStatCache *statCache) {
84   if (!statCache)
85     return;
86 
87   if (StatCache.get() == statCache) {
88     // This is the first stat cache.
89     StatCache = StatCache->takeNextStatCache();
90     return;
91   }
92 
93   // Find the stat cache in the list.
94   FileSystemStatCache *PrevCache = StatCache.get();
95   while (PrevCache && PrevCache->getNextStatCache() != statCache)
96     PrevCache = PrevCache->getNextStatCache();
97 
98   assert(PrevCache && "Stat cache not found for removal");
99   PrevCache->setNextStatCache(statCache->takeNextStatCache());
100 }
101 
102 void FileManager::clearStatCaches() {
103   StatCache.reset();
104 }
105 
106 /// \brief Retrieve the directory that the given file name resides in.
107 /// Filename can point to either a real file or a virtual file.
108 static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
109                                                   StringRef Filename,
110                                                   bool CacheFailure) {
111   if (Filename.empty())
112     return nullptr;
113 
114   if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
115     return nullptr; // If Filename is a directory.
116 
117   StringRef DirName = llvm::sys::path::parent_path(Filename);
118   // Use the current directory if file has no path component.
119   if (DirName.empty())
120     DirName = ".";
121 
122   return FileMgr.getDirectory(DirName, CacheFailure);
123 }
124 
125 /// Add all ancestors of the given path (pointing to either a file or
126 /// a directory) as virtual directories.
127 void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
128   StringRef DirName = llvm::sys::path::parent_path(Path);
129   if (DirName.empty())
130     return;
131 
132   llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
133     SeenDirEntries.GetOrCreateValue(DirName);
134 
135   // When caching a virtual directory, we always cache its ancestors
136   // at the same time.  Therefore, if DirName is already in the cache,
137   // we don't need to recurse as its ancestors must also already be in
138   // the cache.
139   if (NamedDirEnt.getValue())
140     return;
141 
142   // Add the virtual directory to the cache.
143   DirectoryEntry *UDE = new DirectoryEntry;
144   UDE->Name = NamedDirEnt.getKeyData();
145   NamedDirEnt.setValue(UDE);
146   VirtualDirectoryEntries.push_back(UDE);
147 
148   // Recursively add the other ancestors.
149   addAncestorsAsVirtualDirs(DirName);
150 }
151 
152 const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
153                                                 bool CacheFailure) {
154   // stat doesn't like trailing separators except for root directory.
155   // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
156   // (though it can strip '\\')
157   if (DirName.size() > 1 &&
158       DirName != llvm::sys::path::root_path(DirName) &&
159       llvm::sys::path::is_separator(DirName.back()))
160     DirName = DirName.substr(0, DirName.size()-1);
161 #ifdef LLVM_ON_WIN32
162   // Fixing a problem with "clang C:test.c" on Windows.
163   // Stat("C:") does not recognize "C:" as a valid directory
164   std::string DirNameStr;
165   if (DirName.size() > 1 && DirName.back() == ':' &&
166       DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
167     DirNameStr = DirName.str() + '.';
168     DirName = DirNameStr;
169   }
170 #endif
171 
172   ++NumDirLookups;
173   llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
174     SeenDirEntries.GetOrCreateValue(DirName);
175 
176   // See if there was already an entry in the map.  Note that the map
177   // contains both virtual and real directories.
178   if (NamedDirEnt.getValue())
179     return NamedDirEnt.getValue() == NON_EXISTENT_DIR ? nullptr
180                                                       : NamedDirEnt.getValue();
181 
182   ++NumDirCacheMisses;
183 
184   // By default, initialize it to invalid.
185   NamedDirEnt.setValue(NON_EXISTENT_DIR);
186 
187   // Get the null-terminated directory name as stored as the key of the
188   // SeenDirEntries map.
189   const char *InterndDirName = NamedDirEnt.getKeyData();
190 
191   // Check to see if the directory exists.
192   FileData Data;
193   if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) {
194     // There's no real directory at the given path.
195     if (!CacheFailure)
196       SeenDirEntries.erase(DirName);
197     return nullptr;
198   }
199 
200   // It exists.  See if we have already opened a directory with the
201   // same inode (this occurs on Unix-like systems when one dir is
202   // symlinked to another, for example) or the same path (on
203   // Windows).
204   DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID];
205 
206   NamedDirEnt.setValue(&UDE);
207   if (!UDE.getName()) {
208     // We don't have this directory yet, add it.  We use the string
209     // key from the SeenDirEntries map as the string.
210     UDE.Name  = InterndDirName;
211   }
212 
213   return &UDE;
214 }
215 
216 const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
217                                       bool CacheFailure) {
218   ++NumFileLookups;
219 
220   // See if there is already an entry in the map.
221   llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
222     SeenFileEntries.GetOrCreateValue(Filename);
223 
224   // See if there is already an entry in the map.
225   if (NamedFileEnt.getValue())
226     return NamedFileEnt.getValue() == NON_EXISTENT_FILE
227                  ? nullptr : NamedFileEnt.getValue();
228 
229   ++NumFileCacheMisses;
230 
231   // By default, initialize it to invalid.
232   NamedFileEnt.setValue(NON_EXISTENT_FILE);
233 
234   // Get the null-terminated file name as stored as the key of the
235   // SeenFileEntries map.
236   const char *InterndFileName = NamedFileEnt.getKeyData();
237 
238   // Look up the directory for the file.  When looking up something like
239   // sys/foo.h we'll discover all of the search directories that have a 'sys'
240   // subdirectory.  This will let us avoid having to waste time on known-to-fail
241   // searches when we go to find sys/bar.h, because all the search directories
242   // without a 'sys' subdir will get a cached failure result.
243   const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
244                                                        CacheFailure);
245   if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
246     if (!CacheFailure)
247       SeenFileEntries.erase(Filename);
248 
249     return nullptr;
250   }
251 
252   // FIXME: Use the directory info to prune this, before doing the stat syscall.
253   // FIXME: This will reduce the # syscalls.
254 
255   // Nope, there isn't.  Check to see if the file exists.
256   std::unique_ptr<vfs::File> F;
257   FileData Data;
258   if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) {
259     // There's no real file at the given path.
260     if (!CacheFailure)
261       SeenFileEntries.erase(Filename);
262 
263     return nullptr;
264   }
265 
266   assert((openFile || !F) && "undesired open file");
267 
268   // It exists.  See if we have already opened a file with the same inode.
269   // This occurs when one dir is symlinked to another, for example.
270   FileEntry &UFE = UniqueRealFiles[Data.UniqueID];
271 
272   NamedFileEnt.setValue(&UFE);
273 
274   // If the name returned by getStatValue is different than Filename, re-intern
275   // the name.
276   if (Data.Name != Filename) {
277     auto &NamedFileEnt = SeenFileEntries.GetOrCreateValue(Data.Name);
278     if (!NamedFileEnt.getValue())
279       NamedFileEnt.setValue(&UFE);
280     else
281       assert(NamedFileEnt.getValue() == &UFE &&
282              "filename from getStatValue() refers to wrong file");
283     InterndFileName = NamedFileEnt.getKeyData();
284   }
285 
286   if (UFE.isValid()) { // Already have an entry with this inode, return it.
287 
288     // FIXME: this hack ensures that if we look up a file by a virtual path in
289     // the VFS that the getDir() will have the virtual path, even if we found
290     // the file by a 'real' path first. This is required in order to find a
291     // module's structure when its headers/module map are mapped in the VFS.
292     // We should remove this as soon as we can properly support a file having
293     // multiple names.
294     if (DirInfo != UFE.Dir && Data.IsVFSMapped)
295       UFE.Dir = DirInfo;
296 
297     // Always update the name to use the last name by which a file was accessed.
298     // FIXME: Neither this nor always using the first name is correct; we want
299     // to switch towards a design where we return a FileName object that
300     // encapsulates both the name by which the file was accessed and the
301     // corresponding FileEntry.
302     UFE.Name = InterndFileName;
303 
304     return &UFE;
305   }
306 
307   // Otherwise, we don't have this file yet, add it.
308   UFE.Name    = InterndFileName;
309   UFE.Size = Data.Size;
310   UFE.ModTime = Data.ModTime;
311   UFE.Dir     = DirInfo;
312   UFE.UID     = NextFileUID++;
313   UFE.UniqueID = Data.UniqueID;
314   UFE.IsNamedPipe = Data.IsNamedPipe;
315   UFE.InPCH = Data.InPCH;
316   UFE.File = std::move(F);
317   UFE.IsValid = true;
318   return &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.
327   llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
328     SeenFileEntries.GetOrCreateValue(Filename);
329 
330   // See if there is already an entry in the map.
331   if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
332     return NamedFileEnt.getValue();
333 
334   ++NumFileCacheMisses;
335 
336   // By default, initialize it to invalid.
337   NamedFileEnt.setValue(NON_EXISTENT_FILE);
338 
339   addAncestorsAsVirtualDirs(Filename);
340   FileEntry *UFE = nullptr;
341 
342   // Now that all ancestors of Filename are in the cache, the
343   // following call is guaranteed to find the DirectoryEntry from the
344   // cache.
345   const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
346                                                        /*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   FileData Data;
352   const char *InterndFileName = NamedFileEnt.getKeyData();
353   if (getStatValue(InterndFileName, Data, true, nullptr) == 0) {
354     Data.Size = Size;
355     Data.ModTime = ModificationTime;
356     UFE = &UniqueRealFiles[Data.UniqueID];
357 
358     NamedFileEnt.setValue(UFE);
359 
360     // If we had already opened this file, close it now so we don't
361     // leak the descriptor. We're not going to use the file
362     // descriptor anyway, since this is a virtual file.
363     if (UFE->File)
364       UFE->closeFile();
365 
366     // If we already have an entry with this inode, return it.
367     if (UFE->isValid())
368       return UFE;
369 
370     UFE->UniqueID = Data.UniqueID;
371     UFE->IsNamedPipe = Data.IsNamedPipe;
372     UFE->InPCH = Data.InPCH;
373   }
374 
375   if (!UFE) {
376     UFE = new FileEntry();
377     VirtualFileEntries.push_back(UFE);
378     NamedFileEnt.setValue(UFE);
379   }
380 
381   UFE->Name    = InterndFileName;
382   UFE->Size    = Size;
383   UFE->ModTime = ModificationTime;
384   UFE->Dir     = DirInfo;
385   UFE->UID     = NextFileUID++;
386   UFE->File.reset();
387   return UFE;
388 }
389 
390 void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
391   StringRef pathRef(path.data(), path.size());
392 
393   if (FileSystemOpts.WorkingDir.empty()
394       || llvm::sys::path::is_absolute(pathRef))
395     return;
396 
397   SmallString<128> NewPath(FileSystemOpts.WorkingDir);
398   llvm::sys::path::append(NewPath, pathRef);
399   path = NewPath;
400 }
401 
402 std::unique_ptr<llvm::MemoryBuffer>
403 FileManager::getBufferForFile(const FileEntry *Entry, std::string *ErrorStr,
404                               bool isVolatile, bool ShouldCloseOpenFile) {
405   std::unique_ptr<llvm::MemoryBuffer> Result;
406   std::error_code ec;
407 
408   uint64_t FileSize = Entry->getSize();
409   // If there's a high enough chance that the file have changed since we
410   // got its size, force a stat before opening it.
411   if (isVolatile)
412     FileSize = -1;
413 
414   const char *Filename = Entry->getName();
415   // If the file is already open, use the open file descriptor.
416   if (Entry->File) {
417     ec = Entry->File->getBuffer(Filename, Result, FileSize,
418                                 /*RequiresNullTerminator=*/true, isVolatile);
419     if (ErrorStr)
420       *ErrorStr = ec.message();
421     // FIXME: we need a set of APIs that can make guarantees about whether a
422     // FileEntry is open or not.
423     if (ShouldCloseOpenFile)
424       Entry->closeFile();
425     return Result;
426   }
427 
428   // Otherwise, open the file.
429 
430   if (FileSystemOpts.WorkingDir.empty()) {
431     ec = FS->getBufferForFile(Filename, Result, FileSize,
432                               /*RequiresNullTerminator=*/true, isVolatile);
433     if (ec && ErrorStr)
434       *ErrorStr = ec.message();
435     return Result;
436   }
437 
438   SmallString<128> FilePath(Entry->getName());
439   FixupRelativePath(FilePath);
440   ec = FS->getBufferForFile(FilePath.str(), Result, FileSize,
441                             /*RequiresNullTerminator=*/true, isVolatile);
442   if (ec && ErrorStr)
443     *ErrorStr = ec.message();
444   return Result;
445 }
446 
447 std::unique_ptr<llvm::MemoryBuffer>
448 FileManager::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
449   std::unique_ptr<llvm::MemoryBuffer> Result;
450   std::error_code ec;
451   if (FileSystemOpts.WorkingDir.empty()) {
452     ec = FS->getBufferForFile(Filename, Result);
453     if (ec && ErrorStr)
454       *ErrorStr = ec.message();
455     return Result;
456   }
457 
458   SmallString<128> FilePath(Filename);
459   FixupRelativePath(FilePath);
460   ec = FS->getBufferForFile(FilePath.c_str(), Result);
461   if (ec && ErrorStr)
462     *ErrorStr = ec.message();
463   return Result;
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 bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile,
472                                std::unique_ptr<vfs::File> *F) {
473   // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
474   // absolute!
475   if (FileSystemOpts.WorkingDir.empty())
476     return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
477 
478   SmallString<128> FilePath(Path);
479   FixupRelativePath(FilePath);
480 
481   return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
482                                   StatCache.get(), *FS);
483 }
484 
485 bool FileManager::getNoncachedStatValue(StringRef Path,
486                                         vfs::Status &Result) {
487   SmallString<128> FilePath(Path);
488   FixupRelativePath(FilePath);
489 
490   llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str());
491   if (!S)
492     return true;
493   Result = *S;
494   return false;
495 }
496 
497 void FileManager::invalidateCache(const FileEntry *Entry) {
498   assert(Entry && "Cannot invalidate a NULL FileEntry");
499 
500   SeenFileEntries.erase(Entry->getName());
501 
502   // FileEntry invalidation should not block future optimizations in the file
503   // caches. Possible alternatives are cache truncation (invalidate last N) or
504   // invalidation of the whole cache.
505   UniqueRealFiles.erase(Entry->getUniqueID());
506 }
507 
508 
509 void FileManager::GetUniqueIDMapping(
510                    SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
511   UIDToFiles.clear();
512   UIDToFiles.resize(NextFileUID);
513 
514   // Map file entries
515   for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
516          FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
517        FE != FEEnd; ++FE)
518     if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
519       UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
520 
521   // Map virtual file entries
522   for (SmallVectorImpl<FileEntry *>::const_iterator
523          VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
524        VFE != VFEEnd; ++VFE)
525     if (*VFE && *VFE != NON_EXISTENT_FILE)
526       UIDToFiles[(*VFE)->getUID()] = *VFE;
527 }
528 
529 void FileManager::modifyFileEntry(FileEntry *File,
530                                   off_t Size, time_t ModificationTime) {
531   File->Size = Size;
532   File->ModTime = ModificationTime;
533 }
534 
535 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
536   // FIXME: use llvm::sys::fs::canonical() when it gets implemented
537 #ifdef LLVM_ON_UNIX
538   llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
539     = CanonicalDirNames.find(Dir);
540   if (Known != CanonicalDirNames.end())
541     return Known->second;
542 
543   StringRef CanonicalName(Dir->getName());
544   char CanonicalNameBuf[PATH_MAX];
545   if (realpath(Dir->getName(), CanonicalNameBuf)) {
546     unsigned Len = strlen(CanonicalNameBuf);
547     char *Mem = static_cast<char *>(CanonicalNameStorage.Allocate(Len, 1));
548     memcpy(Mem, CanonicalNameBuf, Len);
549     CanonicalName = StringRef(Mem, Len);
550   }
551 
552   CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
553   return CanonicalName;
554 #else
555   return StringRef(Dir->getName());
556 #endif
557 }
558 
559 void FileManager::PrintStats() const {
560   llvm::errs() << "\n*** File Manager Stats:\n";
561   llvm::errs() << UniqueRealFiles.size() << " real files found, "
562                << UniqueRealDirs.size() << " real dirs found.\n";
563   llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
564                << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
565   llvm::errs() << NumDirLookups << " dir lookups, "
566                << NumDirCacheMisses << " dir cache misses.\n";
567   llvm::errs() << NumFileLookups << " file lookups, "
568                << NumFileCacheMisses << " file cache misses.\n";
569 
570   //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
571 }
572