FileManager.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. ///===--- FileManager.cpp - File System Probing and Caching ----------------===//
  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 implements the FileManager interface.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // TODO: This should index all interesting directories with dirent calls.
  15. // getdirentries ?
  16. // opendir/readdir_r/closedir ?
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #include "clang/Basic/FileManager.h"
  20. #include "llvm/ADT/SmallString.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. #include "llvm/System/Path.h"
  23. #include "llvm/Config/config.h"
  24. #include <map>
  25. #include <set>
  26. #include <string>
  27. using namespace clang;
  28. // FIXME: Enhance libsystem to support inode and other fields.
  29. #include <sys/stat.h>
  30. #if defined(_MSC_VER)
  31. #define S_ISDIR(s) (_S_IFDIR & s)
  32. #endif
  33. /// NON_EXISTENT_DIR - A special value distinct from null that is used to
  34. /// represent a dir name that doesn't exist on the disk.
  35. #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
  36. //===----------------------------------------------------------------------===//
  37. // Windows.
  38. //===----------------------------------------------------------------------===//
  39. #ifdef LLVM_ON_WIN32
  40. #define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/' || (x) == '\\')
  41. namespace {
  42. static std::string GetFullPath(const char *relPath) {
  43. char *absPathStrPtr = _fullpath(NULL, relPath, 0);
  44. assert(absPathStrPtr && "_fullpath() returned NULL!");
  45. std::string absPath(absPathStrPtr);
  46. free(absPathStrPtr);
  47. return absPath;
  48. }
  49. }
  50. class FileManager::UniqueDirContainer {
  51. /// UniqueDirs - Cache from full path to existing directories/files.
  52. ///
  53. llvm::StringMap<DirectoryEntry> UniqueDirs;
  54. public:
  55. DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) {
  56. std::string FullPath(GetFullPath(Name));
  57. return UniqueDirs.GetOrCreateValue(
  58. FullPath.c_str(),
  59. FullPath.c_str() + FullPath.size()
  60. ).getValue();
  61. }
  62. size_t size() { return UniqueDirs.size(); }
  63. };
  64. class FileManager::UniqueFileContainer {
  65. /// UniqueFiles - Cache from full path to existing directories/files.
  66. ///
  67. llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;
  68. public:
  69. FileEntry &getFile(const char *Name, struct stat &StatBuf) {
  70. std::string FullPath(GetFullPath(Name));
  71. return UniqueFiles.GetOrCreateValue(
  72. FullPath.c_str(),
  73. FullPath.c_str() + FullPath.size()
  74. ).getValue();
  75. }
  76. size_t size() { return UniqueFiles.size(); }
  77. };
  78. //===----------------------------------------------------------------------===//
  79. // Unix-like Systems.
  80. //===----------------------------------------------------------------------===//
  81. #else
  82. #define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/')
  83. class FileManager::UniqueDirContainer {
  84. /// UniqueDirs - Cache from ID's to existing directories/files.
  85. ///
  86. std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;
  87. public:
  88. DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) {
  89. return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
  90. }
  91. size_t size() { return UniqueDirs.size(); }
  92. };
  93. class FileManager::UniqueFileContainer {
  94. /// UniqueFiles - Cache from ID's to existing directories/files.
  95. ///
  96. std::set<FileEntry> UniqueFiles;
  97. public:
  98. FileEntry &getFile(const char *Name, struct stat &StatBuf) {
  99. return
  100. const_cast<FileEntry&>(
  101. *UniqueFiles.insert(FileEntry(StatBuf.st_dev,
  102. StatBuf.st_ino,
  103. StatBuf.st_mode)).first);
  104. }
  105. size_t size() { return UniqueFiles.size(); }
  106. };
  107. #endif
  108. //===----------------------------------------------------------------------===//
  109. // Common logic.
  110. //===----------------------------------------------------------------------===//
  111. FileManager::FileManager()
  112. : UniqueDirs(*new UniqueDirContainer),
  113. UniqueFiles(*new UniqueFileContainer),
  114. DirEntries(64), FileEntries(64), NextFileUID(0) {
  115. NumDirLookups = NumFileLookups = 0;
  116. NumDirCacheMisses = NumFileCacheMisses = 0;
  117. }
  118. FileManager::~FileManager() {
  119. delete &UniqueDirs;
  120. delete &UniqueFiles;
  121. for (llvm::SmallVectorImpl<FileEntry *>::iterator
  122. V = VirtualFileEntries.begin(),
  123. VEnd = VirtualFileEntries.end();
  124. V != VEnd;
  125. ++V)
  126. delete *V;
  127. }
  128. void FileManager::addStatCache(StatSysCallCache *statCache, bool AtBeginning) {
  129. assert(statCache && "No stat cache provided?");
  130. if (AtBeginning || StatCache.get() == 0) {
  131. statCache->setNextStatCache(StatCache.take());
  132. StatCache.reset(statCache);
  133. return;
  134. }
  135. StatSysCallCache *LastCache = StatCache.get();
  136. while (LastCache->getNextStatCache())
  137. LastCache = LastCache->getNextStatCache();
  138. LastCache->setNextStatCache(statCache);
  139. }
  140. void FileManager::removeStatCache(StatSysCallCache *statCache) {
  141. if (!statCache)
  142. return;
  143. if (StatCache.get() == statCache) {
  144. // This is the first stat cache.
  145. StatCache.reset(StatCache->takeNextStatCache());
  146. return;
  147. }
  148. // Find the stat cache in the list.
  149. StatSysCallCache *PrevCache = StatCache.get();
  150. while (PrevCache && PrevCache->getNextStatCache() != statCache)
  151. PrevCache = PrevCache->getNextStatCache();
  152. if (PrevCache)
  153. PrevCache->setNextStatCache(statCache->getNextStatCache());
  154. else
  155. assert(false && "Stat cache not found for removal");
  156. }
  157. /// \brief Retrieve the directory that the given file name resides in.
  158. static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
  159. const char *NameStart,
  160. const char *NameEnd) {
  161. // Figure out what directory it is in. If the string contains a / in it,
  162. // strip off everything after it.
  163. // FIXME: this logic should be in sys::Path.
  164. const char *SlashPos = NameEnd-1;
  165. while (SlashPos >= NameStart && !IS_DIR_SEPARATOR_CHAR(SlashPos[0]))
  166. --SlashPos;
  167. // Ignore duplicate //'s.
  168. while (SlashPos > NameStart && IS_DIR_SEPARATOR_CHAR(SlashPos[-1]))
  169. --SlashPos;
  170. if (SlashPos < NameStart) {
  171. // Use the current directory if file has no path component.
  172. const char *Name = ".";
  173. return FileMgr.getDirectory(Name, Name+1);
  174. } else if (SlashPos == NameEnd-1)
  175. return 0; // If filename ends with a /, it's a directory.
  176. else
  177. return FileMgr.getDirectory(NameStart, SlashPos);
  178. }
  179. /// getDirectory - Lookup, cache, and verify the specified directory. This
  180. /// returns null if the directory doesn't exist.
  181. ///
  182. const DirectoryEntry *FileManager::getDirectory(const char *NameStart,
  183. const char *NameEnd) {
  184. // stat doesn't like trailing separators (at least on Windows).
  185. if (((NameEnd - NameStart) > 1) &&
  186. ((*(NameEnd - 1) == '/') || (*(NameEnd - 1) == '\\')))
  187. NameEnd--;
  188. ++NumDirLookups;
  189. llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
  190. DirEntries.GetOrCreateValue(NameStart, NameEnd);
  191. // See if there is already an entry in the map.
  192. if (NamedDirEnt.getValue())
  193. return NamedDirEnt.getValue() == NON_EXISTENT_DIR
  194. ? 0 : NamedDirEnt.getValue();
  195. ++NumDirCacheMisses;
  196. // By default, initialize it to invalid.
  197. NamedDirEnt.setValue(NON_EXISTENT_DIR);
  198. // Get the null-terminated directory name as stored as the key of the
  199. // DirEntries map.
  200. const char *InterndDirName = NamedDirEnt.getKeyData();
  201. // Check to see if the directory exists.
  202. struct stat StatBuf;
  203. if (stat_cached(InterndDirName, &StatBuf) || // Error stat'ing.
  204. !S_ISDIR(StatBuf.st_mode)) // Not a directory?
  205. return 0;
  206. // It exists. See if we have already opened a directory with the same inode.
  207. // This occurs when one dir is symlinked to another, for example.
  208. DirectoryEntry &UDE = UniqueDirs.getDirectory(InterndDirName, StatBuf);
  209. NamedDirEnt.setValue(&UDE);
  210. if (UDE.getName()) // Already have an entry with this inode, return it.
  211. return &UDE;
  212. // Otherwise, we don't have this directory yet, add it. We use the string
  213. // key from the DirEntries map as the string.
  214. UDE.Name = InterndDirName;
  215. return &UDE;
  216. }
  217. /// NON_EXISTENT_FILE - A special value distinct from null that is used to
  218. /// represent a filename that doesn't exist on the disk.
  219. #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
  220. /// getFile - Lookup, cache, and verify the specified file. This returns null
  221. /// if the file doesn't exist.
  222. ///
  223. const FileEntry *FileManager::getFile(const char *NameStart,
  224. const char *NameEnd) {
  225. ++NumFileLookups;
  226. // See if there is already an entry in the map.
  227. llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
  228. FileEntries.GetOrCreateValue(NameStart, NameEnd);
  229. // See if there is already an entry in the map.
  230. if (NamedFileEnt.getValue())
  231. return NamedFileEnt.getValue() == NON_EXISTENT_FILE
  232. ? 0 : NamedFileEnt.getValue();
  233. ++NumFileCacheMisses;
  234. // By default, initialize it to invalid.
  235. NamedFileEnt.setValue(NON_EXISTENT_FILE);
  236. // Get the null-terminated file name as stored as the key of the
  237. // FileEntries map.
  238. const char *InterndFileName = NamedFileEnt.getKeyData();
  239. const DirectoryEntry *DirInfo
  240. = getDirectoryFromFile(*this, NameStart, NameEnd);
  241. if (DirInfo == 0) // Directory doesn't exist, file can't exist.
  242. return 0;
  243. // FIXME: Use the directory info to prune this, before doing the stat syscall.
  244. // FIXME: This will reduce the # syscalls.
  245. // Nope, there isn't. Check to see if the file exists.
  246. struct stat StatBuf;
  247. //llvm::errs() << "STATING: " << Filename;
  248. if (stat_cached(InterndFileName, &StatBuf) || // Error stat'ing.
  249. S_ISDIR(StatBuf.st_mode)) { // A directory?
  250. // If this file doesn't exist, we leave a null in FileEntries for this path.
  251. //llvm::errs() << ": Not existing\n";
  252. return 0;
  253. }
  254. //llvm::errs() << ": exists\n";
  255. // It exists. See if we have already opened a file with the same inode.
  256. // This occurs when one dir is symlinked to another, for example.
  257. FileEntry &UFE = UniqueFiles.getFile(InterndFileName, StatBuf);
  258. NamedFileEnt.setValue(&UFE);
  259. if (UFE.getName()) // Already have an entry with this inode, return it.
  260. return &UFE;
  261. // Otherwise, we don't have this directory yet, add it.
  262. // FIXME: Change the name to be a char* that points back to the 'FileEntries'
  263. // key.
  264. UFE.Name = InterndFileName;
  265. UFE.Size = StatBuf.st_size;
  266. UFE.ModTime = StatBuf.st_mtime;
  267. UFE.Dir = DirInfo;
  268. UFE.UID = NextFileUID++;
  269. return &UFE;
  270. }
  271. const FileEntry *
  272. FileManager::getVirtualFile(llvm::StringRef Filename, off_t Size,
  273. time_t ModificationTime) {
  274. const char *NameStart = Filename.begin(), *NameEnd = Filename.end();
  275. ++NumFileLookups;
  276. // See if there is already an entry in the map.
  277. llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
  278. FileEntries.GetOrCreateValue(NameStart, NameEnd);
  279. // See if there is already an entry in the map.
  280. if (NamedFileEnt.getValue())
  281. return NamedFileEnt.getValue() == NON_EXISTENT_FILE
  282. ? 0 : NamedFileEnt.getValue();
  283. ++NumFileCacheMisses;
  284. // By default, initialize it to invalid.
  285. NamedFileEnt.setValue(NON_EXISTENT_FILE);
  286. const DirectoryEntry *DirInfo
  287. = getDirectoryFromFile(*this, NameStart, NameEnd);
  288. if (DirInfo == 0) // Directory doesn't exist, file can't exist.
  289. return 0;
  290. FileEntry *UFE = new FileEntry();
  291. VirtualFileEntries.push_back(UFE);
  292. NamedFileEnt.setValue(UFE);
  293. UFE->Name = NamedFileEnt.getKeyData();
  294. UFE->Size = Size;
  295. UFE->ModTime = ModificationTime;
  296. UFE->Dir = DirInfo;
  297. UFE->UID = NextFileUID++;
  298. return UFE;
  299. }
  300. void FileManager::PrintStats() const {
  301. llvm::errs() << "\n*** File Manager Stats:\n";
  302. llvm::errs() << UniqueFiles.size() << " files found, "
  303. << UniqueDirs.size() << " dirs found.\n";
  304. llvm::errs() << NumDirLookups << " dir lookups, "
  305. << NumDirCacheMisses << " dir cache misses.\n";
  306. llvm::errs() << NumFileLookups << " file lookups, "
  307. << NumFileCacheMisses << " file cache misses.\n";
  308. //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
  309. }
  310. int MemorizeStatCalls::stat(const char *path, struct stat *buf) {
  311. int result = StatSysCallCache::stat(path, buf);
  312. // Do not cache failed stats, it is easy to construct common inconsistent
  313. // situations if we do, and they are not important for PCH performance (which
  314. // currently only needs the stats to construct the initial FileManager
  315. // entries).
  316. if (result != 0)
  317. return result;
  318. // Cache file 'stat' results and directories with absolutely paths.
  319. if (!S_ISDIR(buf->st_mode) || llvm::sys::Path(path).isAbsolute())
  320. StatCalls[path] = StatResult(result, *buf);
  321. return result;
  322. }