FileManager.cpp 15 KB

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