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"
28 #include "llvm/Support/system_error.h"
33 // FIXME: This is terrible, we need this for ::close.
34 #if !defined(_MSC_VER) && !defined(__MINGW32__)
40 #define S_ISFIFO(x) (0)
43 #if defined(LLVM_ON_UNIX)
46 using namespace clang;
48 // FIXME: Enhance libsystem to support inode and other fields.
51 /// NON_EXISTENT_DIR - A special value distinct from null that is used to
52 /// represent a dir name that doesn't exist on the disk.
53 #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
55 /// NON_EXISTENT_FILE - A special value distinct from null that is used to
56 /// represent a filename that doesn't exist on the disk.
57 #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
60 FileEntry::~FileEntry() {
61 // If this FileEntry owns an open file descriptor that never got used, close
63 if (FD != -1) ::close(FD);
66 bool FileEntry::isNamedPipe() const {
67 return S_ISFIFO(FileMode);
70 //===----------------------------------------------------------------------===//
72 //===----------------------------------------------------------------------===//
77 static std::string GetFullPath(const char *relPath) {
78 char *absPathStrPtr = _fullpath(NULL, relPath, 0);
79 assert(absPathStrPtr && "_fullpath() returned NULL!");
81 std::string absPath(absPathStrPtr);
88 class FileManager::UniqueDirContainer {
89 /// UniqueDirs - Cache from full path to existing directories/files.
91 llvm::StringMap<DirectoryEntry> UniqueDirs;
94 /// getDirectory - Return an existing DirectoryEntry with the given
95 /// name if there is already one; otherwise create and return a
96 /// default-constructed DirectoryEntry.
97 DirectoryEntry &getDirectory(const char *Name,
98 const struct stat & /*StatBuf*/) {
99 std::string FullPath(GetFullPath(Name));
100 return UniqueDirs.GetOrCreateValue(FullPath).getValue();
103 size_t size() const { return UniqueDirs.size(); }
106 class FileManager::UniqueFileContainer {
107 /// UniqueFiles - Cache from full path to existing directories/files.
109 llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;
112 /// getFile - Return an existing FileEntry with the given name if
113 /// there is already one; otherwise create and return a
114 /// default-constructed FileEntry.
115 FileEntry &getFile(const char *Name, const struct stat & /*StatBuf*/) {
116 std::string FullPath(GetFullPath(Name));
118 // Lowercase string because Windows filesystem is case insensitive.
119 FullPath = StringRef(FullPath).lower();
120 return UniqueFiles.GetOrCreateValue(FullPath).getValue();
123 size_t size() const { return UniqueFiles.size(); }
125 void erase(const FileEntry *Entry) {
126 std::string FullPath(GetFullPath(Entry->getName()));
128 // Lowercase string because Windows filesystem is case insensitive.
129 FullPath = StringRef(FullPath).lower();
130 UniqueFiles.erase(FullPath);
134 //===----------------------------------------------------------------------===//
135 // Unix-like Systems.
136 //===----------------------------------------------------------------------===//
140 class FileManager::UniqueDirContainer {
141 /// UniqueDirs - Cache from ID's to existing directories/files.
142 std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;
145 /// getDirectory - Return an existing DirectoryEntry with the given
146 /// ID's if there is already one; otherwise create and return a
147 /// default-constructed DirectoryEntry.
148 DirectoryEntry &getDirectory(const char * /*Name*/,
149 const struct stat &StatBuf) {
150 return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
153 size_t size() const { return UniqueDirs.size(); }
156 class FileManager::UniqueFileContainer {
157 /// UniqueFiles - Cache from ID's to existing directories/files.
158 std::set<FileEntry> UniqueFiles;
161 /// getFile - Return an existing FileEntry with the given ID's if
162 /// there is already one; otherwise create and return a
163 /// default-constructed FileEntry.
164 FileEntry &getFile(const char * /*Name*/, const struct stat &StatBuf) {
166 const_cast<FileEntry&>(
167 *UniqueFiles.insert(FileEntry(StatBuf.st_dev,
169 StatBuf.st_mode)).first);
172 size_t size() const { return UniqueFiles.size(); }
174 void erase(const FileEntry *Entry) { UniqueFiles.erase(*Entry); }
179 //===----------------------------------------------------------------------===//
181 //===----------------------------------------------------------------------===//
183 FileManager::FileManager(const FileSystemOptions &FSO)
184 : FileSystemOpts(FSO),
185 UniqueRealDirs(*new UniqueDirContainer()),
186 UniqueRealFiles(*new UniqueFileContainer()),
187 SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
188 NumDirLookups = NumFileLookups = 0;
189 NumDirCacheMisses = NumFileCacheMisses = 0;
192 FileManager::~FileManager() {
193 delete &UniqueRealDirs;
194 delete &UniqueRealFiles;
195 for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
196 delete VirtualFileEntries[i];
197 for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
198 delete VirtualDirectoryEntries[i];
201 void FileManager::addStatCache(FileSystemStatCache *statCache,
203 assert(statCache && "No stat cache provided?");
204 if (AtBeginning || StatCache.get() == 0) {
205 statCache->setNextStatCache(StatCache.take());
206 StatCache.reset(statCache);
210 FileSystemStatCache *LastCache = StatCache.get();
211 while (LastCache->getNextStatCache())
212 LastCache = LastCache->getNextStatCache();
214 LastCache->setNextStatCache(statCache);
217 void FileManager::removeStatCache(FileSystemStatCache *statCache) {
221 if (StatCache.get() == statCache) {
222 // This is the first stat cache.
223 StatCache.reset(StatCache->takeNextStatCache());
227 // Find the stat cache in the list.
228 FileSystemStatCache *PrevCache = StatCache.get();
229 while (PrevCache && PrevCache->getNextStatCache() != statCache)
230 PrevCache = PrevCache->getNextStatCache();
232 assert(PrevCache && "Stat cache not found for removal");
233 PrevCache->setNextStatCache(statCache->getNextStatCache());
236 void FileManager::clearStatCaches() {
240 /// \brief Retrieve the directory that the given file name resides in.
241 /// Filename can point to either a real file or a virtual file.
242 static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
245 if (Filename.empty())
248 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
249 return NULL; // If Filename is a directory.
251 StringRef DirName = llvm::sys::path::parent_path(Filename);
252 // Use the current directory if file has no path component.
256 return FileMgr.getDirectory(DirName, CacheFailure);
259 /// Add all ancestors of the given path (pointing to either a file or
260 /// a directory) as virtual directories.
261 void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
262 StringRef DirName = llvm::sys::path::parent_path(Path);
266 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
267 SeenDirEntries.GetOrCreateValue(DirName);
269 // When caching a virtual directory, we always cache its ancestors
270 // at the same time. Therefore, if DirName is already in the cache,
271 // we don't need to recurse as its ancestors must also already be in
273 if (NamedDirEnt.getValue())
276 // Add the virtual directory to the cache.
277 DirectoryEntry *UDE = new DirectoryEntry;
278 UDE->Name = NamedDirEnt.getKeyData();
279 NamedDirEnt.setValue(UDE);
280 VirtualDirectoryEntries.push_back(UDE);
282 // Recursively add the other ancestors.
283 addAncestorsAsVirtualDirs(DirName);
286 const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
288 // stat doesn't like trailing separators except for root directory.
289 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
290 // (though it can strip '\\')
291 if (DirName.size() > 1 &&
292 DirName != llvm::sys::path::root_path(DirName) &&
293 llvm::sys::path::is_separator(DirName.back()))
294 DirName = DirName.substr(0, DirName.size()-1);
297 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
298 SeenDirEntries.GetOrCreateValue(DirName);
300 // See if there was already an entry in the map. Note that the map
301 // contains both virtual and real directories.
302 if (NamedDirEnt.getValue())
303 return NamedDirEnt.getValue() == NON_EXISTENT_DIR
304 ? 0 : NamedDirEnt.getValue();
308 // By default, initialize it to invalid.
309 NamedDirEnt.setValue(NON_EXISTENT_DIR);
311 // Get the null-terminated directory name as stored as the key of the
312 // SeenDirEntries map.
313 const char *InterndDirName = NamedDirEnt.getKeyData();
315 // Check to see if the directory exists.
317 if (getStatValue(InterndDirName, StatBuf, false, 0/*directory lookup*/)) {
318 // There's no real directory at the given path.
320 SeenDirEntries.erase(DirName);
324 // It exists. See if we have already opened a directory with the
325 // same inode (this occurs on Unix-like systems when one dir is
326 // symlinked to another, for example) or the same path (on
328 DirectoryEntry &UDE = UniqueRealDirs.getDirectory(InterndDirName, StatBuf);
330 NamedDirEnt.setValue(&UDE);
331 if (!UDE.getName()) {
332 // We don't have this directory yet, add it. We use the string
333 // key from the SeenDirEntries map as the string.
334 UDE.Name = InterndDirName;
340 const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
344 // See if there is already an entry in the map.
345 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
346 SeenFileEntries.GetOrCreateValue(Filename);
348 // See if there is already an entry in the map.
349 if (NamedFileEnt.getValue())
350 return NamedFileEnt.getValue() == NON_EXISTENT_FILE
351 ? 0 : NamedFileEnt.getValue();
353 ++NumFileCacheMisses;
355 // By default, initialize it to invalid.
356 NamedFileEnt.setValue(NON_EXISTENT_FILE);
358 // Get the null-terminated file name as stored as the key of the
359 // SeenFileEntries map.
360 const char *InterndFileName = NamedFileEnt.getKeyData();
362 // Look up the directory for the file. When looking up something like
363 // sys/foo.h we'll discover all of the search directories that have a 'sys'
364 // subdirectory. This will let us avoid having to waste time on known-to-fail
365 // searches when we go to find sys/bar.h, because all the search directories
366 // without a 'sys' subdir will get a cached failure result.
367 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
369 if (DirInfo == 0) { // Directory doesn't exist, file can't exist.
371 SeenFileEntries.erase(Filename);
376 // FIXME: Use the directory info to prune this, before doing the stat syscall.
377 // FIXME: This will reduce the # syscalls.
379 // Nope, there isn't. Check to see if the file exists.
380 int FileDescriptor = -1;
382 if (getStatValue(InterndFileName, StatBuf, true,
383 openFile ? &FileDescriptor : 0)) {
384 // There's no real file at the given path.
386 SeenFileEntries.erase(Filename);
391 if (FileDescriptor != -1 && !openFile) {
392 close(FileDescriptor);
396 // It exists. See if we have already opened a file with the same inode.
397 // This occurs when one dir is symlinked to another, for example.
398 FileEntry &UFE = UniqueRealFiles.getFile(InterndFileName, StatBuf);
400 NamedFileEnt.setValue(&UFE);
401 if (UFE.getName()) { // Already have an entry with this inode, return it.
402 // If the stat process opened the file, close it to avoid a FD leak.
403 if (FileDescriptor != -1)
404 close(FileDescriptor);
409 // Otherwise, we don't have this directory yet, add it.
410 // FIXME: Change the name to be a char* that points back to the
411 // 'SeenFileEntries' key.
412 UFE.Name = InterndFileName;
413 UFE.Size = StatBuf.st_size;
414 UFE.ModTime = StatBuf.st_mtime;
416 UFE.UID = NextFileUID++;
417 UFE.FD = FileDescriptor;
422 FileManager::getVirtualFile(StringRef Filename, off_t Size,
423 time_t ModificationTime) {
426 // See if there is already an entry in the map.
427 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
428 SeenFileEntries.GetOrCreateValue(Filename);
430 // See if there is already an entry in the map.
431 if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
432 return NamedFileEnt.getValue();
434 ++NumFileCacheMisses;
436 // By default, initialize it to invalid.
437 NamedFileEnt.setValue(NON_EXISTENT_FILE);
439 addAncestorsAsVirtualDirs(Filename);
442 // Now that all ancestors of Filename are in the cache, the
443 // following call is guaranteed to find the DirectoryEntry from the
445 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
446 /*CacheFailure=*/true);
448 "The directory of a virtual file should already be in the cache.");
450 // Check to see if the file exists. If so, drop the virtual file
452 const char *InterndFileName = NamedFileEnt.getKeyData();
453 if (getStatValue(InterndFileName, StatBuf, true, 0) == 0) {
454 StatBuf.st_size = Size;
455 StatBuf.st_mtime = ModificationTime;
456 UFE = &UniqueRealFiles.getFile(InterndFileName, StatBuf);
458 NamedFileEnt.setValue(UFE);
460 // If we had already opened this file, close it now so we don't
461 // leak the descriptor. We're not going to use the file
462 // descriptor anyway, since this is a virtual file.
468 // If we already have an entry with this inode, return it.
474 UFE = new FileEntry();
475 VirtualFileEntries.push_back(UFE);
476 NamedFileEnt.setValue(UFE);
479 UFE->Name = InterndFileName;
481 UFE->ModTime = ModificationTime;
483 UFE->UID = NextFileUID++;
488 void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
489 StringRef pathRef(path.data(), path.size());
491 if (FileSystemOpts.WorkingDir.empty()
492 || llvm::sys::path::is_absolute(pathRef))
495 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
496 llvm::sys::path::append(NewPath, pathRef);
500 llvm::MemoryBuffer *FileManager::
501 getBufferForFile(const FileEntry *Entry, std::string *ErrorStr,
503 OwningPtr<llvm::MemoryBuffer> Result;
506 uint64_t FileSize = Entry->getSize();
507 // If there's a high enough chance that the file have changed since we
508 // got its size, force a stat before opening it.
512 const char *Filename = Entry->getName();
513 // If the file is already open, use the open file descriptor.
514 if (Entry->FD != -1) {
515 ec = llvm::MemoryBuffer::getOpenFile(Entry->FD, Filename, Result, FileSize);
517 *ErrorStr = ec.message();
521 return Result.take();
524 // Otherwise, open the file.
526 if (FileSystemOpts.WorkingDir.empty()) {
527 ec = llvm::MemoryBuffer::getFile(Filename, Result, FileSize);
529 *ErrorStr = ec.message();
530 return Result.take();
533 SmallString<128> FilePath(Entry->getName());
534 FixupRelativePath(FilePath);
535 ec = llvm::MemoryBuffer::getFile(FilePath.str(), Result, FileSize);
537 *ErrorStr = ec.message();
538 return Result.take();
541 llvm::MemoryBuffer *FileManager::
542 getBufferForFile(StringRef Filename, std::string *ErrorStr) {
543 OwningPtr<llvm::MemoryBuffer> Result;
545 if (FileSystemOpts.WorkingDir.empty()) {
546 ec = llvm::MemoryBuffer::getFile(Filename, Result);
548 *ErrorStr = ec.message();
549 return Result.take();
552 SmallString<128> FilePath(Filename);
553 FixupRelativePath(FilePath);
554 ec = llvm::MemoryBuffer::getFile(FilePath.c_str(), Result);
556 *ErrorStr = ec.message();
557 return Result.take();
560 /// getStatValue - Get the 'stat' information for the specified path,
561 /// using the cache to accelerate it if possible. This returns true
562 /// if the path points to a virtual file or does not exist, or returns
563 /// false if it's an existent real file. If FileDescriptor is NULL,
564 /// do directory look-up instead of file look-up.
565 bool FileManager::getStatValue(const char *Path, struct stat &StatBuf,
566 bool isFile, int *FileDescriptor) {
567 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
569 if (FileSystemOpts.WorkingDir.empty())
570 return FileSystemStatCache::get(Path, StatBuf, isFile, FileDescriptor,
573 SmallString<128> FilePath(Path);
574 FixupRelativePath(FilePath);
576 return FileSystemStatCache::get(FilePath.c_str(), StatBuf,
577 isFile, FileDescriptor, StatCache.get());
580 bool FileManager::getNoncachedStatValue(StringRef Path,
581 struct stat &StatBuf) {
582 SmallString<128> FilePath(Path);
583 FixupRelativePath(FilePath);
585 return ::stat(FilePath.c_str(), &StatBuf) != 0;
588 void FileManager::invalidateCache(const FileEntry *Entry) {
589 assert(Entry && "Cannot invalidate a NULL FileEntry");
591 SeenFileEntries.erase(Entry->getName());
593 // FileEntry invalidation should not block future optimizations in the file
594 // caches. Possible alternatives are cache truncation (invalidate last N) or
595 // invalidation of the whole cache.
596 UniqueRealFiles.erase(Entry);
600 void FileManager::GetUniqueIDMapping(
601 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
603 UIDToFiles.resize(NextFileUID);
606 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
607 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
609 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
610 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
612 // Map virtual file entries
613 for (SmallVector<FileEntry*, 4>::const_iterator
614 VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
615 VFE != VFEEnd; ++VFE)
616 if (*VFE && *VFE != NON_EXISTENT_FILE)
617 UIDToFiles[(*VFE)->getUID()] = *VFE;
620 void FileManager::modifyFileEntry(FileEntry *File,
621 off_t Size, time_t ModificationTime) {
623 File->ModTime = ModificationTime;
626 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
627 // FIXME: use llvm::sys::fs::canonical() when it gets implemented
629 llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
630 = CanonicalDirNames.find(Dir);
631 if (Known != CanonicalDirNames.end())
632 return Known->second;
634 StringRef CanonicalName(Dir->getName());
635 char CanonicalNameBuf[PATH_MAX];
636 if (realpath(Dir->getName(), CanonicalNameBuf)) {
637 unsigned Len = strlen(CanonicalNameBuf);
638 char *Mem = static_cast<char *>(CanonicalNameStorage.Allocate(Len, 1));
639 memcpy(Mem, CanonicalNameBuf, Len);
640 CanonicalName = StringRef(Mem, Len);
643 CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
644 return CanonicalName;
646 return StringRef(Dir->getName());
650 void FileManager::PrintStats() const {
651 llvm::errs() << "\n*** File Manager Stats:\n";
652 llvm::errs() << UniqueRealFiles.size() << " real files found, "
653 << UniqueRealDirs.size() << " real dirs found.\n";
654 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
655 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
656 llvm::errs() << NumDirLookups << " dir lookups, "
657 << NumDirCacheMisses << " dir cache misses.\n";
658 llvm::errs() << NumFileLookups << " file lookups, "
659 << NumFileCacheMisses << " file cache misses.\n";
661 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;