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