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 // FIXME: Enhance libsystem to support inode and other fields.
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)
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)
46 //===----------------------------------------------------------------------===//
48 //===----------------------------------------------------------------------===//
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;
57 // If the caller doesn't provide a virtual file system, just grab the real
60 this->FS = vfs::getRealFileSystem();
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];
70 void FileManager::addStatCache(FileSystemStatCache *statCache,
72 assert(statCache && "No stat cache provided?");
73 if (AtBeginning || !StatCache.get()) {
74 statCache->setNextStatCache(StatCache.release());
75 StatCache.reset(statCache);
79 FileSystemStatCache *LastCache = StatCache.get();
80 while (LastCache->getNextStatCache())
81 LastCache = LastCache->getNextStatCache();
83 LastCache->setNextStatCache(statCache);
86 void FileManager::removeStatCache(FileSystemStatCache *statCache) {
90 if (StatCache.get() == statCache) {
91 // This is the first stat cache.
92 StatCache.reset(StatCache->takeNextStatCache());
96 // Find the stat cache in the list.
97 FileSystemStatCache *PrevCache = StatCache.get();
98 while (PrevCache && PrevCache->getNextStatCache() != statCache)
99 PrevCache = PrevCache->getNextStatCache();
101 assert(PrevCache && "Stat cache not found for removal");
102 PrevCache->setNextStatCache(statCache->getNextStatCache());
105 void FileManager::clearStatCaches() {
106 StatCache.reset(nullptr);
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,
114 if (Filename.empty())
117 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
118 return nullptr; // If Filename is a directory.
120 StringRef DirName = llvm::sys::path::parent_path(Filename);
121 // Use the current directory if file has no path component.
125 return FileMgr.getDirectory(DirName, CacheFailure);
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);
135 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
136 SeenDirEntries.GetOrCreateValue(DirName);
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
142 if (NamedDirEnt.getValue())
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);
151 // Recursively add the other ancestors.
152 addAncestorsAsVirtualDirs(DirName);
155 const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
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);
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;
176 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
177 SeenDirEntries.GetOrCreateValue(DirName);
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 ? nullptr
183 : NamedDirEnt.getValue();
187 // By default, initialize it to invalid.
188 NamedDirEnt.setValue(NON_EXISTENT_DIR);
190 // Get the null-terminated directory name as stored as the key of the
191 // SeenDirEntries map.
192 const char *InterndDirName = NamedDirEnt.getKeyData();
194 // Check to see if the directory exists.
196 if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) {
197 // There's no real directory at the given path.
199 SeenDirEntries.erase(DirName);
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
207 DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID];
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;
219 const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
223 // See if there is already an entry in the map.
224 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
225 SeenFileEntries.GetOrCreateValue(Filename);
227 // See if there is already an entry in the map.
228 if (NamedFileEnt.getValue())
229 return NamedFileEnt.getValue() == NON_EXISTENT_FILE
230 ? nullptr : NamedFileEnt.getValue();
232 ++NumFileCacheMisses;
234 // By default, initialize it to invalid.
235 NamedFileEnt.setValue(NON_EXISTENT_FILE);
237 // Get the null-terminated file name as stored as the key of the
238 // SeenFileEntries map.
239 const char *InterndFileName = NamedFileEnt.getKeyData();
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,
248 if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
250 SeenFileEntries.erase(Filename);
255 // FIXME: Use the directory info to prune this, before doing the stat syscall.
256 // FIXME: This will reduce the # syscalls.
258 // Nope, there isn't. Check to see if the file exists.
259 vfs::File *F = nullptr;
261 if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) {
262 // There's no real file at the given path.
264 SeenFileEntries.erase(Filename);
269 assert((openFile || !F) && "undesired open file");
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];
275 NamedFileEnt.setValue(&UFE);
276 if (UFE.isValid()) { // Already have an entry with this inode, return it.
278 // FIXME: this hack ensures that if we look up a file by a virtual path in
279 // the VFS that the getDir() will have the virtual path, even if we found
280 // the file by a 'real' path first. This is required in order to find a
281 // module's structure when its headers/module map are mapped in the VFS.
282 // We should remove this as soon as we can properly support a file having
284 if (DirInfo != UFE.Dir && Data.IsVFSMapped)
287 // If the stat process opened the file, close it to avoid a FD leak.
294 // Otherwise, we don't have this file yet, add it.
295 UFE.Name = Data.Name;
296 UFE.Size = Data.Size;
297 UFE.ModTime = Data.ModTime;
299 UFE.UID = NextFileUID++;
300 UFE.UniqueID = Data.UniqueID;
301 UFE.IsNamedPipe = Data.IsNamedPipe;
302 UFE.InPCH = Data.InPCH;
309 FileManager::getVirtualFile(StringRef Filename, off_t Size,
310 time_t ModificationTime) {
313 // See if there is already an entry in the map.
314 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
315 SeenFileEntries.GetOrCreateValue(Filename);
317 // See if there is already an entry in the map.
318 if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
319 return NamedFileEnt.getValue();
321 ++NumFileCacheMisses;
323 // By default, initialize it to invalid.
324 NamedFileEnt.setValue(NON_EXISTENT_FILE);
326 addAncestorsAsVirtualDirs(Filename);
327 FileEntry *UFE = nullptr;
329 // Now that all ancestors of Filename are in the cache, the
330 // following call is guaranteed to find the DirectoryEntry from the
332 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
333 /*CacheFailure=*/true);
335 "The directory of a virtual file should already be in the cache.");
337 // Check to see if the file exists. If so, drop the virtual file
339 const char *InterndFileName = NamedFileEnt.getKeyData();
340 if (getStatValue(InterndFileName, Data, true, nullptr) == 0) {
342 Data.ModTime = ModificationTime;
343 UFE = &UniqueRealFiles[Data.UniqueID];
345 NamedFileEnt.setValue(UFE);
347 // If we had already opened this file, close it now so we don't
348 // leak the descriptor. We're not going to use the file
349 // descriptor anyway, since this is a virtual file.
353 // If we already have an entry with this inode, return it.
357 UFE->UniqueID = Data.UniqueID;
358 UFE->IsNamedPipe = Data.IsNamedPipe;
359 UFE->InPCH = Data.InPCH;
363 UFE = new FileEntry();
364 VirtualFileEntries.push_back(UFE);
365 NamedFileEnt.setValue(UFE);
368 UFE->Name = InterndFileName;
370 UFE->ModTime = ModificationTime;
372 UFE->UID = NextFileUID++;
377 void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
378 StringRef pathRef(path.data(), path.size());
380 if (FileSystemOpts.WorkingDir.empty()
381 || llvm::sys::path::is_absolute(pathRef))
384 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
385 llvm::sys::path::append(NewPath, pathRef);
389 llvm::MemoryBuffer *FileManager::
390 getBufferForFile(const FileEntry *Entry, std::string *ErrorStr,
392 std::unique_ptr<llvm::MemoryBuffer> Result;
395 uint64_t FileSize = Entry->getSize();
396 // If there's a high enough chance that the file have changed since we
397 // got its size, force a stat before opening it.
401 const char *Filename = Entry->getName();
402 // If the file is already open, use the open file descriptor.
404 ec = Entry->File->getBuffer(Filename, Result, FileSize,
405 /*RequiresNullTerminator=*/true, isVolatile);
407 *ErrorStr = ec.message();
409 return Result.release();
412 // Otherwise, open the file.
414 if (FileSystemOpts.WorkingDir.empty()) {
415 ec = FS->getBufferForFile(Filename, Result, FileSize,
416 /*RequiresNullTerminator=*/true, isVolatile);
418 *ErrorStr = ec.message();
419 return Result.release();
422 SmallString<128> FilePath(Entry->getName());
423 FixupRelativePath(FilePath);
424 ec = FS->getBufferForFile(FilePath.str(), Result, FileSize,
425 /*RequiresNullTerminator=*/true, isVolatile);
427 *ErrorStr = ec.message();
428 return Result.release();
431 llvm::MemoryBuffer *FileManager::
432 getBufferForFile(StringRef Filename, std::string *ErrorStr) {
433 std::unique_ptr<llvm::MemoryBuffer> Result;
435 if (FileSystemOpts.WorkingDir.empty()) {
436 ec = FS->getBufferForFile(Filename, Result);
438 *ErrorStr = ec.message();
439 return Result.release();
442 SmallString<128> FilePath(Filename);
443 FixupRelativePath(FilePath);
444 ec = FS->getBufferForFile(FilePath.c_str(), Result);
446 *ErrorStr = ec.message();
447 return Result.release();
450 /// getStatValue - Get the 'stat' information for the specified path,
451 /// using the cache to accelerate it if possible. This returns true
452 /// if the path points to a virtual file or does not exist, or returns
453 /// false if it's an existent real file. If FileDescriptor is NULL,
454 /// do directory look-up instead of file look-up.
455 bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile,
457 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
459 if (FileSystemOpts.WorkingDir.empty())
460 return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
462 SmallString<128> FilePath(Path);
463 FixupRelativePath(FilePath);
465 return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
466 StatCache.get(), *FS);
469 bool FileManager::getNoncachedStatValue(StringRef Path,
470 vfs::Status &Result) {
471 SmallString<128> FilePath(Path);
472 FixupRelativePath(FilePath);
474 llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str());
481 void FileManager::invalidateCache(const FileEntry *Entry) {
482 assert(Entry && "Cannot invalidate a NULL FileEntry");
484 SeenFileEntries.erase(Entry->getName());
486 // FileEntry invalidation should not block future optimizations in the file
487 // caches. Possible alternatives are cache truncation (invalidate last N) or
488 // invalidation of the whole cache.
489 UniqueRealFiles.erase(Entry->getUniqueID());
493 void FileManager::GetUniqueIDMapping(
494 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
496 UIDToFiles.resize(NextFileUID);
499 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
500 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
502 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
503 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
505 // Map virtual file entries
506 for (SmallVectorImpl<FileEntry *>::const_iterator
507 VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
508 VFE != VFEEnd; ++VFE)
509 if (*VFE && *VFE != NON_EXISTENT_FILE)
510 UIDToFiles[(*VFE)->getUID()] = *VFE;
513 void FileManager::modifyFileEntry(FileEntry *File,
514 off_t Size, time_t ModificationTime) {
516 File->ModTime = ModificationTime;
519 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
520 // FIXME: use llvm::sys::fs::canonical() when it gets implemented
522 llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
523 = CanonicalDirNames.find(Dir);
524 if (Known != CanonicalDirNames.end())
525 return Known->second;
527 StringRef CanonicalName(Dir->getName());
528 char CanonicalNameBuf[PATH_MAX];
529 if (realpath(Dir->getName(), CanonicalNameBuf)) {
530 unsigned Len = strlen(CanonicalNameBuf);
531 char *Mem = static_cast<char *>(CanonicalNameStorage.Allocate(Len, 1));
532 memcpy(Mem, CanonicalNameBuf, Len);
533 CanonicalName = StringRef(Mem, Len);
536 CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
537 return CanonicalName;
539 return StringRef(Dir->getName());
543 void FileManager::PrintStats() const {
544 llvm::errs() << "\n*** File Manager Stats:\n";
545 llvm::errs() << UniqueRealFiles.size() << " real files found, "
546 << UniqueRealDirs.size() << " real dirs found.\n";
547 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
548 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
549 llvm::errs() << NumDirLookups << " dir lookups, "
550 << NumDirCacheMisses << " dir cache misses.\n";
551 llvm::errs() << NumFileLookups << " file lookups, "
552 << NumFileCacheMisses << " file cache misses.\n";
554 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;