FileManager.cpp 20 KB

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