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 using namespace clang;
42 // FIXME: Enhance libsystem to support inode and other fields.
45 /// NON_EXISTENT_DIR - A special value distinct from null that is used to
46 /// represent a dir name that doesn't exist on the disk.
47 #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
49 /// NON_EXISTENT_FILE - A special value distinct from null that is used to
50 /// represent a filename that doesn't exist on the disk.
51 #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
54 FileEntry::~FileEntry() {
55 // If this FileEntry owns an open file descriptor that never got used, close
57 if (FD != -1) ::close(FD);
60 //===----------------------------------------------------------------------===//
62 //===----------------------------------------------------------------------===//
67 static std::string GetFullPath(const char *relPath) {
68 char *absPathStrPtr = _fullpath(NULL, relPath, 0);
69 assert(absPathStrPtr && "_fullpath() returned NULL!");
71 std::string absPath(absPathStrPtr);
78 class FileManager::UniqueDirContainer {
79 /// UniqueDirs - Cache from full path to existing directories/files.
81 llvm::StringMap<DirectoryEntry> UniqueDirs;
84 /// getDirectory - Return an existing DirectoryEntry with the given
85 /// name if there is already one; otherwise create and return a
86 /// default-constructed DirectoryEntry.
87 DirectoryEntry &getDirectory(const char *Name,
88 const struct stat & /*StatBuf*/) {
89 std::string FullPath(GetFullPath(Name));
90 return UniqueDirs.GetOrCreateValue(FullPath).getValue();
93 size_t size() const { return UniqueDirs.size(); }
96 class FileManager::UniqueFileContainer {
97 /// UniqueFiles - Cache from full path to existing directories/files.
99 llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;
102 /// getFile - Return an existing FileEntry with the given name if
103 /// there is already one; otherwise create and return a
104 /// default-constructed FileEntry.
105 FileEntry &getFile(const char *Name, const struct stat & /*StatBuf*/) {
106 std::string FullPath(GetFullPath(Name));
108 // Lowercase string because Windows filesystem is case insensitive.
109 FullPath = StringRef(FullPath).lower();
110 return UniqueFiles.GetOrCreateValue(FullPath).getValue();
113 size_t size() const { return UniqueFiles.size(); }
115 void erase(const FileEntry *Entry) {
116 std::string FullPath(GetFullPath(Entry->getName()));
118 // Lowercase string because Windows filesystem is case insensitive.
119 FullPath = StringRef(FullPath).lower();
120 UniqueFiles.erase(FullPath);
124 //===----------------------------------------------------------------------===//
125 // Unix-like Systems.
126 //===----------------------------------------------------------------------===//
130 class FileManager::UniqueDirContainer {
131 /// UniqueDirs - Cache from ID's to existing directories/files.
132 std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;
135 /// getDirectory - Return an existing DirectoryEntry with the given
136 /// ID's if there is already one; otherwise create and return a
137 /// default-constructed DirectoryEntry.
138 DirectoryEntry &getDirectory(const char * /*Name*/,
139 const struct stat &StatBuf) {
140 return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
143 size_t size() const { return UniqueDirs.size(); }
146 class FileManager::UniqueFileContainer {
147 /// UniqueFiles - Cache from ID's to existing directories/files.
148 std::set<FileEntry> UniqueFiles;
151 /// getFile - Return an existing FileEntry with the given ID's if
152 /// there is already one; otherwise create and return a
153 /// default-constructed FileEntry.
154 FileEntry &getFile(const char * /*Name*/, const struct stat &StatBuf) {
156 const_cast<FileEntry&>(
157 *UniqueFiles.insert(FileEntry(StatBuf.st_dev,
159 StatBuf.st_mode)).first);
162 size_t size() const { return UniqueFiles.size(); }
164 void erase(const FileEntry *Entry) { UniqueFiles.erase(*Entry); }
169 //===----------------------------------------------------------------------===//
171 //===----------------------------------------------------------------------===//
173 FileManager::FileManager(const FileSystemOptions &FSO)
174 : FileSystemOpts(FSO),
175 UniqueRealDirs(*new UniqueDirContainer()),
176 UniqueRealFiles(*new UniqueFileContainer()),
177 SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
178 NumDirLookups = NumFileLookups = 0;
179 NumDirCacheMisses = NumFileCacheMisses = 0;
182 FileManager::~FileManager() {
183 delete &UniqueRealDirs;
184 delete &UniqueRealFiles;
185 for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
186 delete VirtualFileEntries[i];
187 for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
188 delete VirtualDirectoryEntries[i];
191 void FileManager::addStatCache(FileSystemStatCache *statCache,
193 assert(statCache && "No stat cache provided?");
194 if (AtBeginning || StatCache.get() == 0) {
195 statCache->setNextStatCache(StatCache.take());
196 StatCache.reset(statCache);
200 FileSystemStatCache *LastCache = StatCache.get();
201 while (LastCache->getNextStatCache())
202 LastCache = LastCache->getNextStatCache();
204 LastCache->setNextStatCache(statCache);
207 void FileManager::removeStatCache(FileSystemStatCache *statCache) {
211 if (StatCache.get() == statCache) {
212 // This is the first stat cache.
213 StatCache.reset(StatCache->takeNextStatCache());
217 // Find the stat cache in the list.
218 FileSystemStatCache *PrevCache = StatCache.get();
219 while (PrevCache && PrevCache->getNextStatCache() != statCache)
220 PrevCache = PrevCache->getNextStatCache();
222 assert(PrevCache && "Stat cache not found for removal");
223 PrevCache->setNextStatCache(statCache->getNextStatCache());
226 void FileManager::clearStatCaches() {
230 /// \brief Retrieve the directory that the given file name resides in.
231 /// Filename can point to either a real file or a virtual file.
232 static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
235 if (Filename.empty())
238 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
239 return NULL; // If Filename is a directory.
241 StringRef DirName = llvm::sys::path::parent_path(Filename);
242 // Use the current directory if file has no path component.
246 return FileMgr.getDirectory(DirName, CacheFailure);
249 /// Add all ancestors of the given path (pointing to either a file or
250 /// a directory) as virtual directories.
251 void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
252 StringRef DirName = llvm::sys::path::parent_path(Path);
256 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
257 SeenDirEntries.GetOrCreateValue(DirName);
259 // When caching a virtual directory, we always cache its ancestors
260 // at the same time. Therefore, if DirName is already in the cache,
261 // we don't need to recurse as its ancestors must also already be in
263 if (NamedDirEnt.getValue())
266 // Add the virtual directory to the cache.
267 DirectoryEntry *UDE = new DirectoryEntry;
268 UDE->Name = NamedDirEnt.getKeyData();
269 NamedDirEnt.setValue(UDE);
270 VirtualDirectoryEntries.push_back(UDE);
272 // Recursively add the other ancestors.
273 addAncestorsAsVirtualDirs(DirName);
276 const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
278 // stat doesn't like trailing separators except for root directory.
279 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
280 // (though it can strip '\\')
281 if (DirName.size() > 1 &&
282 DirName != llvm::sys::path::root_path(DirName) &&
283 llvm::sys::path::is_separator(DirName.back()))
284 DirName = DirName.substr(0, DirName.size()-1);
287 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
288 SeenDirEntries.GetOrCreateValue(DirName);
290 // See if there was already an entry in the map. Note that the map
291 // contains both virtual and real directories.
292 if (NamedDirEnt.getValue())
293 return NamedDirEnt.getValue() == NON_EXISTENT_DIR
294 ? 0 : NamedDirEnt.getValue();
298 // By default, initialize it to invalid.
299 NamedDirEnt.setValue(NON_EXISTENT_DIR);
301 // Get the null-terminated directory name as stored as the key of the
302 // SeenDirEntries map.
303 const char *InterndDirName = NamedDirEnt.getKeyData();
305 // Check to see if the directory exists.
307 if (getStatValue(InterndDirName, StatBuf, 0/*directory lookup*/)) {
308 // There's no real directory at the given path.
310 SeenDirEntries.erase(DirName);
314 // It exists. See if we have already opened a directory with the
315 // same inode (this occurs on Unix-like systems when one dir is
316 // symlinked to another, for example) or the same path (on
318 DirectoryEntry &UDE = UniqueRealDirs.getDirectory(InterndDirName, StatBuf);
320 NamedDirEnt.setValue(&UDE);
321 if (!UDE.getName()) {
322 // We don't have this directory yet, add it. We use the string
323 // key from the SeenDirEntries map as the string.
324 UDE.Name = InterndDirName;
330 const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
334 // See if there is already an entry in the map.
335 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
336 SeenFileEntries.GetOrCreateValue(Filename);
338 // See if there is already an entry in the map.
339 if (NamedFileEnt.getValue())
340 return NamedFileEnt.getValue() == NON_EXISTENT_FILE
341 ? 0 : NamedFileEnt.getValue();
343 ++NumFileCacheMisses;
345 // By default, initialize it to invalid.
346 NamedFileEnt.setValue(NON_EXISTENT_FILE);
348 // Get the null-terminated file name as stored as the key of the
349 // SeenFileEntries map.
350 const char *InterndFileName = NamedFileEnt.getKeyData();
352 // Look up the directory for the file. When looking up something like
353 // sys/foo.h we'll discover all of the search directories that have a 'sys'
354 // subdirectory. This will let us avoid having to waste time on known-to-fail
355 // searches when we go to find sys/bar.h, because all the search directories
356 // without a 'sys' subdir will get a cached failure result.
357 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
359 if (DirInfo == 0) { // Directory doesn't exist, file can't exist.
361 SeenFileEntries.erase(Filename);
366 // FIXME: Use the directory info to prune this, before doing the stat syscall.
367 // FIXME: This will reduce the # syscalls.
369 // Nope, there isn't. Check to see if the file exists.
370 int FileDescriptor = -1;
372 if (getStatValue(InterndFileName, StatBuf, &FileDescriptor)) {
373 // There's no real file at the given path.
375 SeenFileEntries.erase(Filename);
380 if (FileDescriptor != -1 && !openFile) {
381 close(FileDescriptor);
385 // It exists. See if we have already opened a file with the same inode.
386 // This occurs when one dir is symlinked to another, for example.
387 FileEntry &UFE = UniqueRealFiles.getFile(InterndFileName, StatBuf);
389 NamedFileEnt.setValue(&UFE);
390 if (UFE.getName()) { // Already have an entry with this inode, return it.
391 // If the stat process opened the file, close it to avoid a FD leak.
392 if (FileDescriptor != -1)
393 close(FileDescriptor);
398 // Otherwise, we don't have this directory yet, add it.
399 // FIXME: Change the name to be a char* that points back to the
400 // 'SeenFileEntries' key.
401 UFE.Name = InterndFileName;
402 UFE.Size = StatBuf.st_size;
403 UFE.ModTime = StatBuf.st_mtime;
405 UFE.UID = NextFileUID++;
406 UFE.FD = FileDescriptor;
411 FileManager::getVirtualFile(StringRef Filename, off_t Size,
412 time_t ModificationTime) {
415 // See if there is already an entry in the map.
416 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
417 SeenFileEntries.GetOrCreateValue(Filename);
419 // See if there is already an entry in the map.
420 if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
421 return NamedFileEnt.getValue();
423 ++NumFileCacheMisses;
425 // By default, initialize it to invalid.
426 NamedFileEnt.setValue(NON_EXISTENT_FILE);
428 addAncestorsAsVirtualDirs(Filename);
431 // Now that all ancestors of Filename are in the cache, the
432 // following call is guaranteed to find the DirectoryEntry from the
434 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
435 /*CacheFailure=*/true);
437 "The directory of a virtual file should already be in the cache.");
439 // Check to see if the file exists. If so, drop the virtual file
440 int FileDescriptor = -1;
442 const char *InterndFileName = NamedFileEnt.getKeyData();
443 if (getStatValue(InterndFileName, StatBuf, &FileDescriptor) == 0) {
444 // If the stat process opened the file, close it to avoid a FD leak.
445 if (FileDescriptor != -1)
446 close(FileDescriptor);
448 StatBuf.st_size = Size;
449 StatBuf.st_mtime = ModificationTime;
450 UFE = &UniqueRealFiles.getFile(InterndFileName, StatBuf);
452 NamedFileEnt.setValue(UFE);
454 // If we had already opened this file, close it now so we don't
455 // leak the descriptor. We're not going to use the file
456 // descriptor anyway, since this is a virtual file.
462 // If we already have an entry with this inode, return it.
468 UFE = new FileEntry();
469 VirtualFileEntries.push_back(UFE);
470 NamedFileEnt.setValue(UFE);
473 UFE->Name = InterndFileName;
475 UFE->ModTime = ModificationTime;
477 UFE->UID = NextFileUID++;
482 void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
483 StringRef pathRef(path.data(), path.size());
485 if (FileSystemOpts.WorkingDir.empty()
486 || llvm::sys::path::is_absolute(pathRef))
489 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
490 llvm::sys::path::append(NewPath, pathRef);
494 llvm::MemoryBuffer *FileManager::
495 getBufferForFile(const FileEntry *Entry, std::string *ErrorStr,
497 OwningPtr<llvm::MemoryBuffer> Result;
500 uint64_t FileSize = Entry->getSize();
501 // If there's a high enough chance that the file have changed since we
502 // got its size, force a stat before opening it.
506 const char *Filename = Entry->getName();
507 // If the file is already open, use the open file descriptor.
508 if (Entry->FD != -1) {
509 ec = llvm::MemoryBuffer::getOpenFile(Entry->FD, Filename, Result, FileSize);
511 *ErrorStr = ec.message();
515 return Result.take();
518 // Otherwise, open the file.
520 if (FileSystemOpts.WorkingDir.empty()) {
521 ec = llvm::MemoryBuffer::getFile(Filename, Result, FileSize);
523 *ErrorStr = ec.message();
524 return Result.take();
527 SmallString<128> FilePath(Entry->getName());
528 FixupRelativePath(FilePath);
529 ec = llvm::MemoryBuffer::getFile(FilePath.str(), Result, FileSize);
531 *ErrorStr = ec.message();
532 return Result.take();
535 llvm::MemoryBuffer *FileManager::
536 getBufferForFile(StringRef Filename, std::string *ErrorStr) {
537 OwningPtr<llvm::MemoryBuffer> Result;
539 if (FileSystemOpts.WorkingDir.empty()) {
540 ec = llvm::MemoryBuffer::getFile(Filename, Result);
542 *ErrorStr = ec.message();
543 return Result.take();
546 SmallString<128> FilePath(Filename);
547 FixupRelativePath(FilePath);
548 ec = llvm::MemoryBuffer::getFile(FilePath.c_str(), Result);
550 *ErrorStr = ec.message();
551 return Result.take();
554 /// getStatValue - Get the 'stat' information for the specified path,
555 /// using the cache to accelerate it if possible. This returns true
556 /// if the path points to a virtual file or does not exist, or returns
557 /// false if it's an existent real file. If FileDescriptor is NULL,
558 /// do directory look-up instead of file look-up.
559 bool FileManager::getStatValue(const char *Path, struct stat &StatBuf,
560 int *FileDescriptor) {
561 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
563 if (FileSystemOpts.WorkingDir.empty())
564 return FileSystemStatCache::get(Path, StatBuf, FileDescriptor,
567 SmallString<128> FilePath(Path);
568 FixupRelativePath(FilePath);
570 return FileSystemStatCache::get(FilePath.c_str(), StatBuf, FileDescriptor,
574 bool FileManager::getNoncachedStatValue(StringRef Path,
575 struct stat &StatBuf) {
576 SmallString<128> FilePath(Path);
577 FixupRelativePath(FilePath);
579 return ::stat(FilePath.c_str(), &StatBuf) != 0;
582 void FileManager::invalidateCache(const FileEntry *Entry) {
583 assert(Entry && "Cannot invalidate a NULL FileEntry");
585 SeenFileEntries.erase(Entry->getName());
587 // FileEntry invalidation should not block future optimizations in the file
588 // caches. Possible alternatives are cache truncation (invalidate last N) or
589 // invalidation of the whole cache.
590 UniqueRealFiles.erase(Entry);
594 void FileManager::GetUniqueIDMapping(
595 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
597 UIDToFiles.resize(NextFileUID);
600 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
601 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
603 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
604 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
606 // Map virtual file entries
607 for (SmallVector<FileEntry*, 4>::const_iterator
608 VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
609 VFE != VFEEnd; ++VFE)
610 if (*VFE && *VFE != NON_EXISTENT_FILE)
611 UIDToFiles[(*VFE)->getUID()] = *VFE;
614 void FileManager::modifyFileEntry(FileEntry *File,
615 off_t Size, time_t ModificationTime) {
617 File->ModTime = ModificationTime;
621 void FileManager::PrintStats() const {
622 llvm::errs() << "\n*** File Manager Stats:\n";
623 llvm::errs() << UniqueRealFiles.size() << " real files found, "
624 << UniqueRealDirs.size() << " real dirs found.\n";
625 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
626 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
627 llvm::errs() << NumDirLookups << " dir lookups, "
628 << NumDirCacheMisses << " dir cache misses.\n";
629 llvm::errs() << NumFileLookups << " file lookups, "
630 << NumFileCacheMisses << " file cache misses.\n";
632 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;