FileManager.cpp 16 KB

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