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 "clang/Frontend/PCHContainerOperations.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/Config/llvm-config.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() {
62 for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
63 delete VirtualFileEntries[i];
64 for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
65 delete VirtualDirectoryEntries[i];
68 void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache,
70 assert(statCache && "No stat cache provided?");
71 if (AtBeginning || !StatCache.get()) {
72 statCache->setNextStatCache(std::move(StatCache));
73 StatCache = std::move(statCache);
77 FileSystemStatCache *LastCache = StatCache.get();
78 while (LastCache->getNextStatCache())
79 LastCache = LastCache->getNextStatCache();
81 LastCache->setNextStatCache(std::move(statCache));
84 void FileManager::removeStatCache(FileSystemStatCache *statCache) {
88 if (StatCache.get() == statCache) {
89 // This is the first stat cache.
90 StatCache = StatCache->takeNextStatCache();
94 // Find the stat cache in the list.
95 FileSystemStatCache *PrevCache = StatCache.get();
96 while (PrevCache && PrevCache->getNextStatCache() != statCache)
97 PrevCache = PrevCache->getNextStatCache();
99 assert(PrevCache && "Stat cache not found for removal");
100 PrevCache->setNextStatCache(statCache->takeNextStatCache());
103 void FileManager::clearStatCaches() {
107 /// \brief Retrieve the directory that the given file name resides in.
108 /// Filename can point to either a real file or a virtual file.
109 static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
112 if (Filename.empty())
115 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
116 return nullptr; // If Filename is a directory.
118 StringRef DirName = llvm::sys::path::parent_path(Filename);
119 // Use the current directory if file has no path component.
123 return FileMgr.getDirectory(DirName, CacheFailure);
126 /// Add all ancestors of the given path (pointing to either a file or
127 /// a directory) as virtual directories.
128 void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
129 StringRef DirName = llvm::sys::path::parent_path(Path);
134 *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
136 // When caching a virtual directory, we always cache its ancestors
137 // at the same time. Therefore, if DirName is already in the cache,
138 // we don't need to recurse as its ancestors must also already be in
140 if (NamedDirEnt.second)
143 // Add the virtual directory to the cache.
144 DirectoryEntry *UDE = new DirectoryEntry;
145 UDE->Name = NamedDirEnt.first().data();
146 NamedDirEnt.second = UDE;
147 VirtualDirectoryEntries.push_back(UDE);
149 // Recursively add the other ancestors.
150 addAncestorsAsVirtualDirs(DirName);
153 const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
155 // stat doesn't like trailing separators except for root directory.
156 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
157 // (though it can strip '\\')
158 if (DirName.size() > 1 &&
159 DirName != llvm::sys::path::root_path(DirName) &&
160 llvm::sys::path::is_separator(DirName.back()))
161 DirName = DirName.substr(0, DirName.size()-1);
163 // Fixing a problem with "clang C:test.c" on Windows.
164 // Stat("C:") does not recognize "C:" as a valid directory
165 std::string DirNameStr;
166 if (DirName.size() > 1 && DirName.back() == ':' &&
167 DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
168 DirNameStr = DirName.str() + '.';
169 DirName = DirNameStr;
175 *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
177 // See if there was already an entry in the map. Note that the map
178 // contains both virtual and real directories.
179 if (NamedDirEnt.second)
180 return NamedDirEnt.second == NON_EXISTENT_DIR ? nullptr
181 : NamedDirEnt.second;
185 // By default, initialize it to invalid.
186 NamedDirEnt.second = NON_EXISTENT_DIR;
188 // Get the null-terminated directory name as stored as the key of the
189 // SeenDirEntries map.
190 const char *InterndDirName = NamedDirEnt.first().data();
192 // Check to see if the directory exists.
194 if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) {
195 // There's no real directory at the given path.
197 SeenDirEntries.erase(DirName);
201 // It exists. See if we have already opened a directory with the
202 // same inode (this occurs on Unix-like systems when one dir is
203 // symlinked to another, for example) or the same path (on
205 DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID];
207 NamedDirEnt.second = &UDE;
208 if (!UDE.getName()) {
209 // We don't have this directory yet, add it. We use the string
210 // key from the SeenDirEntries map as the string.
211 UDE.Name = InterndDirName;
217 const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
221 // See if there is already an entry in the map.
223 *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
225 // See if there is already an entry in the map.
226 if (NamedFileEnt.second)
227 return NamedFileEnt.second == NON_EXISTENT_FILE ? nullptr
228 : NamedFileEnt.second;
230 ++NumFileCacheMisses;
232 // By default, initialize it to invalid.
233 NamedFileEnt.second = NON_EXISTENT_FILE;
235 // Get the null-terminated file name as stored as the key of the
236 // SeenFileEntries map.
237 const char *InterndFileName = NamedFileEnt.first().data();
239 // Look up the directory for the file. When looking up something like
240 // sys/foo.h we'll discover all of the search directories that have a 'sys'
241 // subdirectory. This will let us avoid having to waste time on known-to-fail
242 // searches when we go to find sys/bar.h, because all the search directories
243 // without a 'sys' subdir will get a cached failure result.
244 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
246 if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
248 SeenFileEntries.erase(Filename);
253 // FIXME: Use the directory info to prune this, before doing the stat syscall.
254 // FIXME: This will reduce the # syscalls.
256 // Nope, there isn't. Check to see if the file exists.
257 std::unique_ptr<vfs::File> F;
259 if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) {
260 // There's no real file at the given path.
262 SeenFileEntries.erase(Filename);
267 assert((openFile || !F) && "undesired open file");
269 // It exists. See if we have already opened a file with the same inode.
270 // This occurs when one dir is symlinked to another, for example.
271 FileEntry &UFE = UniqueRealFiles[Data.UniqueID];
273 NamedFileEnt.second = &UFE;
275 // If the name returned by getStatValue is different than Filename, re-intern
277 if (Data.Name != Filename) {
279 *SeenFileEntries.insert(std::make_pair(Data.Name, nullptr)).first;
280 if (!NamedFileEnt.second)
281 NamedFileEnt.second = &UFE;
283 assert(NamedFileEnt.second == &UFE &&
284 "filename from getStatValue() refers to wrong file");
285 InterndFileName = NamedFileEnt.first().data();
288 if (UFE.isValid()) { // Already have an entry with this inode, return it.
290 // FIXME: this hack ensures that if we look up a file by a virtual path in
291 // the VFS that the getDir() will have the virtual path, even if we found
292 // the file by a 'real' path first. This is required in order to find a
293 // module's structure when its headers/module map are mapped in the VFS.
294 // We should remove this as soon as we can properly support a file having
296 if (DirInfo != UFE.Dir && Data.IsVFSMapped)
299 // Always update the name to use the last name by which a file was accessed.
300 // FIXME: Neither this nor always using the first name is correct; we want
301 // to switch towards a design where we return a FileName object that
302 // encapsulates both the name by which the file was accessed and the
303 // corresponding FileEntry.
304 UFE.Name = InterndFileName;
309 // Otherwise, we don't have this file yet, add it.
310 UFE.Name = InterndFileName;
311 UFE.Size = Data.Size;
312 UFE.ModTime = Data.ModTime;
314 UFE.UID = NextFileUID++;
315 UFE.UniqueID = Data.UniqueID;
316 UFE.IsNamedPipe = Data.IsNamedPipe;
317 UFE.InPCH = Data.InPCH;
318 UFE.File = std::move(F);
324 FileManager::getVirtualFile(StringRef Filename, off_t Size,
325 time_t ModificationTime) {
328 // See if there is already an entry in the map.
330 *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
332 // See if there is already an entry in the map.
333 if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE)
334 return NamedFileEnt.second;
336 ++NumFileCacheMisses;
338 // By default, initialize it to invalid.
339 NamedFileEnt.second = NON_EXISTENT_FILE;
341 addAncestorsAsVirtualDirs(Filename);
342 FileEntry *UFE = nullptr;
344 // Now that all ancestors of Filename are in the cache, the
345 // following call is guaranteed to find the DirectoryEntry from the
347 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
348 /*CacheFailure=*/true);
350 "The directory of a virtual file should already be in the cache.");
352 // Check to see if the file exists. If so, drop the virtual file
354 const char *InterndFileName = NamedFileEnt.first().data();
355 if (getStatValue(InterndFileName, Data, true, nullptr) == 0) {
357 Data.ModTime = ModificationTime;
358 UFE = &UniqueRealFiles[Data.UniqueID];
360 NamedFileEnt.second = UFE;
362 // If we had already opened this file, close it now so we don't
363 // leak the descriptor. We're not going to use the file
364 // descriptor anyway, since this is a virtual file.
368 // If we already have an entry with this inode, return it.
372 UFE->UniqueID = Data.UniqueID;
373 UFE->IsNamedPipe = Data.IsNamedPipe;
374 UFE->InPCH = Data.InPCH;
378 UFE = new FileEntry();
379 VirtualFileEntries.push_back(UFE);
380 NamedFileEnt.second = UFE;
383 UFE->Name = InterndFileName;
385 UFE->ModTime = ModificationTime;
387 UFE->UID = NextFileUID++;
392 void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
393 StringRef pathRef(path.data(), path.size());
395 if (FileSystemOpts.WorkingDir.empty()
396 || llvm::sys::path::is_absolute(pathRef))
399 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
400 llvm::sys::path::append(NewPath, pathRef);
404 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
405 FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
406 bool ShouldCloseOpenFile) {
407 uint64_t FileSize = Entry->getSize();
408 // If there's a high enough chance that the file have changed since we
409 // got its size, force a stat before opening it.
413 const char *Filename = Entry->getName();
414 // If the file is already open, use the open file descriptor.
417 Entry->File->getBuffer(Filename, FileSize,
418 /*RequiresNullTerminator=*/true, isVolatile);
419 // FIXME: we need a set of APIs that can make guarantees about whether a
420 // FileEntry is open or not.
421 if (ShouldCloseOpenFile)
426 // Otherwise, open the file.
428 if (FileSystemOpts.WorkingDir.empty())
429 return FS->getBufferForFile(Filename, FileSize,
430 /*RequiresNullTerminator=*/true, isVolatile);
432 SmallString<128> FilePath(Entry->getName());
433 FixupRelativePath(FilePath);
434 return FS->getBufferForFile(FilePath, FileSize,
435 /*RequiresNullTerminator=*/true, isVolatile);
438 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
439 FileManager::getBufferForFile(StringRef Filename) {
440 if (FileSystemOpts.WorkingDir.empty())
441 return FS->getBufferForFile(Filename);
443 SmallString<128> FilePath(Filename);
444 FixupRelativePath(FilePath);
445 return FS->getBufferForFile(FilePath.c_str());
448 /// getStatValue - Get the 'stat' information for the specified path,
449 /// using the cache to accelerate it if possible. This returns true
450 /// if the path points to a virtual file or does not exist, or returns
451 /// false if it's an existent real file. If FileDescriptor is NULL,
452 /// do directory look-up instead of file look-up.
453 bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile,
454 std::unique_ptr<vfs::File> *F) {
455 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
457 if (FileSystemOpts.WorkingDir.empty())
458 return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
460 SmallString<128> FilePath(Path);
461 FixupRelativePath(FilePath);
463 return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
464 StatCache.get(), *FS);
467 bool FileManager::getNoncachedStatValue(StringRef Path,
468 vfs::Status &Result) {
469 SmallString<128> FilePath(Path);
470 FixupRelativePath(FilePath);
472 llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str());
479 void FileManager::invalidateCache(const FileEntry *Entry) {
480 assert(Entry && "Cannot invalidate a NULL FileEntry");
482 SeenFileEntries.erase(Entry->getName());
484 // FileEntry invalidation should not block future optimizations in the file
485 // caches. Possible alternatives are cache truncation (invalidate last N) or
486 // invalidation of the whole cache.
487 UniqueRealFiles.erase(Entry->getUniqueID());
491 void FileManager::GetUniqueIDMapping(
492 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
494 UIDToFiles.resize(NextFileUID);
497 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
498 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
500 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
501 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
503 // Map virtual file entries
504 for (SmallVectorImpl<FileEntry *>::const_iterator
505 VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
506 VFE != VFEEnd; ++VFE)
507 if (*VFE && *VFE != NON_EXISTENT_FILE)
508 UIDToFiles[(*VFE)->getUID()] = *VFE;
511 void FileManager::modifyFileEntry(FileEntry *File,
512 off_t Size, time_t ModificationTime) {
514 File->ModTime = ModificationTime;
517 /// Remove '.' path components from the given absolute path.
518 /// \return \c true if any changes were made.
519 // FIXME: Move this to llvm::sys::path.
520 bool FileManager::removeDotPaths(SmallVectorImpl<char> &Path) {
521 using namespace llvm::sys;
523 SmallVector<StringRef, 16> ComponentStack;
524 StringRef P(Path.data(), Path.size());
526 // Skip the root path, then look for traversal in the components.
527 StringRef Rel = path::relative_path(P);
528 bool AnyDots = false;
529 for (StringRef C : llvm::make_range(path::begin(Rel), path::end(Rel))) {
534 ComponentStack.push_back(C);
540 SmallString<256> Buffer = path::root_path(P);
541 for (StringRef C : ComponentStack)
542 path::append(Buffer, C);
548 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
549 // FIXME: use llvm::sys::fs::canonical() when it gets implemented
550 llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
551 = CanonicalDirNames.find(Dir);
552 if (Known != CanonicalDirNames.end())
553 return Known->second;
555 StringRef CanonicalName(Dir->getName());
558 char CanonicalNameBuf[PATH_MAX];
559 if (realpath(Dir->getName(), CanonicalNameBuf)) {
560 unsigned Len = strlen(CanonicalNameBuf);
561 char *Mem = static_cast<char *>(CanonicalNameStorage.Allocate(Len, 1));
562 memcpy(Mem, CanonicalNameBuf, Len);
563 CanonicalName = StringRef(Mem, Len);
566 SmallString<256> CanonicalNameBuf(CanonicalName);
567 llvm::sys::fs::make_absolute(CanonicalNameBuf);
568 llvm::sys::path::native(CanonicalNameBuf);
569 removeDotPaths(CanonicalNameBuf);
572 CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
573 return CanonicalName;
576 void FileManager::PrintStats() const {
577 llvm::errs() << "\n*** File Manager Stats:\n";
578 llvm::errs() << UniqueRealFiles.size() << " real files found, "
579 << UniqueRealDirs.size() << " real dirs found.\n";
580 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
581 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
582 llvm::errs() << NumDirLookups << " dir lookups, "
583 << NumDirCacheMisses << " dir cache misses.\n";
584 llvm::errs() << NumFileLookups << " file lookups, "
585 << NumFileCacheMisses << " file cache misses.\n";
587 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
590 PCHContainerOperations::~PCHContainerOperations() {}