FileManager.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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/Support/Path.h"
  26. #include "llvm/Config/config.h"
  27. #include <map>
  28. #include <set>
  29. #include <string>
  30. // FIXME: This is terrible, we need this for ::close.
  31. #if !defined(_MSC_VER) && !defined(__MINGW32__)
  32. #include <unistd.h>
  33. #include <sys/uio.h>
  34. #else
  35. #include <io.h>
  36. #endif
  37. using namespace clang;
  38. // FIXME: Enhance libsystem to support inode and other fields.
  39. #include <sys/stat.h>
  40. /// NON_EXISTENT_DIR - A special value distinct from null that is used to
  41. /// represent a dir name that doesn't exist on the disk.
  42. #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
  43. /// NON_EXISTENT_FILE - A special value distinct from null that is used to
  44. /// represent a filename that doesn't exist on the disk.
  45. #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
  46. FileEntry::~FileEntry() {
  47. // If this FileEntry owns an open file descriptor that never got used, close
  48. // it.
  49. if (FD != -1) ::close(FD);
  50. }
  51. //===----------------------------------------------------------------------===//
  52. // Windows.
  53. //===----------------------------------------------------------------------===//
  54. #ifdef LLVM_ON_WIN32
  55. #define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/' || (x) == '\\')
  56. namespace {
  57. static std::string GetFullPath(const char *relPath) {
  58. char *absPathStrPtr = _fullpath(NULL, relPath, 0);
  59. assert(absPathStrPtr && "_fullpath() returned NULL!");
  60. std::string absPath(absPathStrPtr);
  61. free(absPathStrPtr);
  62. return absPath;
  63. }
  64. }
  65. class FileManager::UniqueDirContainer {
  66. /// UniqueDirs - Cache from full path to existing directories/files.
  67. ///
  68. llvm::StringMap<DirectoryEntry> UniqueDirs;
  69. public:
  70. DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) {
  71. std::string FullPath(GetFullPath(Name));
  72. return UniqueDirs.GetOrCreateValue(FullPath).getValue();
  73. }
  74. size_t size() const { return UniqueDirs.size(); }
  75. };
  76. class FileManager::UniqueFileContainer {
  77. /// UniqueFiles - Cache from full path to existing directories/files.
  78. ///
  79. llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;
  80. public:
  81. FileEntry &getFile(const char *Name, struct stat &StatBuf) {
  82. std::string FullPath(GetFullPath(Name));
  83. // LowercaseString because Windows filesystem is case insensitive.
  84. FullPath = llvm::LowercaseString(FullPath);
  85. return UniqueFiles.GetOrCreateValue(FullPath).getValue();
  86. }
  87. size_t size() const { return UniqueFiles.size(); }
  88. };
  89. //===----------------------------------------------------------------------===//
  90. // Unix-like Systems.
  91. //===----------------------------------------------------------------------===//
  92. #else
  93. #define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/')
  94. class FileManager::UniqueDirContainer {
  95. /// UniqueDirs - Cache from ID's to existing directories/files.
  96. std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;
  97. public:
  98. DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) {
  99. return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
  100. }
  101. size_t size() const { return UniqueDirs.size(); }
  102. };
  103. class FileManager::UniqueFileContainer {
  104. /// UniqueFiles - Cache from ID's to existing directories/files.
  105. std::set<FileEntry> UniqueFiles;
  106. public:
  107. FileEntry &getFile(const char *Name, struct stat &StatBuf) {
  108. return
  109. const_cast<FileEntry&>(
  110. *UniqueFiles.insert(FileEntry(StatBuf.st_dev,
  111. StatBuf.st_ino,
  112. StatBuf.st_mode)).first);
  113. }
  114. size_t size() const { return UniqueFiles.size(); }
  115. };
  116. #endif
  117. //===----------------------------------------------------------------------===//
  118. // Common logic.
  119. //===----------------------------------------------------------------------===//
  120. FileManager::FileManager(const FileSystemOptions &FSO)
  121. : FileSystemOpts(FSO),
  122. UniqueDirs(*new UniqueDirContainer()),
  123. UniqueFiles(*new UniqueFileContainer()),
  124. DirEntries(64), FileEntries(64), NextFileUID(0) {
  125. NumDirLookups = NumFileLookups = 0;
  126. NumDirCacheMisses = NumFileCacheMisses = 0;
  127. }
  128. FileManager::~FileManager() {
  129. delete &UniqueDirs;
  130. delete &UniqueFiles;
  131. for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
  132. delete VirtualFileEntries[i];
  133. }
  134. void FileManager::addStatCache(FileSystemStatCache *statCache,
  135. bool AtBeginning) {
  136. assert(statCache && "No stat cache provided?");
  137. if (AtBeginning || StatCache.get() == 0) {
  138. statCache->setNextStatCache(StatCache.take());
  139. StatCache.reset(statCache);
  140. return;
  141. }
  142. FileSystemStatCache *LastCache = StatCache.get();
  143. while (LastCache->getNextStatCache())
  144. LastCache = LastCache->getNextStatCache();
  145. LastCache->setNextStatCache(statCache);
  146. }
  147. void FileManager::removeStatCache(FileSystemStatCache *statCache) {
  148. if (!statCache)
  149. return;
  150. if (StatCache.get() == statCache) {
  151. // This is the first stat cache.
  152. StatCache.reset(StatCache->takeNextStatCache());
  153. return;
  154. }
  155. // Find the stat cache in the list.
  156. FileSystemStatCache *PrevCache = StatCache.get();
  157. while (PrevCache && PrevCache->getNextStatCache() != statCache)
  158. PrevCache = PrevCache->getNextStatCache();
  159. assert(PrevCache && "Stat cache not found for removal");
  160. PrevCache->setNextStatCache(statCache->getNextStatCache());
  161. }
  162. /// \brief Retrieve the directory that the given file name resides in.
  163. static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
  164. llvm::StringRef Filename) {
  165. // Figure out what directory it is in. If the string contains a / in it,
  166. // strip off everything after it.
  167. // FIXME: this logic should be in sys::Path.
  168. size_t SlashPos = Filename.size();
  169. while (SlashPos != 0 && !IS_DIR_SEPARATOR_CHAR(Filename[SlashPos-1]))
  170. --SlashPos;
  171. // Use the current directory if file has no path component.
  172. if (SlashPos == 0)
  173. return FileMgr.getDirectory(".");
  174. if (SlashPos == Filename.size()-1)
  175. return 0; // If filename ends with a /, it's a directory.
  176. // Ignore repeated //'s.
  177. while (SlashPos != 0 && IS_DIR_SEPARATOR_CHAR(Filename[SlashPos-1]))
  178. --SlashPos;
  179. return FileMgr.getDirectory(Filename.substr(0, SlashPos));
  180. }
  181. /// getDirectory - Lookup, cache, and verify the specified directory. This
  182. /// returns null if the directory doesn't exist.
  183. ///
  184. const DirectoryEntry *FileManager::getDirectory(llvm::StringRef Filename) {
  185. // stat doesn't like trailing separators (at least on Windows).
  186. if (Filename.size() > 1 && IS_DIR_SEPARATOR_CHAR(Filename.back()))
  187. Filename = Filename.substr(0, Filename.size()-1);
  188. ++NumDirLookups;
  189. llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
  190. DirEntries.GetOrCreateValue(Filename);
  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 (getStatValue(InterndDirName, StatBuf, 0/*directory lookup*/))
  204. return 0;
  205. // It exists. See if we have already opened a directory with the same inode.
  206. // This occurs when one dir is symlinked to another, for example.
  207. DirectoryEntry &UDE = UniqueDirs.getDirectory(InterndDirName, StatBuf);
  208. NamedDirEnt.setValue(&UDE);
  209. if (UDE.getName()) // Already have an entry with this inode, return it.
  210. return &UDE;
  211. // Otherwise, we don't have this directory yet, add it. We use the string
  212. // key from the DirEntries map as the string.
  213. UDE.Name = InterndDirName;
  214. return &UDE;
  215. }
  216. /// getFile - Lookup, cache, and verify the specified file. This returns null
  217. /// if the file doesn't exist.
  218. ///
  219. const FileEntry *FileManager::getFile(llvm::StringRef Filename) {
  220. ++NumFileLookups;
  221. // See if there is already an entry in the map.
  222. llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
  223. FileEntries.GetOrCreateValue(Filename);
  224. // See if there is already an entry in the map.
  225. if (NamedFileEnt.getValue())
  226. return NamedFileEnt.getValue() == NON_EXISTENT_FILE
  227. ? 0 : NamedFileEnt.getValue();
  228. ++NumFileCacheMisses;
  229. // By default, initialize it to invalid.
  230. NamedFileEnt.setValue(NON_EXISTENT_FILE);
  231. // Get the null-terminated file name as stored as the key of the
  232. // FileEntries map.
  233. const char *InterndFileName = NamedFileEnt.getKeyData();
  234. // Look up the directory for the file. When looking up something like
  235. // sys/foo.h we'll discover all of the search directories that have a 'sys'
  236. // subdirectory. This will let us avoid having to waste time on known-to-fail
  237. // searches when we go to find sys/bar.h, because all the search directories
  238. // without a 'sys' subdir will get a cached failure result.
  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. int FileDescriptor = -1;
  246. struct stat StatBuf;
  247. if (getStatValue(InterndFileName, StatBuf, &FileDescriptor))
  248. return 0;
  249. // It exists. See if we have already opened a file with the same inode.
  250. // This occurs when one dir is symlinked to another, for example.
  251. FileEntry &UFE = UniqueFiles.getFile(InterndFileName, StatBuf);
  252. NamedFileEnt.setValue(&UFE);
  253. if (UFE.getName()) { // Already have an entry with this inode, return it.
  254. // If the stat process opened the file, close it to avoid a FD leak.
  255. if (FileDescriptor != -1)
  256. close(FileDescriptor);
  257. return &UFE;
  258. }
  259. // Otherwise, we don't have this directory yet, add it.
  260. // FIXME: Change the name to be a char* that points back to the 'FileEntries'
  261. // key.
  262. UFE.Name = InterndFileName;
  263. UFE.Size = StatBuf.st_size;
  264. UFE.ModTime = StatBuf.st_mtime;
  265. UFE.Dir = DirInfo;
  266. UFE.UID = NextFileUID++;
  267. UFE.FD = FileDescriptor;
  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. // Get the null-terminated file name as stored as the key of the
  291. // FileEntries map.
  292. const char *InterndFileName = NamedFileEnt.getKeyData();
  293. UFE->Name = InterndFileName;
  294. UFE->Size = Size;
  295. UFE->ModTime = ModificationTime;
  296. UFE->Dir = DirInfo;
  297. UFE->UID = NextFileUID++;
  298. // If this virtual file resolves to a file, also map that file to the
  299. // newly-created file entry.
  300. int FileDescriptor = -1;
  301. struct stat StatBuf;
  302. if (getStatValue(InterndFileName, StatBuf, &FileDescriptor))
  303. return UFE;
  304. UFE->FD = FileDescriptor;
  305. llvm::sys::Path FilePath(UFE->Name);
  306. FilePath.makeAbsolute();
  307. FileEntries[FilePath.str()] = UFE;
  308. return UFE;
  309. }
  310. void FileManager::FixupRelativePath(llvm::sys::Path &path,
  311. const FileSystemOptions &FSOpts) {
  312. if (FSOpts.WorkingDir.empty() || path.isAbsolute()) return;
  313. llvm::sys::Path NewPath(FSOpts.WorkingDir);
  314. NewPath.appendComponent(path.str());
  315. path = NewPath;
  316. }
  317. llvm::MemoryBuffer *FileManager::
  318. getBufferForFile(const FileEntry *Entry, std::string *ErrorStr) {
  319. if (FileSystemOpts.WorkingDir.empty()) {
  320. const char *Filename = Entry->getName();
  321. // If the file is already open, use the open file descriptor.
  322. if (Entry->FD != -1) {
  323. llvm::MemoryBuffer *Buf =
  324. llvm::MemoryBuffer::getOpenFile(Entry->FD, Filename, ErrorStr,
  325. Entry->getSize());
  326. // getOpenFile will have closed the file descriptor, don't reuse or
  327. // reclose it.
  328. Entry->FD = -1;
  329. return Buf;
  330. }
  331. // Otherwise, open the file.
  332. return llvm::MemoryBuffer::getFile(Filename, ErrorStr, Entry->getSize());
  333. }
  334. llvm::sys::Path FilePath(Entry->getName());
  335. FixupRelativePath(FilePath, FileSystemOpts);
  336. return llvm::MemoryBuffer::getFile(FilePath.c_str(), ErrorStr,
  337. Entry->getSize());
  338. }
  339. llvm::MemoryBuffer *FileManager::
  340. getBufferForFile(llvm::StringRef Filename, std::string *ErrorStr) {
  341. if (FileSystemOpts.WorkingDir.empty())
  342. return llvm::MemoryBuffer::getFile(Filename, ErrorStr);
  343. llvm::sys::Path FilePath(Filename);
  344. FixupRelativePath(FilePath, FileSystemOpts);
  345. return llvm::MemoryBuffer::getFile(FilePath.c_str(), ErrorStr);
  346. }
  347. /// getStatValue - Get the 'stat' information for the specified path, using the
  348. /// cache to accelerate it if possible. This returns true if the path does not
  349. /// exist or false if it exists.
  350. ///
  351. /// The isForDir member indicates whether this is a directory lookup or not.
  352. /// This will return failure if the lookup isn't the expected kind.
  353. bool FileManager::getStatValue(const char *Path, struct stat &StatBuf,
  354. int *FileDescriptor) {
  355. // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
  356. // absolute!
  357. if (FileSystemOpts.WorkingDir.empty())
  358. return FileSystemStatCache::get(Path, StatBuf, FileDescriptor,
  359. StatCache.get());
  360. llvm::sys::Path FilePath(Path);
  361. FixupRelativePath(FilePath, FileSystemOpts);
  362. return FileSystemStatCache::get(FilePath.c_str(), StatBuf, FileDescriptor,
  363. StatCache.get());
  364. }
  365. void FileManager::PrintStats() const {
  366. llvm::errs() << "\n*** File Manager Stats:\n";
  367. llvm::errs() << UniqueFiles.size() << " files found, "
  368. << UniqueDirs.size() << " dirs found.\n";
  369. llvm::errs() << NumDirLookups << " dir lookups, "
  370. << NumDirCacheMisses << " dir cache misses.\n";
  371. llvm::errs() << NumFileLookups << " file lookups, "
  372. << NumFileCacheMisses << " file cache misses.\n";
  373. //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
  374. }