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