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 using namespace clang;
17 
18 #if defined(_MSC_VER)
19 #define S_ISDIR(s) (_S_IFDIR & s)
20 #endif
21 
22 /// FileSystemStatCache::get - Get the 'stat' information for the specified
23 /// path, using the cache to accellerate it if possible.  This returns true if
24 /// the path does not exist or false if it exists.
25 ///
26 /// If FileDescriptor is non-null, then this lookup should only return success
27 /// for files (not directories).  If it is null this lookup should only return
28 /// success for directories (not files).  On a successful file lookup, the
29 /// implementation can optionally fill in FileDescriptor with a valid
30 /// descriptor and the client guarantees that it will close it.
31 bool FileSystemStatCache::get(const char *Path, struct stat &StatBuf,
32                               int *FileDescriptor, FileSystemStatCache *Cache) {
33   LookupResult R;
34 
35   if (Cache)
36     R = Cache->getStat(Path, StatBuf, FileDescriptor);
37   else
38     R = ::stat(Path, &StatBuf) != 0 ? CacheMissing : CacheExists;
39 
40   if (R == CacheMissing) return true;
41 
42   bool isForDir = FileDescriptor == 0;
43   return S_ISDIR(StatBuf.st_mode) != isForDir;
44 }
45 
46 
47 MemorizeStatCalls::LookupResult
48 MemorizeStatCalls::getStat(const char *Path, struct stat &StatBuf,
49                            int *FileDescriptor) {
50   LookupResult Result = statChained(Path, StatBuf, FileDescriptor);
51 
52   // Do not cache failed stats, it is easy to construct common inconsistent
53   // situations if we do, and they are not important for PCH performance (which
54   // currently only needs the stats to construct the initial FileManager
55   // entries).
56   if (Result == CacheMissing)
57     return Result;
58 
59   // Cache file 'stat' results and directories with absolutely paths.
60   if (!S_ISDIR(StatBuf.st_mode) || llvm::sys::Path(Path).isAbsolute())
61     StatCalls[Path] = StatBuf;
62 
63   return Result;
64 }
65