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/Support/FileSystem.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/raw_ostream.h"
31 #include <system_error>
33 using namespace clang;
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)
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)
43 //===----------------------------------------------------------------------===//
45 //===----------------------------------------------------------------------===//
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;
54 // If the caller doesn't provide a virtual file system, just grab the real
57 this->FS = vfs::getRealFileSystem();
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];
67 void FileManager::addStatCache(FileSystemStatCache *statCache,
69 assert(statCache && "No stat cache provided?");
70 if (AtBeginning || !StatCache.get()) {
71 statCache->setNextStatCache(StatCache.release());
72 StatCache.reset(statCache);
76 FileSystemStatCache *LastCache = StatCache.get();
77 while (LastCache->getNextStatCache())
78 LastCache = LastCache->getNextStatCache();
80 LastCache->setNextStatCache(statCache);
83 void FileManager::removeStatCache(FileSystemStatCache *statCache) {
87 if (StatCache.get() == statCache) {
88 // This is the first stat cache.
89 StatCache.reset(StatCache->takeNextStatCache());
93 // Find the stat cache in the list.
94 FileSystemStatCache *PrevCache = StatCache.get();
95 while (PrevCache && PrevCache->getNextStatCache() != statCache)
96 PrevCache = PrevCache->getNextStatCache();
98 assert(PrevCache && "Stat cache not found for removal");
99 PrevCache->setNextStatCache(statCache->getNextStatCache());
102 void FileManager::clearStatCaches() {
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,
111 if (Filename.empty())
114 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
115 return nullptr; // If Filename is a directory.
117 StringRef DirName = llvm::sys::path::parent_path(Filename);
118 // Use the current directory if file has no path component.
122 return FileMgr.getDirectory(DirName, CacheFailure);
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);
132 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
133 SeenDirEntries.GetOrCreateValue(DirName);
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
139 if (NamedDirEnt.getValue())
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);
148 // Recursively add the other ancestors.
149 addAncestorsAsVirtualDirs(DirName);
152 const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
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);
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;
173 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
174 SeenDirEntries.GetOrCreateValue(DirName);
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();
184 // By default, initialize it to invalid.
185 NamedDirEnt.setValue(NON_EXISTENT_DIR);
187 // Get the null-terminated directory name as stored as the key of the
188 // SeenDirEntries map.
189 const char *InterndDirName = NamedDirEnt.getKeyData();
191 // Check to see if the directory exists.
193 if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) {
194 // There's no real directory at the given path.
196 SeenDirEntries.erase(DirName);
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
204 DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID];
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;
216 const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
220 // See if there is already an entry in the map.
221 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
222 SeenFileEntries.GetOrCreateValue(Filename);
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();
229 ++NumFileCacheMisses;
231 // By default, initialize it to invalid.
232 NamedFileEnt.setValue(NON_EXISTENT_FILE);
234 // Get the null-terminated file name as stored as the key of the
235 // SeenFileEntries map.
236 const char *InterndFileName = NamedFileEnt.getKeyData();
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,
245 if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
247 SeenFileEntries.erase(Filename);
252 // FIXME: Use the directory info to prune this, before doing the stat syscall.
253 // FIXME: This will reduce the # syscalls.
255 // Nope, there isn't. Check to see if the file exists.
256 std::unique_ptr<vfs::File> F;
258 if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) {
259 // There's no real file at the given path.
261 SeenFileEntries.erase(Filename);
266 assert((openFile || !F) && "undesired open file");
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];
272 NamedFileEnt.setValue(&UFE);
273 if (UFE.isValid()) { // Already have an entry with this inode, return it.
275 // FIXME: this hack ensures that if we look up a file by a virtual path in
276 // the VFS that the getDir() will have the virtual path, even if we found
277 // the file by a 'real' path first. This is required in order to find a
278 // module's structure when its headers/module map are mapped in the VFS.
279 // We should remove this as soon as we can properly support a file having
281 if (DirInfo != UFE.Dir && Data.IsVFSMapped)
287 // Otherwise, we don't have this file yet, add it.
288 UFE.Name = Data.Name;
289 UFE.Size = Data.Size;
290 UFE.ModTime = Data.ModTime;
292 UFE.UID = NextFileUID++;
293 UFE.UniqueID = Data.UniqueID;
294 UFE.IsNamedPipe = Data.IsNamedPipe;
295 UFE.InPCH = Data.InPCH;
296 UFE.File = std::move(F);
302 FileManager::getVirtualFile(StringRef Filename, off_t Size,
303 time_t ModificationTime) {
306 // See if there is already an entry in the map.
307 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
308 SeenFileEntries.GetOrCreateValue(Filename);
310 // See if there is already an entry in the map.
311 if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
312 return NamedFileEnt.getValue();
314 ++NumFileCacheMisses;
316 // By default, initialize it to invalid.
317 NamedFileEnt.setValue(NON_EXISTENT_FILE);
319 addAncestorsAsVirtualDirs(Filename);
320 FileEntry *UFE = nullptr;
322 // Now that all ancestors of Filename are in the cache, the
323 // following call is guaranteed to find the DirectoryEntry from the
325 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
326 /*CacheFailure=*/true);
328 "The directory of a virtual file should already be in the cache.");
330 // Check to see if the file exists. If so, drop the virtual file
332 const char *InterndFileName = NamedFileEnt.getKeyData();
333 if (getStatValue(InterndFileName, Data, true, nullptr) == 0) {
335 Data.ModTime = ModificationTime;
336 UFE = &UniqueRealFiles[Data.UniqueID];
338 NamedFileEnt.setValue(UFE);
340 // If we had already opened this file, close it now so we don't
341 // leak the descriptor. We're not going to use the file
342 // descriptor anyway, since this is a virtual file.
346 // If we already have an entry with this inode, return it.
350 UFE->UniqueID = Data.UniqueID;
351 UFE->IsNamedPipe = Data.IsNamedPipe;
352 UFE->InPCH = Data.InPCH;
356 UFE = new FileEntry();
357 VirtualFileEntries.push_back(UFE);
358 NamedFileEnt.setValue(UFE);
361 UFE->Name = InterndFileName;
363 UFE->ModTime = ModificationTime;
365 UFE->UID = NextFileUID++;
370 void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
371 StringRef pathRef(path.data(), path.size());
373 if (FileSystemOpts.WorkingDir.empty()
374 || llvm::sys::path::is_absolute(pathRef))
377 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
378 llvm::sys::path::append(NewPath, pathRef);
382 llvm::MemoryBuffer *FileManager::
383 getBufferForFile(const FileEntry *Entry, std::string *ErrorStr,
384 bool isVolatile, bool ShouldCloseOpenFile) {
385 std::unique_ptr<llvm::MemoryBuffer> Result;
388 uint64_t FileSize = Entry->getSize();
389 // If there's a high enough chance that the file have changed since we
390 // got its size, force a stat before opening it.
394 const char *Filename = Entry->getName();
395 // If the file is already open, use the open file descriptor.
397 ec = Entry->File->getBuffer(Filename, Result, FileSize,
398 /*RequiresNullTerminator=*/true, isVolatile);
400 *ErrorStr = ec.message();
401 // FIXME: we need a set of APIs that can make guarantees about whether a
402 // FileEntry is open or not.
403 if (ShouldCloseOpenFile)
405 return Result.release();
408 // Otherwise, open the file.
410 if (FileSystemOpts.WorkingDir.empty()) {
411 ec = FS->getBufferForFile(Filename, Result, FileSize,
412 /*RequiresNullTerminator=*/true, isVolatile);
414 *ErrorStr = ec.message();
415 return Result.release();
418 SmallString<128> FilePath(Entry->getName());
419 FixupRelativePath(FilePath);
420 ec = FS->getBufferForFile(FilePath.str(), Result, FileSize,
421 /*RequiresNullTerminator=*/true, isVolatile);
423 *ErrorStr = ec.message();
424 return Result.release();
427 llvm::MemoryBuffer *FileManager::
428 getBufferForFile(StringRef Filename, std::string *ErrorStr) {
429 std::unique_ptr<llvm::MemoryBuffer> Result;
431 if (FileSystemOpts.WorkingDir.empty()) {
432 ec = FS->getBufferForFile(Filename, Result);
434 *ErrorStr = ec.message();
435 return Result.release();
438 SmallString<128> FilePath(Filename);
439 FixupRelativePath(FilePath);
440 ec = FS->getBufferForFile(FilePath.c_str(), Result);
442 *ErrorStr = ec.message();
443 return Result.release();
446 /// getStatValue - Get the 'stat' information for the specified path,
447 /// using the cache to accelerate it if possible. This returns true
448 /// if the path points to a virtual file or does not exist, or returns
449 /// false if it's an existent real file. If FileDescriptor is NULL,
450 /// do directory look-up instead of file look-up.
451 bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile,
452 std::unique_ptr<vfs::File> *F) {
453 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
455 if (FileSystemOpts.WorkingDir.empty())
456 return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
458 SmallString<128> FilePath(Path);
459 FixupRelativePath(FilePath);
461 return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
462 StatCache.get(), *FS);
465 bool FileManager::getNoncachedStatValue(StringRef Path,
466 vfs::Status &Result) {
467 SmallString<128> FilePath(Path);
468 FixupRelativePath(FilePath);
470 llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str());
477 void FileManager::invalidateCache(const FileEntry *Entry) {
478 assert(Entry && "Cannot invalidate a NULL FileEntry");
480 SeenFileEntries.erase(Entry->getName());
482 // FileEntry invalidation should not block future optimizations in the file
483 // caches. Possible alternatives are cache truncation (invalidate last N) or
484 // invalidation of the whole cache.
485 UniqueRealFiles.erase(Entry->getUniqueID());
489 void FileManager::GetUniqueIDMapping(
490 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
492 UIDToFiles.resize(NextFileUID);
495 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
496 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
498 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
499 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
501 // Map virtual file entries
502 for (SmallVectorImpl<FileEntry *>::const_iterator
503 VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
504 VFE != VFEEnd; ++VFE)
505 if (*VFE && *VFE != NON_EXISTENT_FILE)
506 UIDToFiles[(*VFE)->getUID()] = *VFE;
509 void FileManager::modifyFileEntry(FileEntry *File,
510 off_t Size, time_t ModificationTime) {
512 File->ModTime = ModificationTime;
515 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
516 // FIXME: use llvm::sys::fs::canonical() when it gets implemented
518 llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
519 = CanonicalDirNames.find(Dir);
520 if (Known != CanonicalDirNames.end())
521 return Known->second;
523 StringRef CanonicalName(Dir->getName());
524 char CanonicalNameBuf[PATH_MAX];
525 if (realpath(Dir->getName(), CanonicalNameBuf)) {
526 unsigned Len = strlen(CanonicalNameBuf);
527 char *Mem = static_cast<char *>(CanonicalNameStorage.Allocate(Len, 1));
528 memcpy(Mem, CanonicalNameBuf, Len);
529 CanonicalName = StringRef(Mem, Len);
532 CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
533 return CanonicalName;
535 return StringRef(Dir->getName());
539 void FileManager::PrintStats() const {
540 llvm::errs() << "\n*** File Manager Stats:\n";
541 llvm::errs() << UniqueRealFiles.size() << " real files found, "
542 << UniqueRealDirs.size() << " real dirs found.\n";
543 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
544 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
545 llvm::errs() << NumDirLookups << " dir lookups, "
546 << NumDirCacheMisses << " dir cache misses.\n";
547 llvm::errs() << NumFileLookups << " file lookups, "
548 << NumFileCacheMisses << " file cache misses.\n";
550 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;