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