FileManager.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  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/STLExtras.h"
  21. #include "llvm/ADT/SmallString.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/Config/llvm-config.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. #define DEBUG_TYPE "file-search"
  37. ALWAYS_ENABLED_STATISTIC(NumDirLookups, "Number of directory lookups.");
  38. ALWAYS_ENABLED_STATISTIC(NumFileLookups, "Number of file lookups.");
  39. ALWAYS_ENABLED_STATISTIC(NumDirCacheMisses,
  40. "Number of directory cache misses.");
  41. ALWAYS_ENABLED_STATISTIC(NumFileCacheMisses, "Number of file cache misses.");
  42. //===----------------------------------------------------------------------===//
  43. // Common logic.
  44. //===----------------------------------------------------------------------===//
  45. FileManager::FileManager(const FileSystemOptions &FSO,
  46. IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
  47. : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
  48. SeenFileEntries(64), NextFileUID(0) {
  49. // If the caller doesn't provide a virtual file system, just grab the real
  50. // file system.
  51. if (!this->FS)
  52. this->FS = llvm::vfs::getRealFileSystem();
  53. }
  54. FileManager::~FileManager() = default;
  55. void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
  56. assert(statCache && "No stat cache provided?");
  57. StatCache = std::move(statCache);
  58. }
  59. void FileManager::clearStatCache() { StatCache.reset(); }
  60. /// Retrieve the directory that the given file name resides in.
  61. /// Filename can point to either a real file or a virtual file.
  62. static llvm::Expected<DirectoryEntryRef>
  63. getDirectoryFromFile(FileManager &FileMgr, StringRef Filename,
  64. bool CacheFailure) {
  65. if (Filename.empty())
  66. return llvm::errorCodeToError(
  67. make_error_code(std::errc::no_such_file_or_directory));
  68. if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
  69. return llvm::errorCodeToError(make_error_code(std::errc::is_a_directory));
  70. StringRef DirName = llvm::sys::path::parent_path(Filename);
  71. // Use the current directory if file has no path component.
  72. if (DirName.empty())
  73. DirName = ".";
  74. return FileMgr.getDirectoryRef(DirName, CacheFailure);
  75. }
  76. /// Add all ancestors of the given path (pointing to either a file or
  77. /// a directory) as virtual directories.
  78. void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
  79. StringRef DirName = llvm::sys::path::parent_path(Path);
  80. if (DirName.empty())
  81. DirName = ".";
  82. auto &NamedDirEnt = *SeenDirEntries.insert(
  83. {DirName, std::errc::no_such_file_or_directory}).first;
  84. // When caching a virtual directory, we always cache its ancestors
  85. // at the same time. Therefore, if DirName is already in the cache,
  86. // we don't need to recurse as its ancestors must also already be in
  87. // the cache (or it's a known non-virtual directory).
  88. if (NamedDirEnt.second)
  89. return;
  90. // Add the virtual directory to the cache.
  91. auto UDE = std::make_unique<DirectoryEntry>();
  92. UDE->Name = NamedDirEnt.first();
  93. NamedDirEnt.second = *UDE.get();
  94. VirtualDirectoryEntries.push_back(std::move(UDE));
  95. // Recursively add the other ancestors.
  96. addAncestorsAsVirtualDirs(DirName);
  97. }
  98. llvm::Expected<DirectoryEntryRef>
  99. FileManager::getDirectoryRef(StringRef DirName, bool CacheFailure) {
  100. // stat doesn't like trailing separators except for root directory.
  101. // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
  102. // (though it can strip '\\')
  103. if (DirName.size() > 1 &&
  104. DirName != llvm::sys::path::root_path(DirName) &&
  105. llvm::sys::path::is_separator(DirName.back()))
  106. DirName = DirName.substr(0, DirName.size()-1);
  107. Optional<std::string> DirNameStr;
  108. if (is_style_windows(llvm::sys::path::Style::native)) {
  109. // Fixing a problem with "clang C:test.c" on Windows.
  110. // Stat("C:") does not recognize "C:" as a valid directory
  111. if (DirName.size() > 1 && DirName.back() == ':' &&
  112. DirName.equals_insensitive(llvm::sys::path::root_name(DirName))) {
  113. DirNameStr = DirName.str() + '.';
  114. DirName = *DirNameStr;
  115. }
  116. }
  117. ++NumDirLookups;
  118. // See if there was already an entry in the map. Note that the map
  119. // contains both virtual and real directories.
  120. auto SeenDirInsertResult =
  121. SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory});
  122. if (!SeenDirInsertResult.second) {
  123. if (SeenDirInsertResult.first->second)
  124. return DirectoryEntryRef(*SeenDirInsertResult.first);
  125. return llvm::errorCodeToError(SeenDirInsertResult.first->second.getError());
  126. }
  127. // We've not seen this before. Fill it in.
  128. ++NumDirCacheMisses;
  129. auto &NamedDirEnt = *SeenDirInsertResult.first;
  130. assert(!NamedDirEnt.second && "should be newly-created");
  131. // Get the null-terminated directory name as stored as the key of the
  132. // SeenDirEntries map.
  133. StringRef InterndDirName = NamedDirEnt.first();
  134. // Check to see if the directory exists.
  135. llvm::vfs::Status Status;
  136. auto statError = getStatValue(InterndDirName, Status, false,
  137. nullptr /*directory lookup*/);
  138. if (statError) {
  139. // There's no real directory at the given path.
  140. if (CacheFailure)
  141. NamedDirEnt.second = statError;
  142. else
  143. SeenDirEntries.erase(DirName);
  144. return llvm::errorCodeToError(statError);
  145. }
  146. // It exists. See if we have already opened a directory with the
  147. // same inode (this occurs on Unix-like systems when one dir is
  148. // symlinked to another, for example) or the same path (on
  149. // Windows).
  150. DirectoryEntry &UDE = UniqueRealDirs[Status.getUniqueID()];
  151. NamedDirEnt.second = UDE;
  152. if (UDE.getName().empty()) {
  153. // We don't have this directory yet, add it. We use the string
  154. // key from the SeenDirEntries map as the string.
  155. UDE.Name = InterndDirName;
  156. }
  157. return DirectoryEntryRef(NamedDirEnt);
  158. }
  159. llvm::ErrorOr<const DirectoryEntry *>
  160. FileManager::getDirectory(StringRef DirName, bool CacheFailure) {
  161. auto Result = getDirectoryRef(DirName, CacheFailure);
  162. if (Result)
  163. return &Result->getDirEntry();
  164. return llvm::errorToErrorCode(Result.takeError());
  165. }
  166. llvm::ErrorOr<const FileEntry *>
  167. FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) {
  168. auto Result = getFileRef(Filename, openFile, CacheFailure);
  169. if (Result)
  170. return &Result->getFileEntry();
  171. return llvm::errorToErrorCode(Result.takeError());
  172. }
  173. llvm::Expected<FileEntryRef>
  174. FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) {
  175. ++NumFileLookups;
  176. // See if there is already an entry in the map.
  177. auto SeenFileInsertResult =
  178. SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
  179. if (!SeenFileInsertResult.second) {
  180. if (!SeenFileInsertResult.first->second)
  181. return llvm::errorCodeToError(
  182. SeenFileInsertResult.first->second.getError());
  183. // Construct and return and FileEntryRef, unless it's a redirect to another
  184. // filename.
  185. FileEntryRef::MapValue Value = *SeenFileInsertResult.first->second;
  186. if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
  187. return FileEntryRef(*SeenFileInsertResult.first);
  188. return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
  189. Value.V.get<const void *>()));
  190. }
  191. // We've not seen this before. Fill it in.
  192. ++NumFileCacheMisses;
  193. auto *NamedFileEnt = &*SeenFileInsertResult.first;
  194. assert(!NamedFileEnt->second && "should be newly-created");
  195. // Get the null-terminated file name as stored as the key of the
  196. // SeenFileEntries map.
  197. StringRef InterndFileName = NamedFileEnt->first();
  198. // Look up the directory for the file. When looking up something like
  199. // sys/foo.h we'll discover all of the search directories that have a 'sys'
  200. // subdirectory. This will let us avoid having to waste time on known-to-fail
  201. // searches when we go to find sys/bar.h, because all the search directories
  202. // without a 'sys' subdir will get a cached failure result.
  203. auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure);
  204. if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist.
  205. std::error_code Err = errorToErrorCode(DirInfoOrErr.takeError());
  206. if (CacheFailure)
  207. NamedFileEnt->second = Err;
  208. else
  209. SeenFileEntries.erase(Filename);
  210. return llvm::errorCodeToError(Err);
  211. }
  212. DirectoryEntryRef DirInfo = *DirInfoOrErr;
  213. // FIXME: Use the directory info to prune this, before doing the stat syscall.
  214. // FIXME: This will reduce the # syscalls.
  215. // Check to see if the file exists.
  216. std::unique_ptr<llvm::vfs::File> F;
  217. llvm::vfs::Status Status;
  218. auto statError = getStatValue(InterndFileName, Status, true,
  219. openFile ? &F : nullptr);
  220. if (statError) {
  221. // There's no real file at the given path.
  222. if (CacheFailure)
  223. NamedFileEnt->second = statError;
  224. else
  225. SeenFileEntries.erase(Filename);
  226. return llvm::errorCodeToError(statError);
  227. }
  228. assert((openFile || !F) && "undesired open file");
  229. // It exists. See if we have already opened a file with the same inode.
  230. // This occurs when one dir is symlinked to another, for example.
  231. FileEntry &UFE = UniqueRealFiles[Status.getUniqueID()];
  232. if (Status.getName() == Filename) {
  233. // The name matches. Set the FileEntry.
  234. NamedFileEnt->second = FileEntryRef::MapValue(UFE, DirInfo);
  235. } else {
  236. // Name mismatch. We need a redirect. First grab the actual entry we want
  237. // to return.
  238. //
  239. // This redirection logic intentionally leaks the external name of a
  240. // redirected file that uses 'use-external-name' in \a
  241. // vfs::RedirectionFileSystem. This allows clang to report the external
  242. // name to users (in diagnostics) and to tools that don't have access to
  243. // the VFS (in debug info and dependency '.d' files).
  244. //
  245. // FIXME: This is pretty complicated. It's also inconsistent with how
  246. // "real" filesystems behave and confuses parts of clang expect to see the
  247. // name-as-accessed on the \a FileEntryRef. Maybe the returned \a
  248. // FileEntryRef::getName() could return the accessed name unmodified, but
  249. // make the external name available via a separate API.
  250. auto &Redirection =
  251. *SeenFileEntries
  252. .insert({Status.getName(), FileEntryRef::MapValue(UFE, DirInfo)})
  253. .first;
  254. assert(Redirection.second->V.is<FileEntry *>() &&
  255. "filename redirected to a non-canonical filename?");
  256. assert(Redirection.second->V.get<FileEntry *>() == &UFE &&
  257. "filename from getStatValue() refers to wrong file");
  258. // Cache the redirection in the previously-inserted entry, still available
  259. // in the tentative return value.
  260. NamedFileEnt->second = FileEntryRef::MapValue(Redirection);
  261. // Fix the tentative return value.
  262. NamedFileEnt = &Redirection;
  263. }
  264. FileEntryRef ReturnedRef(*NamedFileEnt);
  265. if (UFE.isValid()) { // Already have an entry with this inode, return it.
  266. // FIXME: this hack ensures that if we look up a file by a virtual path in
  267. // the VFS that the getDir() will have the virtual path, even if we found
  268. // the file by a 'real' path first. This is required in order to find a
  269. // module's structure when its headers/module map are mapped in the VFS.
  270. // We should remove this as soon as we can properly support a file having
  271. // multiple names.
  272. if (&DirInfo.getDirEntry() != UFE.Dir && Status.IsVFSMapped)
  273. UFE.Dir = &DirInfo.getDirEntry();
  274. // Always update LastRef to the last name by which a file was accessed.
  275. // FIXME: Neither this nor always using the first reference is correct; we
  276. // want to switch towards a design where we return a FileName object that
  277. // encapsulates both the name by which the file was accessed and the
  278. // corresponding FileEntry.
  279. // FIXME: LastRef should be removed from FileEntry once all clients adopt
  280. // FileEntryRef.
  281. UFE.LastRef = ReturnedRef;
  282. return ReturnedRef;
  283. }
  284. // Otherwise, we don't have this file yet, add it.
  285. UFE.LastRef = ReturnedRef;
  286. UFE.Size = Status.getSize();
  287. UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
  288. UFE.Dir = &DirInfo.getDirEntry();
  289. UFE.UID = NextFileUID++;
  290. UFE.UniqueID = Status.getUniqueID();
  291. UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
  292. UFE.File = std::move(F);
  293. UFE.IsValid = true;
  294. if (UFE.File) {
  295. if (auto PathName = UFE.File->getName())
  296. fillRealPathName(&UFE, *PathName);
  297. } else if (!openFile) {
  298. // We should still fill the path even if we aren't opening the file.
  299. fillRealPathName(&UFE, InterndFileName);
  300. }
  301. return ReturnedRef;
  302. }
  303. llvm::Expected<FileEntryRef> FileManager::getSTDIN() {
  304. // Only read stdin once.
  305. if (STDIN)
  306. return *STDIN;
  307. std::unique_ptr<llvm::MemoryBuffer> Content;
  308. if (auto ContentOrError = llvm::MemoryBuffer::getSTDIN())
  309. Content = std::move(*ContentOrError);
  310. else
  311. return llvm::errorCodeToError(ContentOrError.getError());
  312. STDIN = getVirtualFileRef(Content->getBufferIdentifier(),
  313. Content->getBufferSize(), 0);
  314. FileEntry &FE = const_cast<FileEntry &>(STDIN->getFileEntry());
  315. FE.Content = std::move(Content);
  316. FE.IsNamedPipe = true;
  317. return *STDIN;
  318. }
  319. const FileEntry *FileManager::getVirtualFile(StringRef Filename, off_t Size,
  320. time_t ModificationTime) {
  321. return &getVirtualFileRef(Filename, Size, ModificationTime).getFileEntry();
  322. }
  323. FileEntryRef FileManager::getVirtualFileRef(StringRef Filename, off_t Size,
  324. time_t ModificationTime) {
  325. ++NumFileLookups;
  326. // See if there is already an entry in the map for an existing file.
  327. auto &NamedFileEnt = *SeenFileEntries.insert(
  328. {Filename, std::errc::no_such_file_or_directory}).first;
  329. if (NamedFileEnt.second) {
  330. FileEntryRef::MapValue Value = *NamedFileEnt.second;
  331. if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
  332. return FileEntryRef(NamedFileEnt);
  333. return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
  334. Value.V.get<const void *>()));
  335. }
  336. // We've not seen this before, or the file is cached as non-existent.
  337. ++NumFileCacheMisses;
  338. addAncestorsAsVirtualDirs(Filename);
  339. FileEntry *UFE = nullptr;
  340. // Now that all ancestors of Filename are in the cache, the
  341. // following call is guaranteed to find the DirectoryEntry from the
  342. // cache. A virtual file can also have an empty filename, that could come
  343. // from a source location preprocessor directive with an empty filename as
  344. // an example, so we need to pretend it has a name to ensure a valid directory
  345. // entry can be returned.
  346. auto DirInfo = expectedToOptional(getDirectoryFromFile(
  347. *this, Filename.empty() ? "." : Filename, /*CacheFailure=*/true));
  348. assert(DirInfo &&
  349. "The directory of a virtual file should already be in the cache.");
  350. // Check to see if the file exists. If so, drop the virtual file
  351. llvm::vfs::Status Status;
  352. const char *InterndFileName = NamedFileEnt.first().data();
  353. if (!getStatValue(InterndFileName, Status, true, nullptr)) {
  354. UFE = &UniqueRealFiles[Status.getUniqueID()];
  355. Status = llvm::vfs::Status(
  356. Status.getName(), Status.getUniqueID(),
  357. llvm::sys::toTimePoint(ModificationTime),
  358. Status.getUser(), Status.getGroup(), Size,
  359. Status.getType(), Status.getPermissions());
  360. NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo);
  361. // If we had already opened this file, close it now so we don't
  362. // leak the descriptor. We're not going to use the file
  363. // descriptor anyway, since this is a virtual file.
  364. if (UFE->File)
  365. UFE->closeFile();
  366. // If we already have an entry with this inode, return it.
  367. //
  368. // FIXME: Surely this should add a reference by the new name, and return
  369. // it instead...
  370. if (UFE->isValid())
  371. return FileEntryRef(NamedFileEnt);
  372. UFE->UniqueID = Status.getUniqueID();
  373. UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
  374. fillRealPathName(UFE, Status.getName());
  375. } else {
  376. VirtualFileEntries.push_back(std::make_unique<FileEntry>());
  377. UFE = VirtualFileEntries.back().get();
  378. NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo);
  379. }
  380. UFE->LastRef = FileEntryRef(NamedFileEnt);
  381. UFE->Size = Size;
  382. UFE->ModTime = ModificationTime;
  383. UFE->Dir = &DirInfo->getDirEntry();
  384. UFE->UID = NextFileUID++;
  385. UFE->IsValid = true;
  386. UFE->File.reset();
  387. return FileEntryRef(NamedFileEnt);
  388. }
  389. llvm::Optional<FileEntryRef> FileManager::getBypassFile(FileEntryRef VF) {
  390. // Stat of the file and return nullptr if it doesn't exist.
  391. llvm::vfs::Status Status;
  392. if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr))
  393. return None;
  394. if (!SeenBypassFileEntries)
  395. SeenBypassFileEntries = std::make_unique<
  396. llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>>>();
  397. // If we've already bypassed just use the existing one.
  398. auto Insertion = SeenBypassFileEntries->insert(
  399. {VF.getName(), std::errc::no_such_file_or_directory});
  400. if (!Insertion.second)
  401. return FileEntryRef(*Insertion.first);
  402. // Fill in the new entry from the stat.
  403. BypassFileEntries.push_back(std::make_unique<FileEntry>());
  404. const FileEntry &VFE = VF.getFileEntry();
  405. FileEntry &BFE = *BypassFileEntries.back();
  406. Insertion.first->second = FileEntryRef::MapValue(BFE, VF.getDir());
  407. BFE.LastRef = FileEntryRef(*Insertion.first);
  408. BFE.Size = Status.getSize();
  409. BFE.Dir = VFE.Dir;
  410. BFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
  411. BFE.UID = NextFileUID++;
  412. BFE.IsValid = true;
  413. // Save the entry in the bypass table and return.
  414. return FileEntryRef(*Insertion.first);
  415. }
  416. bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
  417. StringRef pathRef(path.data(), path.size());
  418. if (FileSystemOpts.WorkingDir.empty()
  419. || llvm::sys::path::is_absolute(pathRef))
  420. return false;
  421. SmallString<128> NewPath(FileSystemOpts.WorkingDir);
  422. llvm::sys::path::append(NewPath, pathRef);
  423. path = NewPath;
  424. return true;
  425. }
  426. bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
  427. bool Changed = FixupRelativePath(Path);
  428. if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
  429. FS->makeAbsolute(Path);
  430. Changed = true;
  431. }
  432. return Changed;
  433. }
  434. void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
  435. llvm::SmallString<128> AbsPath(FileName);
  436. // This is not the same as `VFS::getRealPath()`, which resolves symlinks
  437. // but can be very expensive on real file systems.
  438. // FIXME: the semantic of RealPathName is unclear, and the name might be
  439. // misleading. We need to clean up the interface here.
  440. makeAbsolutePath(AbsPath);
  441. llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
  442. UFE->RealPathName = std::string(AbsPath.str());
  443. }
  444. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
  445. FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
  446. bool RequiresNullTerminator) {
  447. // If the content is living on the file entry, return a reference to it.
  448. if (Entry->Content)
  449. return llvm::MemoryBuffer::getMemBuffer(Entry->Content->getMemBufferRef());
  450. uint64_t FileSize = Entry->getSize();
  451. // If there's a high enough chance that the file have changed since we
  452. // got its size, force a stat before opening it.
  453. if (isVolatile || Entry->isNamedPipe())
  454. FileSize = -1;
  455. StringRef Filename = Entry->getName();
  456. // If the file is already open, use the open file descriptor.
  457. if (Entry->File) {
  458. auto Result = Entry->File->getBuffer(Filename, FileSize,
  459. RequiresNullTerminator, isVolatile);
  460. Entry->closeFile();
  461. return Result;
  462. }
  463. // Otherwise, open the file.
  464. return getBufferForFileImpl(Filename, FileSize, isVolatile,
  465. RequiresNullTerminator);
  466. }
  467. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
  468. FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
  469. bool isVolatile,
  470. bool RequiresNullTerminator) {
  471. if (FileSystemOpts.WorkingDir.empty())
  472. return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator,
  473. isVolatile);
  474. SmallString<128> FilePath(Filename);
  475. FixupRelativePath(FilePath);
  476. return FS->getBufferForFile(FilePath, FileSize, RequiresNullTerminator,
  477. isVolatile);
  478. }
  479. /// getStatValue - Get the 'stat' information for the specified path,
  480. /// using the cache to accelerate it if possible. This returns true
  481. /// if the path points to a virtual file or does not exist, or returns
  482. /// false if it's an existent real file. If FileDescriptor is NULL,
  483. /// do directory look-up instead of file look-up.
  484. std::error_code
  485. FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
  486. bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
  487. // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
  488. // absolute!
  489. if (FileSystemOpts.WorkingDir.empty())
  490. return FileSystemStatCache::get(Path, Status, isFile, F,
  491. StatCache.get(), *FS);
  492. SmallString<128> FilePath(Path);
  493. FixupRelativePath(FilePath);
  494. return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
  495. StatCache.get(), *FS);
  496. }
  497. std::error_code
  498. FileManager::getNoncachedStatValue(StringRef Path,
  499. llvm::vfs::Status &Result) {
  500. SmallString<128> FilePath(Path);
  501. FixupRelativePath(FilePath);
  502. llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
  503. if (!S)
  504. return S.getError();
  505. Result = *S;
  506. return std::error_code();
  507. }
  508. void FileManager::GetUniqueIDMapping(
  509. SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
  510. UIDToFiles.clear();
  511. UIDToFiles.resize(NextFileUID);
  512. // Map file entries
  513. for (llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>,
  514. llvm::BumpPtrAllocator>::const_iterator
  515. FE = SeenFileEntries.begin(),
  516. FEEnd = SeenFileEntries.end();
  517. FE != FEEnd; ++FE)
  518. if (llvm::ErrorOr<FileEntryRef::MapValue> Entry = FE->getValue()) {
  519. if (const auto *FE = Entry->V.dyn_cast<FileEntry *>())
  520. UIDToFiles[FE->getUID()] = FE;
  521. }
  522. // Map virtual file entries
  523. for (const auto &VFE : VirtualFileEntries)
  524. UIDToFiles[VFE->getUID()] = VFE.get();
  525. }
  526. StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
  527. llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
  528. = CanonicalNames.find(Dir);
  529. if (Known != CanonicalNames.end())
  530. return Known->second;
  531. StringRef CanonicalName(Dir->getName());
  532. SmallString<4096> CanonicalNameBuf;
  533. if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
  534. CanonicalName = CanonicalNameBuf.str().copy(CanonicalNameStorage);
  535. CanonicalNames.insert({Dir, CanonicalName});
  536. return CanonicalName;
  537. }
  538. StringRef FileManager::getCanonicalName(const FileEntry *File) {
  539. llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
  540. = CanonicalNames.find(File);
  541. if (Known != CanonicalNames.end())
  542. return Known->second;
  543. StringRef CanonicalName(File->getName());
  544. SmallString<4096> CanonicalNameBuf;
  545. if (!FS->getRealPath(File->getName(), CanonicalNameBuf))
  546. CanonicalName = CanonicalNameBuf.str().copy(CanonicalNameStorage);
  547. CanonicalNames.insert({File, CanonicalName});
  548. return CanonicalName;
  549. }
  550. void FileManager::PrintStats() const {
  551. llvm::errs() << "\n*** File Manager Stats:\n";
  552. llvm::errs() << UniqueRealFiles.size() << " real files found, "
  553. << UniqueRealDirs.size() << " real dirs found.\n";
  554. llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
  555. << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
  556. llvm::errs() << NumDirLookups << " dir lookups, "
  557. << NumDirCacheMisses << " dir cache misses.\n";
  558. llvm::errs() << NumFileLookups << " file lookups, "
  559. << NumFileCacheMisses << " file cache misses.\n";
  560. //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
  561. }