FileManager.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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/FileSystemStatCache.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. /// 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. /// NON_EXISTENT_FILE - A special value distinct from null that is used to
  37. /// represent a filename that doesn't exist on the disk.
  38. #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
  39. FileEntry::~FileEntry() {
  40. // If this FileEntry owns an open file descriptor that never got used, close
  41. // it.
  42. if (FD != -1) ::close(FD);
  43. }
  44. //===----------------------------------------------------------------------===//
  45. // Windows.
  46. //===----------------------------------------------------------------------===//
  47. #ifdef LLVM_ON_WIN32
  48. #define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/' || (x) == '\\')
  49. namespace {
  50. static std::string GetFullPath(const char *relPath) {
  51. char *absPathStrPtr = _fullpath(NULL, relPath, 0);
  52. assert(absPathStrPtr && "_fullpath() returned NULL!");
  53. std::string absPath(absPathStrPtr);
  54. free(absPathStrPtr);
  55. return absPath;
  56. }
  57. }
  58. class FileManager::UniqueDirContainer {
  59. /// UniqueDirs - Cache from full path to existing directories/files.
  60. ///
  61. llvm::StringMap<DirectoryEntry> UniqueDirs;
  62. public:
  63. DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) {
  64. std::string FullPath(GetFullPath(Name));
  65. return UniqueDirs.GetOrCreateValue(FullPath).getValue();
  66. }
  67. size_t size() const { return UniqueDirs.size(); }
  68. };
  69. class FileManager::UniqueFileContainer {
  70. /// UniqueFiles - Cache from full path to existing directories/files.
  71. ///
  72. llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;
  73. public:
  74. FileEntry &getFile(const char *Name, struct stat &StatBuf) {
  75. std::string FullPath(GetFullPath(Name));
  76. // LowercaseString because Windows filesystem is case insensitive.
  77. FullPath = llvm::LowercaseString(FullPath);
  78. return UniqueFiles.GetOrCreateValue(FullPath).getValue();
  79. }
  80. size_t size() const { return UniqueFiles.size(); }
  81. };
  82. //===----------------------------------------------------------------------===//
  83. // Unix-like Systems.
  84. //===----------------------------------------------------------------------===//
  85. #else
  86. #define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/')
  87. class FileManager::UniqueDirContainer {
  88. /// UniqueDirs - Cache from ID's to existing directories/files.
  89. std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;
  90. public:
  91. DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) {
  92. return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
  93. }
  94. size_t size() const { return UniqueDirs.size(); }
  95. };
  96. class FileManager::UniqueFileContainer {
  97. /// UniqueFiles - Cache from ID's to existing directories/files.
  98. std::set<FileEntry> UniqueFiles;
  99. public:
  100. FileEntry &getFile(const char *Name, struct stat &StatBuf) {
  101. return
  102. const_cast<FileEntry&>(
  103. *UniqueFiles.insert(FileEntry(StatBuf.st_dev,
  104. StatBuf.st_ino,
  105. StatBuf.st_mode)).first);
  106. }
  107. size_t size() const { return UniqueFiles.size(); }
  108. };
  109. #endif
  110. //===----------------------------------------------------------------------===//
  111. // Common logic.
  112. //===----------------------------------------------------------------------===//
  113. FileManager::FileManager(const FileSystemOptions &FSO)
  114. : FileSystemOpts(FSO),
  115. UniqueDirs(*new UniqueDirContainer()),
  116. UniqueFiles(*new UniqueFileContainer()),
  117. DirEntries(64), FileEntries(64), NextFileUID(0) {
  118. NumDirLookups = NumFileLookups = 0;
  119. NumDirCacheMisses = NumFileCacheMisses = 0;
  120. }
  121. FileManager::~FileManager() {
  122. delete &UniqueDirs;
  123. delete &UniqueFiles;
  124. for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
  125. delete VirtualFileEntries[i];
  126. }
  127. void FileManager::addStatCache(FileSystemStatCache *statCache,
  128. 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. FileSystemStatCache *LastCache = StatCache.get();
  136. while (LastCache->getNextStatCache())
  137. LastCache = LastCache->getNextStatCache();
  138. LastCache->setNextStatCache(statCache);
  139. }
  140. void FileManager::removeStatCache(FileSystemStatCache *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. FileSystemStatCache *PrevCache = StatCache.get();
  150. while (PrevCache && PrevCache->getNextStatCache() != statCache)
  151. PrevCache = PrevCache->getNextStatCache();
  152. assert(PrevCache && "Stat cache not found for removal");
  153. PrevCache->setNextStatCache(statCache->getNextStatCache());
  154. }
  155. /// \brief Retrieve the directory that the given file name resides in.
  156. static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
  157. llvm::StringRef Filename) {
  158. // Figure out what directory it is in. If the string contains a / in it,
  159. // strip off everything after it.
  160. // FIXME: this logic should be in sys::Path.
  161. size_t SlashPos = Filename.size();
  162. while (SlashPos != 0 && !IS_DIR_SEPARATOR_CHAR(Filename[SlashPos-1]))
  163. --SlashPos;
  164. // Use the current directory if file has no path component.
  165. if (SlashPos == 0)
  166. return FileMgr.getDirectory(".");
  167. if (SlashPos == Filename.size()-1)
  168. return 0; // If filename ends with a /, it's a directory.
  169. // Ignore repeated //'s.
  170. while (SlashPos != 0 && IS_DIR_SEPARATOR_CHAR(Filename[SlashPos-1]))
  171. --SlashPos;
  172. return FileMgr.getDirectory(Filename.substr(0, SlashPos));
  173. }
  174. /// getDirectory - Lookup, cache, and verify the specified directory. This
  175. /// returns null if the directory doesn't exist.
  176. ///
  177. const DirectoryEntry *FileManager::getDirectory(llvm::StringRef Filename) {
  178. // stat doesn't like trailing separators (at least on Windows).
  179. if (Filename.size() > 1 && IS_DIR_SEPARATOR_CHAR(Filename.back()))
  180. Filename = Filename.substr(0, Filename.size()-1);
  181. ++NumDirLookups;
  182. llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
  183. DirEntries.GetOrCreateValue(Filename);
  184. // See if there is already an entry in the map.
  185. if (NamedDirEnt.getValue())
  186. return NamedDirEnt.getValue() == NON_EXISTENT_DIR
  187. ? 0 : NamedDirEnt.getValue();
  188. ++NumDirCacheMisses;
  189. // By default, initialize it to invalid.
  190. NamedDirEnt.setValue(NON_EXISTENT_DIR);
  191. // Get the null-terminated directory name as stored as the key of the
  192. // DirEntries map.
  193. const char *InterndDirName = NamedDirEnt.getKeyData();
  194. // Check to see if the directory exists.
  195. struct stat StatBuf;
  196. if (getStatValue(InterndDirName, StatBuf, 0/*directory lookup*/))
  197. return 0;
  198. // It exists. See if we have already opened a directory with the same inode.
  199. // This occurs when one dir is symlinked to another, for example.
  200. DirectoryEntry &UDE = UniqueDirs.getDirectory(InterndDirName, StatBuf);
  201. NamedDirEnt.setValue(&UDE);
  202. if (UDE.getName()) // Already have an entry with this inode, return it.
  203. return &UDE;
  204. // Otherwise, we don't have this directory yet, add it. We use the string
  205. // key from the DirEntries map as the string.
  206. UDE.Name = InterndDirName;
  207. return &UDE;
  208. }
  209. /// getFile - Lookup, cache, and verify the specified file. This returns null
  210. /// if the file doesn't exist.
  211. ///
  212. const FileEntry *FileManager::getFile(llvm::StringRef Filename) {
  213. ++NumFileLookups;
  214. // See if there is already an entry in the map.
  215. llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
  216. FileEntries.GetOrCreateValue(Filename);
  217. // See if there is already an entry in the map.
  218. if (NamedFileEnt.getValue())
  219. return NamedFileEnt.getValue() == NON_EXISTENT_FILE
  220. ? 0 : NamedFileEnt.getValue();
  221. ++NumFileCacheMisses;
  222. // By default, initialize it to invalid.
  223. NamedFileEnt.setValue(NON_EXISTENT_FILE);
  224. // Get the null-terminated file name as stored as the key of the
  225. // FileEntries map.
  226. const char *InterndFileName = NamedFileEnt.getKeyData();
  227. // Look up the directory for the file. When looking up something like
  228. // sys/foo.h we'll discover all of the search directories that have a 'sys'
  229. // subdirectory. This will let us avoid having to waste time on known-to-fail
  230. // searches when we go to find sys/bar.h, because all the search directories
  231. // without a 'sys' subdir will get a cached failure result.
  232. const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename);
  233. if (DirInfo == 0) // Directory doesn't exist, file can't exist.
  234. return 0;
  235. // FIXME: Use the directory info to prune this, before doing the stat syscall.
  236. // FIXME: This will reduce the # syscalls.
  237. // Nope, there isn't. Check to see if the file exists.
  238. int FileDescriptor = -1;
  239. struct stat StatBuf;
  240. if (getStatValue(InterndFileName, StatBuf, &FileDescriptor))
  241. return 0;
  242. // It exists. See if we have already opened a file with the same inode.
  243. // This occurs when one dir is symlinked to another, for example.
  244. FileEntry &UFE = UniqueFiles.getFile(InterndFileName, StatBuf);
  245. NamedFileEnt.setValue(&UFE);
  246. if (UFE.getName()) { // Already have an entry with this inode, return it.
  247. // If the stat process opened the file, close it to avoid a FD leak.
  248. if (FileDescriptor != -1)
  249. close(FileDescriptor);
  250. return &UFE;
  251. }
  252. // Otherwise, we don't have this directory yet, add it.
  253. // FIXME: Change the name to be a char* that points back to the 'FileEntries'
  254. // key.
  255. UFE.Name = InterndFileName;
  256. UFE.Size = StatBuf.st_size;
  257. UFE.ModTime = StatBuf.st_mtime;
  258. UFE.Dir = DirInfo;
  259. UFE.UID = NextFileUID++;
  260. UFE.FD = FileDescriptor;
  261. return &UFE;
  262. }
  263. const FileEntry *
  264. FileManager::getVirtualFile(llvm::StringRef Filename, off_t Size,
  265. time_t ModificationTime) {
  266. ++NumFileLookups;
  267. // See if there is already an entry in the map.
  268. llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
  269. FileEntries.GetOrCreateValue(Filename);
  270. // See if there is already an entry in the map.
  271. if (NamedFileEnt.getValue())
  272. return NamedFileEnt.getValue() == NON_EXISTENT_FILE
  273. ? 0 : NamedFileEnt.getValue();
  274. ++NumFileCacheMisses;
  275. // By default, initialize it to invalid.
  276. NamedFileEnt.setValue(NON_EXISTENT_FILE);
  277. const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename);
  278. if (DirInfo == 0) // Directory doesn't exist, file can't exist.
  279. return 0;
  280. FileEntry *UFE = new FileEntry();
  281. VirtualFileEntries.push_back(UFE);
  282. NamedFileEnt.setValue(UFE);
  283. // Get the null-terminated file name as stored as the key of the
  284. // FileEntries map.
  285. const char *InterndFileName = NamedFileEnt.getKeyData();
  286. UFE->Name = InterndFileName;
  287. UFE->Size = Size;
  288. UFE->ModTime = ModificationTime;
  289. UFE->Dir = DirInfo;
  290. UFE->UID = NextFileUID++;
  291. // If this virtual file resolves to a file, also map that file to the
  292. // newly-created file entry.
  293. int FileDescriptor = -1;
  294. struct stat StatBuf;
  295. if (getStatValue(InterndFileName, StatBuf, &FileDescriptor))
  296. return UFE;
  297. UFE->FD = FileDescriptor;
  298. llvm::sys::Path FilePath(UFE->Name);
  299. FilePath.makeAbsolute();
  300. FileEntries[FilePath.str()] = UFE;
  301. return UFE;
  302. }
  303. void FileManager::FixupRelativePath(llvm::sys::Path &path,
  304. const FileSystemOptions &FSOpts) {
  305. if (FSOpts.WorkingDir.empty() || path.isAbsolute()) return;
  306. llvm::sys::Path NewPath(FSOpts.WorkingDir);
  307. NewPath.appendComponent(path.str());
  308. path = NewPath;
  309. }
  310. llvm::MemoryBuffer *FileManager::
  311. getBufferForFile(const FileEntry *Entry, std::string *ErrorStr) {
  312. llvm::StringRef Filename = Entry->getName();
  313. if (FileSystemOpts.WorkingDir.empty())
  314. return llvm::MemoryBuffer::getFile(Filename, ErrorStr, Entry->getSize());
  315. llvm::sys::Path FilePath(Filename);
  316. FixupRelativePath(FilePath, FileSystemOpts);
  317. return llvm::MemoryBuffer::getFile(FilePath.c_str(), ErrorStr,
  318. Entry->getSize());
  319. }
  320. llvm::MemoryBuffer *FileManager::
  321. getBufferForFile(llvm::StringRef Filename, std::string *ErrorStr) {
  322. if (FileSystemOpts.WorkingDir.empty())
  323. return llvm::MemoryBuffer::getFile(Filename, ErrorStr);
  324. llvm::sys::Path FilePath(Filename);
  325. FixupRelativePath(FilePath, FileSystemOpts);
  326. return llvm::MemoryBuffer::getFile(FilePath.c_str(), ErrorStr);
  327. }
  328. /// getStatValue - Get the 'stat' information for the specified path, using the
  329. /// cache to accellerate it if possible. This returns true if the path does not
  330. /// exist or false if it exists.
  331. ///
  332. /// The isForDir member indicates whether this is a directory lookup or not.
  333. /// This will return failure if the lookup isn't the expected kind.
  334. bool FileManager::getStatValue(const char *Path, struct stat &StatBuf,
  335. int *FileDescriptor) {
  336. // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
  337. // absolute!
  338. if (FileSystemOpts.WorkingDir.empty())
  339. return FileSystemStatCache::get(Path, StatBuf, FileDescriptor,
  340. StatCache.get());
  341. llvm::sys::Path FilePath(Path);
  342. FixupRelativePath(FilePath, FileSystemOpts);
  343. return FileSystemStatCache::get(FilePath.c_str(), StatBuf, FileDescriptor,
  344. StatCache.get());
  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. }