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/Support/FileSystem.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/system_error.h"
28 #include "llvm/Config/llvm-config.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 using namespace clang;
45 // FIXME: Enhance libsystem to support inode and other fields.
48 /// NON_EXISTENT_DIR - A special value distinct from null that is used to
49 /// represent a dir name that doesn't exist on the disk.
50 #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
52 /// NON_EXISTENT_FILE - A special value distinct from null that is used to
53 /// represent a filename that doesn't exist on the disk.
54 #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
57 FileEntry::~FileEntry() {
58 // If this FileEntry owns an open file descriptor that never got used, close
60 if (FD != -1) ::close(FD);
63 bool FileEntry::isNamedPipe() const {
64 return S_ISFIFO(FileMode);
67 //===----------------------------------------------------------------------===//
69 //===----------------------------------------------------------------------===//
74 static std::string GetFullPath(const char *relPath) {
75 char *absPathStrPtr = _fullpath(NULL, relPath, 0);
76 assert(absPathStrPtr && "_fullpath() returned NULL!");
78 std::string absPath(absPathStrPtr);
85 class FileManager::UniqueDirContainer {
86 /// UniqueDirs - Cache from full path to existing directories/files.
88 llvm::StringMap<DirectoryEntry> UniqueDirs;
91 /// getDirectory - Return an existing DirectoryEntry with the given
92 /// name if there is already one; otherwise create and return a
93 /// default-constructed DirectoryEntry.
94 DirectoryEntry &getDirectory(const char *Name,
95 const struct stat & /*StatBuf*/) {
96 std::string FullPath(GetFullPath(Name));
97 return UniqueDirs.GetOrCreateValue(FullPath).getValue();
100 size_t size() const { return UniqueDirs.size(); }
103 class FileManager::UniqueFileContainer {
104 /// UniqueFiles - Cache from full path to existing directories/files.
106 llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;
109 /// getFile - Return an existing FileEntry with the given name if
110 /// there is already one; otherwise create and return a
111 /// default-constructed FileEntry.
112 FileEntry &getFile(const char *Name, const struct stat & /*StatBuf*/) {
113 std::string FullPath(GetFullPath(Name));
115 // Lowercase string because Windows filesystem is case insensitive.
116 FullPath = StringRef(FullPath).lower();
117 return UniqueFiles.GetOrCreateValue(FullPath).getValue();
120 size_t size() const { return UniqueFiles.size(); }
122 void erase(const FileEntry *Entry) {
123 std::string FullPath(GetFullPath(Entry->getName()));
125 // Lowercase string because Windows filesystem is case insensitive.
126 FullPath = StringRef(FullPath).lower();
127 UniqueFiles.erase(FullPath);
131 //===----------------------------------------------------------------------===//
132 // Unix-like Systems.
133 //===----------------------------------------------------------------------===//
137 class FileManager::UniqueDirContainer {
138 /// UniqueDirs - Cache from ID's to existing directories/files.
139 std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;
142 /// getDirectory - Return an existing DirectoryEntry with the given
143 /// ID's if there is already one; otherwise create and return a
144 /// default-constructed DirectoryEntry.
145 DirectoryEntry &getDirectory(const char * /*Name*/,
146 const struct stat &StatBuf) {
147 return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
150 size_t size() const { return UniqueDirs.size(); }
153 class FileManager::UniqueFileContainer {
154 /// UniqueFiles - Cache from ID's to existing directories/files.
155 std::set<FileEntry> UniqueFiles;
158 /// getFile - Return an existing FileEntry with the given ID's if
159 /// there is already one; otherwise create and return a
160 /// default-constructed FileEntry.
161 FileEntry &getFile(const char * /*Name*/, const struct stat &StatBuf) {
163 const_cast<FileEntry&>(
164 *UniqueFiles.insert(FileEntry(StatBuf.st_dev,
166 StatBuf.st_mode)).first);
169 size_t size() const { return UniqueFiles.size(); }
171 void erase(const FileEntry *Entry) { UniqueFiles.erase(*Entry); }
176 //===----------------------------------------------------------------------===//
178 //===----------------------------------------------------------------------===//
180 FileManager::FileManager(const FileSystemOptions &FSO)
181 : FileSystemOpts(FSO),
182 UniqueRealDirs(*new UniqueDirContainer()),
183 UniqueRealFiles(*new UniqueFileContainer()),
184 SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
185 NumDirLookups = NumFileLookups = 0;
186 NumDirCacheMisses = NumFileCacheMisses = 0;
189 FileManager::~FileManager() {
190 delete &UniqueRealDirs;
191 delete &UniqueRealFiles;
192 for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
193 delete VirtualFileEntries[i];
194 for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
195 delete VirtualDirectoryEntries[i];
198 void FileManager::addStatCache(FileSystemStatCache *statCache,
200 assert(statCache && "No stat cache provided?");
201 if (AtBeginning || StatCache.get() == 0) {
202 statCache->setNextStatCache(StatCache.take());
203 StatCache.reset(statCache);
207 FileSystemStatCache *LastCache = StatCache.get();
208 while (LastCache->getNextStatCache())
209 LastCache = LastCache->getNextStatCache();
211 LastCache->setNextStatCache(statCache);
214 void FileManager::removeStatCache(FileSystemStatCache *statCache) {
218 if (StatCache.get() == statCache) {
219 // This is the first stat cache.
220 StatCache.reset(StatCache->takeNextStatCache());
224 // Find the stat cache in the list.
225 FileSystemStatCache *PrevCache = StatCache.get();
226 while (PrevCache && PrevCache->getNextStatCache() != statCache)
227 PrevCache = PrevCache->getNextStatCache();
229 assert(PrevCache && "Stat cache not found for removal");
230 PrevCache->setNextStatCache(statCache->getNextStatCache());
233 void FileManager::clearStatCaches() {
237 /// \brief Retrieve the directory that the given file name resides in.
238 /// Filename can point to either a real file or a virtual file.
239 static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
242 if (Filename.empty())
245 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
246 return NULL; // If Filename is a directory.
248 StringRef DirName = llvm::sys::path::parent_path(Filename);
249 // Use the current directory if file has no path component.
253 return FileMgr.getDirectory(DirName, CacheFailure);
256 /// Add all ancestors of the given path (pointing to either a file or
257 /// a directory) as virtual directories.
258 void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
259 StringRef DirName = llvm::sys::path::parent_path(Path);
263 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
264 SeenDirEntries.GetOrCreateValue(DirName);
266 // When caching a virtual directory, we always cache its ancestors
267 // at the same time. Therefore, if DirName is already in the cache,
268 // we don't need to recurse as its ancestors must also already be in
270 if (NamedDirEnt.getValue())
273 // Add the virtual directory to the cache.
274 DirectoryEntry *UDE = new DirectoryEntry;
275 UDE->Name = NamedDirEnt.getKeyData();
276 NamedDirEnt.setValue(UDE);
277 VirtualDirectoryEntries.push_back(UDE);
279 // Recursively add the other ancestors.
280 addAncestorsAsVirtualDirs(DirName);
283 const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
285 // stat doesn't like trailing separators except for root directory.
286 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
287 // (though it can strip '\\')
288 if (DirName.size() > 1 &&
289 DirName != llvm::sys::path::root_path(DirName) &&
290 llvm::sys::path::is_separator(DirName.back()))
291 DirName = DirName.substr(0, DirName.size()-1);
294 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
295 SeenDirEntries.GetOrCreateValue(DirName);
297 // See if there was already an entry in the map. Note that the map
298 // contains both virtual and real directories.
299 if (NamedDirEnt.getValue())
300 return NamedDirEnt.getValue() == NON_EXISTENT_DIR
301 ? 0 : NamedDirEnt.getValue();
305 // By default, initialize it to invalid.
306 NamedDirEnt.setValue(NON_EXISTENT_DIR);
308 // Get the null-terminated directory name as stored as the key of the
309 // SeenDirEntries map.
310 const char *InterndDirName = NamedDirEnt.getKeyData();
312 // Check to see if the directory exists.
314 if (getStatValue(InterndDirName, StatBuf, 0/*directory lookup*/)) {
315 // There's no real directory at the given path.
317 SeenDirEntries.erase(DirName);
321 // It exists. See if we have already opened a directory with the
322 // same inode (this occurs on Unix-like systems when one dir is
323 // symlinked to another, for example) or the same path (on
325 DirectoryEntry &UDE = UniqueRealDirs.getDirectory(InterndDirName, StatBuf);
327 NamedDirEnt.setValue(&UDE);
328 if (!UDE.getName()) {
329 // We don't have this directory yet, add it. We use the string
330 // key from the SeenDirEntries map as the string.
331 UDE.Name = InterndDirName;
337 const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
341 // See if there is already an entry in the map.
342 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
343 SeenFileEntries.GetOrCreateValue(Filename);
345 // See if there is already an entry in the map.
346 if (NamedFileEnt.getValue())
347 return NamedFileEnt.getValue() == NON_EXISTENT_FILE
348 ? 0 : NamedFileEnt.getValue();
350 ++NumFileCacheMisses;
352 // By default, initialize it to invalid.
353 NamedFileEnt.setValue(NON_EXISTENT_FILE);
355 // Get the null-terminated file name as stored as the key of the
356 // SeenFileEntries map.
357 const char *InterndFileName = NamedFileEnt.getKeyData();
359 // Look up the directory for the file. When looking up something like
360 // sys/foo.h we'll discover all of the search directories that have a 'sys'
361 // subdirectory. This will let us avoid having to waste time on known-to-fail
362 // searches when we go to find sys/bar.h, because all the search directories
363 // without a 'sys' subdir will get a cached failure result.
364 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
366 if (DirInfo == 0) { // Directory doesn't exist, file can't exist.
368 SeenFileEntries.erase(Filename);
373 // FIXME: Use the directory info to prune this, before doing the stat syscall.
374 // FIXME: This will reduce the # syscalls.
376 // Nope, there isn't. Check to see if the file exists.
377 int FileDescriptor = -1;
379 if (getStatValue(InterndFileName, StatBuf, &FileDescriptor)) {
380 // There's no real file at the given path.
382 SeenFileEntries.erase(Filename);
387 if (FileDescriptor != -1 && !openFile) {
388 close(FileDescriptor);
392 // It exists. See if we have already opened a file with the same inode.
393 // This occurs when one dir is symlinked to another, for example.
394 FileEntry &UFE = UniqueRealFiles.getFile(InterndFileName, StatBuf);
396 NamedFileEnt.setValue(&UFE);
397 if (UFE.getName()) { // Already have an entry with this inode, return it.
398 // If the stat process opened the file, close it to avoid a FD leak.
399 if (FileDescriptor != -1)
400 close(FileDescriptor);
405 // Otherwise, we don't have this directory yet, add it.
406 // FIXME: Change the name to be a char* that points back to the
407 // 'SeenFileEntries' key.
408 UFE.Name = InterndFileName;
409 UFE.Size = StatBuf.st_size;
410 UFE.ModTime = StatBuf.st_mtime;
412 UFE.UID = NextFileUID++;
413 UFE.FD = FileDescriptor;
418 FileManager::getVirtualFile(StringRef Filename, off_t Size,
419 time_t ModificationTime) {
422 // See if there is already an entry in the map.
423 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
424 SeenFileEntries.GetOrCreateValue(Filename);
426 // See if there is already an entry in the map.
427 if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
428 return NamedFileEnt.getValue();
430 ++NumFileCacheMisses;
432 // By default, initialize it to invalid.
433 NamedFileEnt.setValue(NON_EXISTENT_FILE);
435 addAncestorsAsVirtualDirs(Filename);
438 // Now that all ancestors of Filename are in the cache, the
439 // following call is guaranteed to find the DirectoryEntry from the
441 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
442 /*CacheFailure=*/true);
444 "The directory of a virtual file should already be in the cache.");
446 // Check to see if the file exists. If so, drop the virtual file
447 int FileDescriptor = -1;
449 const char *InterndFileName = NamedFileEnt.getKeyData();
450 if (getStatValue(InterndFileName, StatBuf, &FileDescriptor) == 0) {
451 // If the stat process opened the file, close it to avoid a FD leak.
452 if (FileDescriptor != -1)
453 close(FileDescriptor);
455 StatBuf.st_size = Size;
456 StatBuf.st_mtime = ModificationTime;
457 UFE = &UniqueRealFiles.getFile(InterndFileName, StatBuf);
459 NamedFileEnt.setValue(UFE);
461 // If we had already opened this file, close it now so we don't
462 // leak the descriptor. We're not going to use the file
463 // descriptor anyway, since this is a virtual file.
469 // If we already have an entry with this inode, return it.
475 UFE = new FileEntry();
476 VirtualFileEntries.push_back(UFE);
477 NamedFileEnt.setValue(UFE);
480 UFE->Name = InterndFileName;
482 UFE->ModTime = ModificationTime;
484 UFE->UID = NextFileUID++;
489 void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
490 StringRef pathRef(path.data(), path.size());
492 if (FileSystemOpts.WorkingDir.empty()
493 || llvm::sys::path::is_absolute(pathRef))
496 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
497 llvm::sys::path::append(NewPath, pathRef);
501 llvm::MemoryBuffer *FileManager::
502 getBufferForFile(const FileEntry *Entry, std::string *ErrorStr,
504 OwningPtr<llvm::MemoryBuffer> Result;
507 uint64_t FileSize = Entry->getSize();
508 // If there's a high enough chance that the file have changed since we
509 // got its size, force a stat before opening it.
513 const char *Filename = Entry->getName();
514 // If the file is already open, use the open file descriptor.
515 if (Entry->FD != -1) {
516 ec = llvm::MemoryBuffer::getOpenFile(Entry->FD, Filename, Result, FileSize);
518 *ErrorStr = ec.message();
522 return Result.take();
525 // Otherwise, open the file.
527 if (FileSystemOpts.WorkingDir.empty()) {
528 ec = llvm::MemoryBuffer::getFile(Filename, Result, FileSize);
530 *ErrorStr = ec.message();
531 return Result.take();
534 SmallString<128> FilePath(Entry->getName());
535 FixupRelativePath(FilePath);
536 ec = llvm::MemoryBuffer::getFile(FilePath.str(), Result, FileSize);
538 *ErrorStr = ec.message();
539 return Result.take();
542 llvm::MemoryBuffer *FileManager::
543 getBufferForFile(StringRef Filename, std::string *ErrorStr) {
544 OwningPtr<llvm::MemoryBuffer> Result;
546 if (FileSystemOpts.WorkingDir.empty()) {
547 ec = llvm::MemoryBuffer::getFile(Filename, Result);
549 *ErrorStr = ec.message();
550 return Result.take();
553 SmallString<128> FilePath(Filename);
554 FixupRelativePath(FilePath);
555 ec = llvm::MemoryBuffer::getFile(FilePath.c_str(), Result);
557 *ErrorStr = ec.message();
558 return Result.take();
561 /// getStatValue - Get the 'stat' information for the specified path,
562 /// using the cache to accelerate it if possible. This returns true
563 /// if the path points to a virtual file or does not exist, or returns
564 /// false if it's an existent real file. If FileDescriptor is NULL,
565 /// do directory look-up instead of file look-up.
566 bool FileManager::getStatValue(const char *Path, struct stat &StatBuf,
567 int *FileDescriptor) {
568 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
570 if (FileSystemOpts.WorkingDir.empty())
571 return FileSystemStatCache::get(Path, StatBuf, FileDescriptor,
574 SmallString<128> FilePath(Path);
575 FixupRelativePath(FilePath);
577 return FileSystemStatCache::get(FilePath.c_str(), StatBuf, FileDescriptor,
581 bool FileManager::getNoncachedStatValue(StringRef Path,
582 struct stat &StatBuf) {
583 SmallString<128> FilePath(Path);
584 FixupRelativePath(FilePath);
586 return ::stat(FilePath.c_str(), &StatBuf) != 0;
589 void FileManager::invalidateCache(const FileEntry *Entry) {
590 assert(Entry && "Cannot invalidate a NULL FileEntry");
592 SeenFileEntries.erase(Entry->getName());
594 // FileEntry invalidation should not block future optimizations in the file
595 // caches. Possible alternatives are cache truncation (invalidate last N) or
596 // invalidation of the whole cache.
597 UniqueRealFiles.erase(Entry);
601 void FileManager::GetUniqueIDMapping(
602 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
604 UIDToFiles.resize(NextFileUID);
607 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
608 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
610 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
611 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
613 // Map virtual file entries
614 for (SmallVector<FileEntry*, 4>::const_iterator
615 VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
616 VFE != VFEEnd; ++VFE)
617 if (*VFE && *VFE != NON_EXISTENT_FILE)
618 UIDToFiles[(*VFE)->getUID()] = *VFE;
621 void FileManager::modifyFileEntry(FileEntry *File,
622 off_t Size, time_t ModificationTime) {
624 File->ModTime = ModificationTime;
628 void FileManager::PrintStats() const {
629 llvm::errs() << "\n*** File Manager Stats:\n";
630 llvm::errs() << UniqueRealFiles.size() << " real files found, "
631 << UniqueRealDirs.size() << " real dirs found.\n";
632 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
633 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
634 llvm::errs() << NumDirLookups << " dir lookups, "
635 << NumDirCacheMisses << " dir cache misses.\n";
636 llvm::errs() << NumFileLookups << " file lookups, "
637 << NumFileCacheMisses << " file cache misses.\n";
639 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;