1 //===--- FileSystemStatCache.cpp - Caching for 'stat' calls ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the FileSystemStatCache interface. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Basic/FileSystemStatCache.h" 15 #include "llvm/System/Path.h" 16 17 // FIXME: This is terrible, we need this for ::close. 18 #if !defined(_MSC_VER) && !defined(__MINGW32__) 19 #include <unistd.h> 20 #include <sys/uio.h> 21 #else 22 #include <io.h> 23 #endif 24 using namespace clang; 25 26 #if defined(_MSC_VER) 27 #define S_ISDIR(s) (_S_IFDIR & s) 28 #endif 29 30 /// FileSystemStatCache::get - Get the 'stat' information for the specified 31 /// path, using the cache to accellerate it if possible. This returns true if 32 /// the path does not exist or false if it exists. 33 /// 34 /// If FileDescriptor is non-null, then this lookup should only return success 35 /// for files (not directories). If it is null this lookup should only return 36 /// success for directories (not files). On a successful file lookup, the 37 /// implementation can optionally fill in FileDescriptor with a valid 38 /// descriptor and the client guarantees that it will close it. 39 bool FileSystemStatCache::get(const char *Path, struct stat &StatBuf, 40 int *FileDescriptor, FileSystemStatCache *Cache) { 41 LookupResult R; 42 43 if (Cache) 44 R = Cache->getStat(Path, StatBuf, FileDescriptor); 45 else 46 R = ::stat(Path, &StatBuf) != 0 ? CacheMissing : CacheExists; 47 48 // If the path doesn't exist, return failure. 49 if (R == CacheMissing) return true; 50 51 // If the path exists, make sure that its "directoryness" matches the clients 52 // demands. 53 bool isForDir = FileDescriptor == 0; 54 if (S_ISDIR(StatBuf.st_mode) != isForDir) { 55 // If not, close the file if opened. 56 if (FileDescriptor && *FileDescriptor != -1) { 57 ::close(*FileDescriptor); 58 *FileDescriptor = -1; 59 } 60 61 return true; 62 } 63 64 return false; 65 } 66 67 68 MemorizeStatCalls::LookupResult 69 MemorizeStatCalls::getStat(const char *Path, struct stat &StatBuf, 70 int *FileDescriptor) { 71 LookupResult Result = statChained(Path, StatBuf, FileDescriptor); 72 73 // Do not cache failed stats, it is easy to construct common inconsistent 74 // situations if we do, and they are not important for PCH performance (which 75 // currently only needs the stats to construct the initial FileManager 76 // entries). 77 if (Result == CacheMissing) 78 return Result; 79 80 // Cache file 'stat' results and directories with absolutely paths. 81 if (!S_ISDIR(StatBuf.st_mode) || llvm::sys::Path(Path).isAbsolute()) 82 StatCalls[Path] = StatBuf; 83 84 return Result; 85 } 86