FileManager.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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/Config/llvm-config.h"
  23. #include "llvm/Support/FileSystem.h"
  24. #include "llvm/Support/MemoryBuffer.h"
  25. #include "llvm/Support/Path.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include "llvm/Support/system_error.h"
  28. #include <map>
  29. #include <set>
  30. #include <string>
  31. using namespace clang;
  32. // FIXME: Enhance libsystem to support inode and other fields.
  33. #include <sys/stat.h>
  34. /// NON_EXISTENT_DIR - A special value distinct from null that is used to
  35. /// represent a dir name that doesn't exist on the disk.
  36. #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
  37. /// NON_EXISTENT_FILE - A special value distinct from null that is used to
  38. /// represent a filename that doesn't exist on the disk.
  39. #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
  40. class FileManager::UniqueDirContainer {
  41. /// UniqueDirs - Cache from ID's to existing directories/files.
  42. std::map<llvm::sys::fs::UniqueID, DirectoryEntry> UniqueDirs;
  43. public:
  44. /// getDirectory - Return an existing DirectoryEntry with the given
  45. /// ID's if there is already one; otherwise create and return a
  46. /// default-constructed DirectoryEntry.
  47. DirectoryEntry &getDirectory(const llvm::sys::fs::UniqueID &UniqueID) {
  48. return UniqueDirs[UniqueID];
  49. }
  50. size_t size() const { return UniqueDirs.size(); }
  51. };
  52. class FileManager::UniqueFileContainer {
  53. /// UniqueFiles - Cache from ID's to existing directories/files.
  54. std::set<FileEntry> UniqueFiles;
  55. public:
  56. /// getFile - Return an existing FileEntry with the given ID's if
  57. /// there is already one; otherwise create and return a
  58. /// default-constructed FileEntry.
  59. FileEntry &getFile(llvm::sys::fs::UniqueID UniqueID, bool IsNamedPipe,
  60. bool InPCH) {
  61. return const_cast<FileEntry &>(
  62. *UniqueFiles.insert(FileEntry(UniqueID, IsNamedPipe, InPCH)).first);
  63. }
  64. size_t size() const { return UniqueFiles.size(); }
  65. void erase(const FileEntry *Entry) { UniqueFiles.erase(*Entry); }
  66. };
  67. //===----------------------------------------------------------------------===//
  68. // Common logic.
  69. //===----------------------------------------------------------------------===//
  70. FileManager::FileManager(const FileSystemOptions &FSO,
  71. IntrusiveRefCntPtr<vfs::FileSystem> FS)
  72. : FS(FS), FileSystemOpts(FSO),
  73. UniqueRealDirs(*new UniqueDirContainer()),
  74. UniqueRealFiles(*new UniqueFileContainer()),
  75. SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
  76. NumDirLookups = NumFileLookups = 0;
  77. NumDirCacheMisses = NumFileCacheMisses = 0;
  78. // If the caller doesn't provide a virtual file system, just grab the real
  79. // file system.
  80. if (!FS)
  81. this->FS = vfs::getRealFileSystem();
  82. }
  83. FileManager::~FileManager() {
  84. delete &UniqueRealDirs;
  85. delete &UniqueRealFiles;
  86. for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
  87. delete VirtualFileEntries[i];
  88. for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
  89. delete VirtualDirectoryEntries[i];
  90. }
  91. void FileManager::addStatCache(FileSystemStatCache *statCache,
  92. bool AtBeginning) {
  93. assert(statCache && "No stat cache provided?");
  94. if (AtBeginning || StatCache.get() == 0) {
  95. statCache->setNextStatCache(StatCache.take());
  96. StatCache.reset(statCache);
  97. return;
  98. }
  99. FileSystemStatCache *LastCache = StatCache.get();
  100. while (LastCache->getNextStatCache())
  101. LastCache = LastCache->getNextStatCache();
  102. LastCache->setNextStatCache(statCache);
  103. }
  104. void FileManager::removeStatCache(FileSystemStatCache *statCache) {
  105. if (!statCache)
  106. return;
  107. if (StatCache.get() == statCache) {
  108. // This is the first stat cache.
  109. StatCache.reset(StatCache->takeNextStatCache());
  110. return;
  111. }
  112. // Find the stat cache in the list.
  113. FileSystemStatCache *PrevCache = StatCache.get();
  114. while (PrevCache && PrevCache->getNextStatCache() != statCache)
  115. PrevCache = PrevCache->getNextStatCache();
  116. assert(PrevCache && "Stat cache not found for removal");
  117. PrevCache->setNextStatCache(statCache->getNextStatCache());
  118. }
  119. void FileManager::clearStatCaches() {
  120. StatCache.reset(0);
  121. }
  122. /// \brief Retrieve the directory that the given file name resides in.
  123. /// Filename can point to either a real file or a virtual file.
  124. static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
  125. StringRef Filename,
  126. bool CacheFailure) {
  127. if (Filename.empty())
  128. return NULL;
  129. if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
  130. return NULL; // If Filename is a directory.
  131. StringRef DirName = llvm::sys::path::parent_path(Filename);
  132. // Use the current directory if file has no path component.
  133. if (DirName.empty())
  134. DirName = ".";
  135. return FileMgr.getDirectory(DirName, CacheFailure);
  136. }
  137. /// Add all ancestors of the given path (pointing to either a file or
  138. /// a directory) as virtual directories.
  139. void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
  140. StringRef DirName = llvm::sys::path::parent_path(Path);
  141. if (DirName.empty())
  142. return;
  143. llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
  144. SeenDirEntries.GetOrCreateValue(DirName);
  145. // When caching a virtual directory, we always cache its ancestors
  146. // at the same time. Therefore, if DirName is already in the cache,
  147. // we don't need to recurse as its ancestors must also already be in
  148. // the cache.
  149. if (NamedDirEnt.getValue())
  150. return;
  151. // Add the virtual directory to the cache.
  152. DirectoryEntry *UDE = new DirectoryEntry;
  153. UDE->Name = NamedDirEnt.getKeyData();
  154. NamedDirEnt.setValue(UDE);
  155. VirtualDirectoryEntries.push_back(UDE);
  156. // Recursively add the other ancestors.
  157. addAncestorsAsVirtualDirs(DirName);
  158. }
  159. const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
  160. bool CacheFailure) {
  161. // stat doesn't like trailing separators except for root directory.
  162. // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
  163. // (though it can strip '\\')
  164. if (DirName.size() > 1 &&
  165. DirName != llvm::sys::path::root_path(DirName) &&
  166. llvm::sys::path::is_separator(DirName.back()))
  167. DirName = DirName.substr(0, DirName.size()-1);
  168. #ifdef LLVM_ON_WIN32
  169. // Fixing a problem with "clang C:test.c" on Windows.
  170. // Stat("C:") does not recognize "C:" as a valid directory
  171. std::string DirNameStr;
  172. if (DirName.size() > 1 && DirName.back() == ':' &&
  173. DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
  174. DirNameStr = DirName.str() + '.';
  175. DirName = DirNameStr;
  176. }
  177. #endif
  178. ++NumDirLookups;
  179. llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
  180. SeenDirEntries.GetOrCreateValue(DirName);
  181. // See if there was already an entry in the map. Note that the map
  182. // contains both virtual and real directories.
  183. if (NamedDirEnt.getValue())
  184. return NamedDirEnt.getValue() == NON_EXISTENT_DIR
  185. ? 0 : NamedDirEnt.getValue();
  186. ++NumDirCacheMisses;
  187. // By default, initialize it to invalid.
  188. NamedDirEnt.setValue(NON_EXISTENT_DIR);
  189. // Get the null-terminated directory name as stored as the key of the
  190. // SeenDirEntries map.
  191. const char *InterndDirName = NamedDirEnt.getKeyData();
  192. // Check to see if the directory exists.
  193. FileData Data;
  194. if (getStatValue(InterndDirName, Data, false, 0 /*directory lookup*/)) {
  195. // There's no real directory at the given path.
  196. if (!CacheFailure)
  197. SeenDirEntries.erase(DirName);
  198. return 0;
  199. }
  200. // It exists. See if we have already opened a directory with the
  201. // same inode (this occurs on Unix-like systems when one dir is
  202. // symlinked to another, for example) or the same path (on
  203. // Windows).
  204. DirectoryEntry &UDE =
  205. UniqueRealDirs.getDirectory(Data.UniqueID);
  206. NamedDirEnt.setValue(&UDE);
  207. if (!UDE.getName()) {
  208. // We don't have this directory yet, add it. We use the string
  209. // key from the SeenDirEntries map as the string.
  210. UDE.Name = InterndDirName;
  211. }
  212. return &UDE;
  213. }
  214. const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
  215. bool CacheFailure) {
  216. ++NumFileLookups;
  217. // See if there is already an entry in the map.
  218. llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
  219. SeenFileEntries.GetOrCreateValue(Filename);
  220. // See if there is already an entry in the map.
  221. if (NamedFileEnt.getValue())
  222. return NamedFileEnt.getValue() == NON_EXISTENT_FILE
  223. ? 0 : NamedFileEnt.getValue();
  224. ++NumFileCacheMisses;
  225. // By default, initialize it to invalid.
  226. NamedFileEnt.setValue(NON_EXISTENT_FILE);
  227. // Get the null-terminated file name as stored as the key of the
  228. // SeenFileEntries map.
  229. const char *InterndFileName = NamedFileEnt.getKeyData();
  230. // Look up the directory for the file. When looking up something like
  231. // sys/foo.h we'll discover all of the search directories that have a 'sys'
  232. // subdirectory. This will let us avoid having to waste time on known-to-fail
  233. // searches when we go to find sys/bar.h, because all the search directories
  234. // without a 'sys' subdir will get a cached failure result.
  235. const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
  236. CacheFailure);
  237. if (DirInfo == 0) { // Directory doesn't exist, file can't exist.
  238. if (!CacheFailure)
  239. SeenFileEntries.erase(Filename);
  240. return 0;
  241. }
  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. vfs::File *F = 0;
  246. FileData Data;
  247. if (getStatValue(InterndFileName, Data, true, openFile ? &F : 0)) {
  248. // There's no real file at the given path.
  249. if (!CacheFailure)
  250. SeenFileEntries.erase(Filename);
  251. return 0;
  252. }
  253. assert(openFile || !F && "undesired open file");
  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 =
  257. UniqueRealFiles.getFile(Data.UniqueID, Data.IsNamedPipe, Data.InPCH);
  258. NamedFileEnt.setValue(&UFE);
  259. if (UFE.getName()) { // Already have an entry with this inode, return it.
  260. // If the stat process opened the file, close it to avoid a FD leak.
  261. if (F)
  262. delete F;
  263. return &UFE;
  264. }
  265. // Otherwise, we don't have this directory yet, add it.
  266. // FIXME: Change the name to be a char* that points back to the
  267. // 'SeenFileEntries' key.
  268. UFE.Name = InterndFileName;
  269. UFE.Size = Data.Size;
  270. UFE.ModTime = Data.ModTime;
  271. UFE.Dir = DirInfo;
  272. UFE.UID = NextFileUID++;
  273. UFE.File.reset(F);
  274. return &UFE;
  275. }
  276. const FileEntry *
  277. FileManager::getVirtualFile(StringRef Filename, off_t Size,
  278. time_t ModificationTime) {
  279. ++NumFileLookups;
  280. // See if there is already an entry in the map.
  281. llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
  282. SeenFileEntries.GetOrCreateValue(Filename);
  283. // See if there is already an entry in the map.
  284. if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
  285. return NamedFileEnt.getValue();
  286. ++NumFileCacheMisses;
  287. // By default, initialize it to invalid.
  288. NamedFileEnt.setValue(NON_EXISTENT_FILE);
  289. addAncestorsAsVirtualDirs(Filename);
  290. FileEntry *UFE = 0;
  291. // Now that all ancestors of Filename are in the cache, the
  292. // following call is guaranteed to find the DirectoryEntry from the
  293. // cache.
  294. const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
  295. /*CacheFailure=*/true);
  296. assert(DirInfo &&
  297. "The directory of a virtual file should already be in the cache.");
  298. // Check to see if the file exists. If so, drop the virtual file
  299. FileData Data;
  300. const char *InterndFileName = NamedFileEnt.getKeyData();
  301. if (getStatValue(InterndFileName, Data, true, 0) == 0) {
  302. Data.Size = Size;
  303. Data.ModTime = ModificationTime;
  304. UFE = &UniqueRealFiles.getFile(Data.UniqueID, Data.IsNamedPipe, Data.InPCH);
  305. NamedFileEnt.setValue(UFE);
  306. // If we had already opened this file, close it now so we don't
  307. // leak the descriptor. We're not going to use the file
  308. // descriptor anyway, since this is a virtual file.
  309. if (UFE->File)
  310. UFE->closeFile();
  311. // If we already have an entry with this inode, return it.
  312. if (UFE->getName())
  313. return UFE;
  314. }
  315. if (!UFE) {
  316. UFE = new FileEntry();
  317. VirtualFileEntries.push_back(UFE);
  318. NamedFileEnt.setValue(UFE);
  319. }
  320. UFE->Name = InterndFileName;
  321. UFE->Size = Size;
  322. UFE->ModTime = ModificationTime;
  323. UFE->Dir = DirInfo;
  324. UFE->UID = NextFileUID++;
  325. UFE->File.reset();
  326. return UFE;
  327. }
  328. void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
  329. StringRef pathRef(path.data(), path.size());
  330. if (FileSystemOpts.WorkingDir.empty()
  331. || llvm::sys::path::is_absolute(pathRef))
  332. return;
  333. SmallString<128> NewPath(FileSystemOpts.WorkingDir);
  334. llvm::sys::path::append(NewPath, pathRef);
  335. path = NewPath;
  336. }
  337. llvm::MemoryBuffer *FileManager::
  338. getBufferForFile(const FileEntry *Entry, std::string *ErrorStr,
  339. bool isVolatile) {
  340. OwningPtr<llvm::MemoryBuffer> Result;
  341. llvm::error_code ec;
  342. uint64_t FileSize = Entry->getSize();
  343. // If there's a high enough chance that the file have changed since we
  344. // got its size, force a stat before opening it.
  345. if (isVolatile)
  346. FileSize = -1;
  347. const char *Filename = Entry->getName();
  348. // If the file is already open, use the open file descriptor.
  349. if (Entry->File) {
  350. ec = Entry->File->getBuffer(Filename, Result, FileSize);
  351. if (ErrorStr)
  352. *ErrorStr = ec.message();
  353. Entry->closeFile();
  354. return Result.take();
  355. }
  356. // Otherwise, open the file.
  357. if (FileSystemOpts.WorkingDir.empty()) {
  358. ec = FS->getBufferForFile(Filename, Result, FileSize);
  359. if (ec && ErrorStr)
  360. *ErrorStr = ec.message();
  361. return Result.take();
  362. }
  363. SmallString<128> FilePath(Entry->getName());
  364. FixupRelativePath(FilePath);
  365. ec = FS->getBufferForFile(FilePath.str(), Result, FileSize);
  366. if (ec && ErrorStr)
  367. *ErrorStr = ec.message();
  368. return Result.take();
  369. }
  370. llvm::MemoryBuffer *FileManager::
  371. getBufferForFile(StringRef Filename, std::string *ErrorStr) {
  372. OwningPtr<llvm::MemoryBuffer> Result;
  373. llvm::error_code ec;
  374. if (FileSystemOpts.WorkingDir.empty()) {
  375. ec = FS->getBufferForFile(Filename, Result);
  376. if (ec && ErrorStr)
  377. *ErrorStr = ec.message();
  378. return Result.take();
  379. }
  380. SmallString<128> FilePath(Filename);
  381. FixupRelativePath(FilePath);
  382. ec = FS->getBufferForFile(FilePath.c_str(), Result);
  383. if (ec && ErrorStr)
  384. *ErrorStr = ec.message();
  385. return Result.take();
  386. }
  387. /// getStatValue - Get the 'stat' information for the specified path,
  388. /// using the cache to accelerate it if possible. This returns true
  389. /// if the path points to a virtual file or does not exist, or returns
  390. /// false if it's an existent real file. If FileDescriptor is NULL,
  391. /// do directory look-up instead of file look-up.
  392. bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile,
  393. vfs::File **F) {
  394. // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
  395. // absolute!
  396. if (FileSystemOpts.WorkingDir.empty())
  397. return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
  398. SmallString<128> FilePath(Path);
  399. FixupRelativePath(FilePath);
  400. return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
  401. StatCache.get(), *FS);
  402. }
  403. bool FileManager::getNoncachedStatValue(StringRef Path,
  404. vfs::Status &Result) {
  405. SmallString<128> FilePath(Path);
  406. FixupRelativePath(FilePath);
  407. llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str());
  408. if (!S)
  409. return true;
  410. Result = *S;
  411. return false;
  412. }
  413. void FileManager::invalidateCache(const FileEntry *Entry) {
  414. assert(Entry && "Cannot invalidate a NULL FileEntry");
  415. SeenFileEntries.erase(Entry->getName());
  416. // FileEntry invalidation should not block future optimizations in the file
  417. // caches. Possible alternatives are cache truncation (invalidate last N) or
  418. // invalidation of the whole cache.
  419. UniqueRealFiles.erase(Entry);
  420. }
  421. void FileManager::GetUniqueIDMapping(
  422. SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
  423. UIDToFiles.clear();
  424. UIDToFiles.resize(NextFileUID);
  425. // Map file entries
  426. for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
  427. FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
  428. FE != FEEnd; ++FE)
  429. if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
  430. UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
  431. // Map virtual file entries
  432. for (SmallVectorImpl<FileEntry *>::const_iterator
  433. VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
  434. VFE != VFEEnd; ++VFE)
  435. if (*VFE && *VFE != NON_EXISTENT_FILE)
  436. UIDToFiles[(*VFE)->getUID()] = *VFE;
  437. }
  438. void FileManager::modifyFileEntry(FileEntry *File,
  439. off_t Size, time_t ModificationTime) {
  440. File->Size = Size;
  441. File->ModTime = ModificationTime;
  442. }
  443. StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
  444. // FIXME: use llvm::sys::fs::canonical() when it gets implemented
  445. #ifdef LLVM_ON_UNIX
  446. llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
  447. = CanonicalDirNames.find(Dir);
  448. if (Known != CanonicalDirNames.end())
  449. return Known->second;
  450. StringRef CanonicalName(Dir->getName());
  451. char CanonicalNameBuf[PATH_MAX];
  452. if (realpath(Dir->getName(), CanonicalNameBuf)) {
  453. unsigned Len = strlen(CanonicalNameBuf);
  454. char *Mem = static_cast<char *>(CanonicalNameStorage.Allocate(Len, 1));
  455. memcpy(Mem, CanonicalNameBuf, Len);
  456. CanonicalName = StringRef(Mem, Len);
  457. }
  458. CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
  459. return CanonicalName;
  460. #else
  461. return StringRef(Dir->getName());
  462. #endif
  463. }
  464. void FileManager::PrintStats() const {
  465. llvm::errs() << "\n*** File Manager Stats:\n";
  466. llvm::errs() << UniqueRealFiles.size() << " real files found, "
  467. << UniqueRealDirs.size() << " real dirs found.\n";
  468. llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
  469. << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
  470. llvm::errs() << NumDirLookups << " dir lookups, "
  471. << NumDirCacheMisses << " dir cache misses.\n";
  472. llvm::errs() << NumFileLookups << " file lookups, "
  473. << NumFileCacheMisses << " file cache misses.\n";
  474. //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
  475. }