1 //===--- FileManager.cpp - File System Probing and Caching ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the FileManager interface.
12 //===----------------------------------------------------------------------===//
14 // TODO: This should index all interesting directories with dirent calls.
16 // opendir/readdir_r/closedir ?
18 //===----------------------------------------------------------------------===//
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"
32 #include <system_error>
34 using namespace clang;
36 /// NON_EXISTENT_DIR - A special value distinct from null that is used to
37 /// represent a dir name that doesn't exist on the disk.
38 #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
40 /// NON_EXISTENT_FILE - A special value distinct from null that is used to
41 /// represent a filename that doesn't exist on the disk.
42 #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
44 //===----------------------------------------------------------------------===//
46 //===----------------------------------------------------------------------===//
48 FileManager::FileManager(const FileSystemOptions &FSO,
49 IntrusiveRefCntPtr<vfs::FileSystem> FS)
50 : FS(FS), FileSystemOpts(FSO),
51 SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
52 NumDirLookups = NumFileLookups = 0;
53 NumDirCacheMisses = NumFileCacheMisses = 0;
55 // If the caller doesn't provide a virtual file system, just grab the real
58 this->FS = vfs::getRealFileSystem();
61 FileManager::~FileManager() = default;
63 void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache,
65 assert(statCache && "No stat cache provided?");
66 if (AtBeginning || !StatCache.get()) {
67 statCache->setNextStatCache(std::move(StatCache));
68 StatCache = std::move(statCache);
72 FileSystemStatCache *LastCache = StatCache.get();
73 while (LastCache->getNextStatCache())
74 LastCache = LastCache->getNextStatCache();
76 LastCache->setNextStatCache(std::move(statCache));
79 void FileManager::removeStatCache(FileSystemStatCache *statCache) {
83 if (StatCache.get() == statCache) {
84 // This is the first stat cache.
85 StatCache = StatCache->takeNextStatCache();
89 // Find the stat cache in the list.
90 FileSystemStatCache *PrevCache = StatCache.get();
91 while (PrevCache && PrevCache->getNextStatCache() != statCache)
92 PrevCache = PrevCache->getNextStatCache();
94 assert(PrevCache && "Stat cache not found for removal");
95 PrevCache->setNextStatCache(statCache->takeNextStatCache());
98 void FileManager::clearStatCaches() {
102 /// \brief Retrieve the directory that the given file name resides in.
103 /// Filename can point to either a real file or a virtual file.
104 static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
107 if (Filename.empty())
110 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
111 return nullptr; // If Filename is a directory.
113 StringRef DirName = llvm::sys::path::parent_path(Filename);
114 // Use the current directory if file has no path component.
118 return FileMgr.getDirectory(DirName, CacheFailure);
121 /// Add all ancestors of the given path (pointing to either a file or
122 /// a directory) as virtual directories.
123 void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
124 StringRef DirName = llvm::sys::path::parent_path(Path);
129 *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
131 // When caching a virtual directory, we always cache its ancestors
132 // at the same time. Therefore, if DirName is already in the cache,
133 // we don't need to recurse as its ancestors must also already be in
135 if (NamedDirEnt.second && NamedDirEnt.second != NON_EXISTENT_DIR)
138 // Add the virtual directory to the cache.
139 auto UDE = llvm::make_unique<DirectoryEntry>();
140 UDE->Name = NamedDirEnt.first().data();
141 NamedDirEnt.second = UDE.get();
142 VirtualDirectoryEntries.push_back(std::move(UDE));
144 // Recursively add the other ancestors.
145 addAncestorsAsVirtualDirs(DirName);
148 const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
150 // stat doesn't like trailing separators except for root directory.
151 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
152 // (though it can strip '\\')
153 if (DirName.size() > 1 &&
154 DirName != llvm::sys::path::root_path(DirName) &&
155 llvm::sys::path::is_separator(DirName.back()))
156 DirName = DirName.substr(0, DirName.size()-1);
158 // Fixing a problem with "clang C:test.c" on Windows.
159 // Stat("C:") does not recognize "C:" as a valid directory
160 std::string DirNameStr;
161 if (DirName.size() > 1 && DirName.back() == ':' &&
162 DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
163 DirNameStr = DirName.str() + '.';
164 DirName = DirNameStr;
170 *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
172 // See if there was already an entry in the map. Note that the map
173 // contains both virtual and real directories.
174 if (NamedDirEnt.second)
175 return NamedDirEnt.second == NON_EXISTENT_DIR ? nullptr
176 : NamedDirEnt.second;
180 // By default, initialize it to invalid.
181 NamedDirEnt.second = NON_EXISTENT_DIR;
183 // Get the null-terminated directory name as stored as the key of the
184 // SeenDirEntries map.
185 const char *InterndDirName = NamedDirEnt.first().data();
187 // Check to see if the directory exists.
189 if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) {
190 // There's no real directory at the given path.
192 SeenDirEntries.erase(DirName);
196 // It exists. See if we have already opened a directory with the
197 // same inode (this occurs on Unix-like systems when one dir is
198 // symlinked to another, for example) or the same path (on
200 DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID];
202 NamedDirEnt.second = &UDE;
203 if (!UDE.getName()) {
204 // We don't have this directory yet, add it. We use the string
205 // key from the SeenDirEntries map as the string.
206 UDE.Name = InterndDirName;
212 const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
216 // See if there is already an entry in the map.
218 *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
220 // See if there is already an entry in the map.
221 if (NamedFileEnt.second)
222 return NamedFileEnt.second == NON_EXISTENT_FILE ? nullptr
223 : NamedFileEnt.second;
225 ++NumFileCacheMisses;
227 // By default, initialize it to invalid.
228 NamedFileEnt.second = NON_EXISTENT_FILE;
230 // Get the null-terminated file name as stored as the key of the
231 // SeenFileEntries map.
232 const char *InterndFileName = NamedFileEnt.first().data();
234 // Look up the directory for the file. When looking up something like
235 // sys/foo.h we'll discover all of the search directories that have a 'sys'
236 // subdirectory. This will let us avoid having to waste time on known-to-fail
237 // searches when we go to find sys/bar.h, because all the search directories
238 // without a 'sys' subdir will get a cached failure result.
239 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
241 if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
243 SeenFileEntries.erase(Filename);
248 // FIXME: Use the directory info to prune this, before doing the stat syscall.
249 // FIXME: This will reduce the # syscalls.
251 // Nope, there isn't. Check to see if the file exists.
252 std::unique_ptr<vfs::File> F;
254 if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) {
255 // There's no real file at the given path.
257 SeenFileEntries.erase(Filename);
262 assert((openFile || !F) && "undesired open file");
264 // It exists. See if we have already opened a file with the same inode.
265 // This occurs when one dir is symlinked to another, for example.
266 FileEntry &UFE = UniqueRealFiles[Data.UniqueID];
268 NamedFileEnt.second = &UFE;
270 // If the name returned by getStatValue is different than Filename, re-intern
272 if (Data.Name != Filename) {
274 *SeenFileEntries.insert(std::make_pair(Data.Name, nullptr)).first;
275 if (!NamedFileEnt.second)
276 NamedFileEnt.second = &UFE;
278 assert(NamedFileEnt.second == &UFE &&
279 "filename from getStatValue() refers to wrong file");
280 InterndFileName = NamedFileEnt.first().data();
283 if (UFE.isValid()) { // Already have an entry with this inode, return it.
285 // FIXME: this hack ensures that if we look up a file by a virtual path in
286 // the VFS that the getDir() will have the virtual path, even if we found
287 // the file by a 'real' path first. This is required in order to find a
288 // module's structure when its headers/module map are mapped in the VFS.
289 // We should remove this as soon as we can properly support a file having
291 if (DirInfo != UFE.Dir && Data.IsVFSMapped)
294 // Always update the name to use the last name by which a file was accessed.
295 // FIXME: Neither this nor always using the first name is correct; we want
296 // to switch towards a design where we return a FileName object that
297 // encapsulates both the name by which the file was accessed and the
298 // corresponding FileEntry.
299 UFE.Name = InterndFileName;
304 // Otherwise, we don't have this file yet, add it.
305 UFE.Name = InterndFileName;
306 UFE.Size = Data.Size;
307 UFE.ModTime = Data.ModTime;
309 UFE.UID = NextFileUID++;
310 UFE.UniqueID = Data.UniqueID;
311 UFE.IsNamedPipe = Data.IsNamedPipe;
312 UFE.InPCH = Data.InPCH;
313 UFE.File = std::move(F);
316 if (auto RealPathName = UFE.File->getName())
317 UFE.RealPathName = *RealPathName;
322 FileManager::getVirtualFile(StringRef Filename, off_t Size,
323 time_t ModificationTime) {
326 // See if there is already an entry in the map.
328 *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
330 // See if there is already an entry in the map.
331 if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE)
332 return NamedFileEnt.second;
334 ++NumFileCacheMisses;
336 // By default, initialize it to invalid.
337 NamedFileEnt.second = NON_EXISTENT_FILE;
339 addAncestorsAsVirtualDirs(Filename);
340 FileEntry *UFE = nullptr;
342 // Now that all ancestors of Filename are in the cache, the
343 // following call is guaranteed to find the DirectoryEntry from the
345 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
346 /*CacheFailure=*/true);
348 "The directory of a virtual file should already be in the cache.");
350 // Check to see if the file exists. If so, drop the virtual file
352 const char *InterndFileName = NamedFileEnt.first().data();
353 if (getStatValue(InterndFileName, Data, true, nullptr) == 0) {
355 Data.ModTime = ModificationTime;
356 UFE = &UniqueRealFiles[Data.UniqueID];
358 NamedFileEnt.second = UFE;
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.
366 // If we already have an entry with this inode, return it.
370 UFE->UniqueID = Data.UniqueID;
371 UFE->IsNamedPipe = Data.IsNamedPipe;
372 UFE->InPCH = Data.InPCH;
376 VirtualFileEntries.push_back(llvm::make_unique<FileEntry>());
377 UFE = VirtualFileEntries.back().get();
378 NamedFileEnt.second = UFE;
381 UFE->Name = InterndFileName;
383 UFE->ModTime = ModificationTime;
385 UFE->UID = NextFileUID++;
390 bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
391 StringRef pathRef(path.data(), path.size());
393 if (FileSystemOpts.WorkingDir.empty()
394 || llvm::sys::path::is_absolute(pathRef))
397 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
398 llvm::sys::path::append(NewPath, pathRef);
403 bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
404 bool Changed = FixupRelativePath(Path);
406 if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
407 llvm::sys::fs::make_absolute(Path);
414 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
415 FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
416 bool ShouldCloseOpenFile) {
417 uint64_t FileSize = Entry->getSize();
418 // If there's a high enough chance that the file have changed since we
419 // got its size, force a stat before opening it.
423 const char *Filename = Entry->getName();
424 // If the file is already open, use the open file descriptor.
427 Entry->File->getBuffer(Filename, FileSize,
428 /*RequiresNullTerminator=*/true, isVolatile);
429 // FIXME: we need a set of APIs that can make guarantees about whether a
430 // FileEntry is open or not.
431 if (ShouldCloseOpenFile)
436 // Otherwise, open the file.
438 if (FileSystemOpts.WorkingDir.empty())
439 return FS->getBufferForFile(Filename, FileSize,
440 /*RequiresNullTerminator=*/true, isVolatile);
442 SmallString<128> FilePath(Entry->getName());
443 FixupRelativePath(FilePath);
444 return FS->getBufferForFile(FilePath, FileSize,
445 /*RequiresNullTerminator=*/true, isVolatile);
448 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
449 FileManager::getBufferForFile(StringRef Filename) {
450 if (FileSystemOpts.WorkingDir.empty())
451 return FS->getBufferForFile(Filename);
453 SmallString<128> FilePath(Filename);
454 FixupRelativePath(FilePath);
455 return FS->getBufferForFile(FilePath.c_str());
458 /// getStatValue - Get the 'stat' information for the specified path,
459 /// using the cache to accelerate it if possible. This returns true
460 /// if the path points to a virtual file or does not exist, or returns
461 /// false if it's an existent real file. If FileDescriptor is NULL,
462 /// do directory look-up instead of file look-up.
463 bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile,
464 std::unique_ptr<vfs::File> *F) {
465 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
467 if (FileSystemOpts.WorkingDir.empty())
468 return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
470 SmallString<128> FilePath(Path);
471 FixupRelativePath(FilePath);
473 return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
474 StatCache.get(), *FS);
477 bool FileManager::getNoncachedStatValue(StringRef Path,
478 vfs::Status &Result) {
479 SmallString<128> FilePath(Path);
480 FixupRelativePath(FilePath);
482 llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str());
489 void FileManager::invalidateCache(const FileEntry *Entry) {
490 assert(Entry && "Cannot invalidate a NULL FileEntry");
492 SeenFileEntries.erase(Entry->getName());
494 // FileEntry invalidation should not block future optimizations in the file
495 // caches. Possible alternatives are cache truncation (invalidate last N) or
496 // invalidation of the whole cache.
497 UniqueRealFiles.erase(Entry->getUniqueID());
501 void FileManager::GetUniqueIDMapping(
502 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
504 UIDToFiles.resize(NextFileUID);
507 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
508 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
510 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
511 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
513 // Map virtual file entries
514 for (const auto &VFE : VirtualFileEntries)
515 if (VFE && VFE.get() != NON_EXISTENT_FILE)
516 UIDToFiles[VFE->getUID()] = VFE.get();
519 void FileManager::modifyFileEntry(FileEntry *File,
520 off_t Size, time_t ModificationTime) {
522 File->ModTime = ModificationTime;
525 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
526 // FIXME: use llvm::sys::fs::canonical() when it gets implemented
527 llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
528 = CanonicalDirNames.find(Dir);
529 if (Known != CanonicalDirNames.end())
530 return Known->second;
532 StringRef CanonicalName(Dir->getName());
535 char CanonicalNameBuf[PATH_MAX];
536 if (realpath(Dir->getName(), CanonicalNameBuf))
537 CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
539 SmallString<256> CanonicalNameBuf(CanonicalName);
540 llvm::sys::fs::make_absolute(CanonicalNameBuf);
541 llvm::sys::path::native(CanonicalNameBuf);
542 // We've run into needing to remove '..' here in the wild though, so
544 // On Windows, symlinks are significantly less prevalent, so removing
545 // '..' is pretty safe.
546 // Ideally we'd have an equivalent of `realpath` and could implement
547 // sys::fs::canonical across all the platforms.
548 llvm::sys::path::remove_dots(CanonicalNameBuf, /* remove_dot_dot */ true);
549 CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
552 CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
553 return CanonicalName;
556 void FileManager::PrintStats() const {
557 llvm::errs() << "\n*** File Manager Stats:\n";
558 llvm::errs() << UniqueRealFiles.size() << " real files found, "
559 << UniqueRealDirs.size() << " real dirs found.\n";
560 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
561 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
562 llvm::errs() << NumDirLookups << " dir lookups, "
563 << NumDirCacheMisses << " dir cache misses.\n";
564 llvm::errs() << NumFileLookups << " file lookups, "
565 << NumFileCacheMisses << " file cache misses.\n";
567 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;