FileManager.cpp 19 KB

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