FileManager.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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()
  117. : UniqueDirs(*new UniqueDirContainer),
  118. UniqueFiles(*new UniqueFileContainer),
  119. DirEntries(64), FileEntries(64), NextFileUID(0) {
  120. NumDirLookups = NumFileLookups = 0;
  121. NumDirCacheMisses = NumFileCacheMisses = 0;
  122. }
  123. FileManager::~FileManager() {
  124. delete &UniqueDirs;
  125. delete &UniqueFiles;
  126. for (llvm::SmallVectorImpl<FileEntry *>::iterator
  127. V = VirtualFileEntries.begin(),
  128. VEnd = VirtualFileEntries.end();
  129. V != VEnd;
  130. ++V)
  131. delete *V;
  132. }
  133. void FileManager::addStatCache(StatSysCallCache *statCache, bool AtBeginning) {
  134. assert(statCache && "No stat cache provided?");
  135. if (AtBeginning || StatCache.get() == 0) {
  136. statCache->setNextStatCache(StatCache.take());
  137. StatCache.reset(statCache);
  138. return;
  139. }
  140. StatSysCallCache *LastCache = StatCache.get();
  141. while (LastCache->getNextStatCache())
  142. LastCache = LastCache->getNextStatCache();
  143. LastCache->setNextStatCache(statCache);
  144. }
  145. void FileManager::removeStatCache(StatSysCallCache *statCache) {
  146. if (!statCache)
  147. return;
  148. if (StatCache.get() == statCache) {
  149. // This is the first stat cache.
  150. StatCache.reset(StatCache->takeNextStatCache());
  151. return;
  152. }
  153. // Find the stat cache in the list.
  154. StatSysCallCache *PrevCache = StatCache.get();
  155. while (PrevCache && PrevCache->getNextStatCache() != statCache)
  156. PrevCache = PrevCache->getNextStatCache();
  157. if (PrevCache)
  158. PrevCache->setNextStatCache(statCache->getNextStatCache());
  159. else
  160. assert(false && "Stat cache not found for removal");
  161. }
  162. /// \brief Retrieve the directory that the given file name resides in.
  163. static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
  164. const char *NameStart,
  165. const char *NameEnd,
  166. const FileSystemOptions &FileSystemOpts) {
  167. // Figure out what directory it is in. If the string contains a / in it,
  168. // strip off everything after it.
  169. // FIXME: this logic should be in sys::Path.
  170. const char *SlashPos = NameEnd-1;
  171. while (SlashPos >= NameStart && !IS_DIR_SEPARATOR_CHAR(SlashPos[0]))
  172. --SlashPos;
  173. // Ignore duplicate //'s.
  174. while (SlashPos > NameStart && IS_DIR_SEPARATOR_CHAR(SlashPos[-1]))
  175. --SlashPos;
  176. if (SlashPos < NameStart) {
  177. // Use the current directory if file has no path component.
  178. const char *Name = ".";
  179. return FileMgr.getDirectory(Name, Name+1, FileSystemOpts);
  180. } else if (SlashPos == NameEnd-1)
  181. return 0; // If filename ends with a /, it's a directory.
  182. else
  183. return FileMgr.getDirectory(NameStart, SlashPos, FileSystemOpts);
  184. }
  185. /// getDirectory - Lookup, cache, and verify the specified directory. This
  186. /// returns null if the directory doesn't exist.
  187. ///
  188. const DirectoryEntry *FileManager::getDirectory(const char *NameStart,
  189. const char *NameEnd,
  190. const FileSystemOptions &FileSystemOpts) {
  191. // stat doesn't like trailing separators (at least on Windows).
  192. if (((NameEnd - NameStart) > 1) &&
  193. ((*(NameEnd - 1) == '/') || (*(NameEnd - 1) == '\\')))
  194. NameEnd--;
  195. ++NumDirLookups;
  196. llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
  197. DirEntries.GetOrCreateValue(NameStart, NameEnd);
  198. // See if there is already an entry in the map.
  199. if (NamedDirEnt.getValue())
  200. return NamedDirEnt.getValue() == NON_EXISTENT_DIR
  201. ? 0 : NamedDirEnt.getValue();
  202. ++NumDirCacheMisses;
  203. // By default, initialize it to invalid.
  204. NamedDirEnt.setValue(NON_EXISTENT_DIR);
  205. // Get the null-terminated directory name as stored as the key of the
  206. // DirEntries map.
  207. const char *InterndDirName = NamedDirEnt.getKeyData();
  208. // Check to see if the directory exists.
  209. struct stat StatBuf;
  210. if (stat_cached(InterndDirName, &StatBuf, FileSystemOpts) || // Error stat'ing.
  211. !S_ISDIR(StatBuf.st_mode)) // Not a directory?
  212. return 0;
  213. // It exists. See if we have already opened a directory with the same inode.
  214. // This occurs when one dir is symlinked to another, for example.
  215. DirectoryEntry &UDE = UniqueDirs.getDirectory(InterndDirName, StatBuf);
  216. NamedDirEnt.setValue(&UDE);
  217. if (UDE.getName()) // Already have an entry with this inode, return it.
  218. return &UDE;
  219. // Otherwise, we don't have this directory yet, add it. We use the string
  220. // key from the DirEntries map as the string.
  221. UDE.Name = InterndDirName;
  222. return &UDE;
  223. }
  224. /// NON_EXISTENT_FILE - A special value distinct from null that is used to
  225. /// represent a filename that doesn't exist on the disk.
  226. #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
  227. /// getFile - Lookup, cache, and verify the specified file. This returns null
  228. /// if the file doesn't exist.
  229. ///
  230. const FileEntry *FileManager::getFile(const char *NameStart,
  231. const char *NameEnd,
  232. const FileSystemOptions &FileSystemOpts) {
  233. ++NumFileLookups;
  234. // See if there is already an entry in the map.
  235. llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
  236. FileEntries.GetOrCreateValue(NameStart, NameEnd);
  237. // See if there is already an entry in the map.
  238. if (NamedFileEnt.getValue())
  239. return NamedFileEnt.getValue() == NON_EXISTENT_FILE
  240. ? 0 : NamedFileEnt.getValue();
  241. ++NumFileCacheMisses;
  242. // By default, initialize it to invalid.
  243. NamedFileEnt.setValue(NON_EXISTENT_FILE);
  244. // Get the null-terminated file name as stored as the key of the
  245. // FileEntries map.
  246. const char *InterndFileName = NamedFileEnt.getKeyData();
  247. const DirectoryEntry *DirInfo
  248. = getDirectoryFromFile(*this, NameStart, NameEnd, FileSystemOpts);
  249. if (DirInfo == 0) // Directory doesn't exist, file can't exist.
  250. return 0;
  251. // FIXME: Use the directory info to prune this, before doing the stat syscall.
  252. // FIXME: This will reduce the # syscalls.
  253. // Nope, there isn't. Check to see if the file exists.
  254. struct stat StatBuf;
  255. //llvm::errs() << "STATING: " << Filename;
  256. if (stat_cached(InterndFileName, &StatBuf, FileSystemOpts) || // Error stat'ing.
  257. S_ISDIR(StatBuf.st_mode)) { // A directory?
  258. // If this file doesn't exist, we leave a null in FileEntries for this path.
  259. //llvm::errs() << ": Not existing\n";
  260. return 0;
  261. }
  262. //llvm::errs() << ": exists\n";
  263. // It exists. See if we have already opened a file with the same inode.
  264. // This occurs when one dir is symlinked to another, for example.
  265. FileEntry &UFE = UniqueFiles.getFile(InterndFileName, StatBuf);
  266. NamedFileEnt.setValue(&UFE);
  267. if (UFE.getName()) // Already have an entry with this inode, return it.
  268. return &UFE;
  269. // Otherwise, we don't have this directory yet, add it.
  270. // FIXME: Change the name to be a char* that points back to the 'FileEntries'
  271. // key.
  272. UFE.Name = InterndFileName;
  273. UFE.Size = StatBuf.st_size;
  274. UFE.ModTime = StatBuf.st_mtime;
  275. UFE.Dir = DirInfo;
  276. UFE.UID = NextFileUID++;
  277. return &UFE;
  278. }
  279. const FileEntry *
  280. FileManager::getVirtualFile(llvm::StringRef Filename, off_t Size,
  281. time_t ModificationTime,
  282. const FileSystemOptions &FileSystemOpts) {
  283. const char *NameStart = Filename.begin(), *NameEnd = Filename.end();
  284. ++NumFileLookups;
  285. // See if there is already an entry in the map.
  286. llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
  287. FileEntries.GetOrCreateValue(NameStart, NameEnd);
  288. // See if there is already an entry in the map.
  289. if (NamedFileEnt.getValue())
  290. return NamedFileEnt.getValue() == NON_EXISTENT_FILE
  291. ? 0 : NamedFileEnt.getValue();
  292. ++NumFileCacheMisses;
  293. // By default, initialize it to invalid.
  294. NamedFileEnt.setValue(NON_EXISTENT_FILE);
  295. const DirectoryEntry *DirInfo
  296. = getDirectoryFromFile(*this, NameStart, NameEnd, FileSystemOpts);
  297. if (DirInfo == 0) // Directory doesn't exist, file can't exist.
  298. return 0;
  299. FileEntry *UFE = new FileEntry();
  300. VirtualFileEntries.push_back(UFE);
  301. NamedFileEnt.setValue(UFE);
  302. UFE->Name = NamedFileEnt.getKeyData();
  303. UFE->Size = Size;
  304. UFE->ModTime = ModificationTime;
  305. UFE->Dir = DirInfo;
  306. UFE->UID = NextFileUID++;
  307. // If this virtual file resolves to a file, also map that file to the
  308. // newly-created file entry.
  309. const char *InterndFileName = NamedFileEnt.getKeyData();
  310. struct stat StatBuf;
  311. if (!stat_cached(InterndFileName, &StatBuf, FileSystemOpts) &&
  312. !S_ISDIR(StatBuf.st_mode)) {
  313. llvm::sys::Path FilePath(InterndFileName);
  314. FilePath.makeAbsolute();
  315. FileEntries[FilePath.str()] = UFE;
  316. }
  317. return UFE;
  318. }
  319. llvm::MemoryBuffer *FileManager::getBufferForFile(const char *FilenameStart,
  320. const char *FilenameEnd,
  321. const FileSystemOptions &FileSystemOpts,
  322. std::string *ErrorStr,
  323. int64_t FileSize,
  324. struct stat *FileInfo) {
  325. llvm::sys::Path FilePath(llvm::StringRef(FilenameStart,
  326. FilenameEnd-FilenameStart));
  327. FixupRelativePath(FilePath, FileSystemOpts);
  328. return llvm::MemoryBuffer::getFile(FilePath.c_str(), ErrorStr,
  329. FileSize, FileInfo);
  330. }
  331. int FileManager::stat_cached(const char* path, struct stat* buf,
  332. const FileSystemOptions &FileSystemOpts) {
  333. llvm::sys::Path FilePath(path);
  334. FixupRelativePath(FilePath, FileSystemOpts);
  335. return StatCache.get() ? StatCache->stat(FilePath.c_str(), buf)
  336. : stat(FilePath.c_str(), buf);
  337. }
  338. void FileManager::FixupRelativePath(llvm::sys::Path &path,
  339. const FileSystemOptions &FSOpts) {
  340. if (!FSOpts.WorkingDir.empty() && !path.isAbsolute()) {
  341. llvm::sys::Path NewPath(FSOpts.WorkingDir);
  342. NewPath.appendComponent(path.str());
  343. path = NewPath;
  344. }
  345. }
  346. void FileManager::PrintStats() const {
  347. llvm::errs() << "\n*** File Manager Stats:\n";
  348. llvm::errs() << UniqueFiles.size() << " files found, "
  349. << UniqueDirs.size() << " dirs found.\n";
  350. llvm::errs() << NumDirLookups << " dir lookups, "
  351. << NumDirCacheMisses << " dir cache misses.\n";
  352. llvm::errs() << NumFileLookups << " file lookups, "
  353. << NumFileCacheMisses << " file cache misses.\n";
  354. //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
  355. }
  356. int MemorizeStatCalls::stat(const char *path, struct stat *buf) {
  357. int result = StatSysCallCache::stat(path, buf);
  358. // Do not cache failed stats, it is easy to construct common inconsistent
  359. // situations if we do, and they are not important for PCH performance (which
  360. // currently only needs the stats to construct the initial FileManager
  361. // entries).
  362. if (result != 0)
  363. return result;
  364. // Cache file 'stat' results and directories with absolutely paths.
  365. if (!S_ISDIR(buf->st_mode) || llvm::sys::Path(path).isAbsolute())
  366. StatCalls[path] = StatResult(result, *buf);
  367. return result;
  368. }