FileManager.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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<llvm::vfs::FileSystem> FS)
  47. : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
  48. 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 (!this->FS)
  54. this->FS = llvm::vfs::getRealFileSystem();
  55. }
  56. FileManager::~FileManager() = default;
  57. void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
  58. assert(statCache && "No stat cache provided?");
  59. StatCache = std::move(statCache);
  60. }
  61. void FileManager::clearStatCache() { StatCache.reset(); }
  62. /// Retrieve the directory that the given file name resides in.
  63. /// Filename can point to either a real file or a virtual file.
  64. static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
  65. StringRef Filename,
  66. bool CacheFailure) {
  67. if (Filename.empty())
  68. return nullptr;
  69. if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
  70. return nullptr; // If Filename is a directory.
  71. StringRef DirName = llvm::sys::path::parent_path(Filename);
  72. // Use the current directory if file has no path component.
  73. if (DirName.empty())
  74. DirName = ".";
  75. return FileMgr.getDirectory(DirName, CacheFailure);
  76. }
  77. /// Add all ancestors of the given path (pointing to either a file or
  78. /// a directory) as virtual directories.
  79. void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
  80. StringRef DirName = llvm::sys::path::parent_path(Path);
  81. if (DirName.empty())
  82. DirName = ".";
  83. auto &NamedDirEnt =
  84. *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
  85. // When caching a virtual directory, we always cache its ancestors
  86. // at the same time. Therefore, if DirName is already in the cache,
  87. // we don't need to recurse as its ancestors must also already be in
  88. // the cache.
  89. if (NamedDirEnt.second && NamedDirEnt.second != NON_EXISTENT_DIR)
  90. return;
  91. // Add the virtual directory to the cache.
  92. auto UDE = llvm::make_unique<DirectoryEntry>();
  93. UDE->Name = NamedDirEnt.first();
  94. NamedDirEnt.second = UDE.get();
  95. VirtualDirectoryEntries.push_back(std::move(UDE));
  96. // Recursively add the other ancestors.
  97. addAncestorsAsVirtualDirs(DirName);
  98. }
  99. const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
  100. bool CacheFailure) {
  101. // stat doesn't like trailing separators except for root directory.
  102. // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
  103. // (though it can strip '\\')
  104. if (DirName.size() > 1 &&
  105. DirName != llvm::sys::path::root_path(DirName) &&
  106. llvm::sys::path::is_separator(DirName.back()))
  107. DirName = DirName.substr(0, DirName.size()-1);
  108. #ifdef _WIN32
  109. // Fixing a problem with "clang C:test.c" on Windows.
  110. // Stat("C:") does not recognize "C:" as a valid directory
  111. std::string DirNameStr;
  112. if (DirName.size() > 1 && DirName.back() == ':' &&
  113. DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
  114. DirNameStr = DirName.str() + '.';
  115. DirName = DirNameStr;
  116. }
  117. #endif
  118. ++NumDirLookups;
  119. auto &NamedDirEnt =
  120. *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
  121. // See if there was already an entry in the map. Note that the map
  122. // contains both virtual and real directories.
  123. if (NamedDirEnt.second)
  124. return NamedDirEnt.second == NON_EXISTENT_DIR ? nullptr
  125. : NamedDirEnt.second;
  126. ++NumDirCacheMisses;
  127. // By default, initialize it to invalid.
  128. NamedDirEnt.second = NON_EXISTENT_DIR;
  129. // Get the null-terminated directory name as stored as the key of the
  130. // SeenDirEntries map.
  131. StringRef InterndDirName = NamedDirEnt.first();
  132. // Check to see if the directory exists.
  133. FileData Data;
  134. if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) {
  135. // There's no real directory at the given path.
  136. if (!CacheFailure)
  137. SeenDirEntries.erase(DirName);
  138. return nullptr;
  139. }
  140. // It exists. See if we have already opened a directory with the
  141. // same inode (this occurs on Unix-like systems when one dir is
  142. // symlinked to another, for example) or the same path (on
  143. // Windows).
  144. DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID];
  145. NamedDirEnt.second = &UDE;
  146. if (UDE.getName().empty()) {
  147. // We don't have this directory yet, add it. We use the string
  148. // key from the SeenDirEntries map as the string.
  149. UDE.Name = InterndDirName;
  150. }
  151. return &UDE;
  152. }
  153. const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
  154. bool CacheFailure) {
  155. ++NumFileLookups;
  156. // See if there is already an entry in the map.
  157. auto &NamedFileEnt =
  158. *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
  159. // See if there is already an entry in the map.
  160. if (NamedFileEnt.second) {
  161. if (NamedFileEnt.second == NON_EXISTENT_FILE)
  162. return nullptr;
  163. // Entry exists: return it *unless* it wasn't opened and open is requested.
  164. if (!(NamedFileEnt.second->DeferredOpen && openFile))
  165. return NamedFileEnt.second;
  166. // We previously stat()ed the file, but didn't open it: do that below.
  167. // FIXME: the below does other redundant work too (stats the dir and file).
  168. } else {
  169. // By default, initialize it to invalid.
  170. NamedFileEnt.second = NON_EXISTENT_FILE;
  171. }
  172. ++NumFileCacheMisses;
  173. // Get the null-terminated file name as stored as the key of the
  174. // SeenFileEntries map.
  175. StringRef InterndFileName = NamedFileEnt.first();
  176. // Look up the directory for the file. When looking up something like
  177. // sys/foo.h we'll discover all of the search directories that have a 'sys'
  178. // subdirectory. This will let us avoid having to waste time on known-to-fail
  179. // searches when we go to find sys/bar.h, because all the search directories
  180. // without a 'sys' subdir will get a cached failure result.
  181. const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
  182. CacheFailure);
  183. if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
  184. if (!CacheFailure)
  185. SeenFileEntries.erase(Filename);
  186. return nullptr;
  187. }
  188. // FIXME: Use the directory info to prune this, before doing the stat syscall.
  189. // FIXME: This will reduce the # syscalls.
  190. // Nope, there isn't. Check to see if the file exists.
  191. std::unique_ptr<llvm::vfs::File> F;
  192. FileData Data;
  193. if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) {
  194. // There's no real file at the given path.
  195. if (!CacheFailure)
  196. SeenFileEntries.erase(Filename);
  197. return nullptr;
  198. }
  199. assert((openFile || !F) && "undesired open file");
  200. // It exists. See if we have already opened a file with the same inode.
  201. // This occurs when one dir is symlinked to another, for example.
  202. FileEntry &UFE = UniqueRealFiles[Data.UniqueID];
  203. UFE.DeferredOpen = !openFile;
  204. NamedFileEnt.second = &UFE;
  205. // If the name returned by getStatValue is different than Filename, re-intern
  206. // the name.
  207. if (Data.Name != Filename) {
  208. auto &NamedFileEnt =
  209. *SeenFileEntries.insert(std::make_pair(Data.Name, nullptr)).first;
  210. if (!NamedFileEnt.second)
  211. NamedFileEnt.second = &UFE;
  212. else
  213. assert(NamedFileEnt.second == &UFE &&
  214. "filename from getStatValue() refers to wrong file");
  215. InterndFileName = NamedFileEnt.first().data();
  216. }
  217. // If we opened the file for the first time, record the resulting info.
  218. // Do this even if the cache entry was valid, maybe we didn't previously open.
  219. if (F && !UFE.File) {
  220. if (auto PathName = F->getName())
  221. fillRealPathName(&UFE, *PathName);
  222. UFE.File = std::move(F);
  223. assert(!UFE.DeferredOpen && "we just opened it!");
  224. }
  225. if (UFE.isValid()) { // Already have an entry with this inode, return it.
  226. // FIXME: this hack ensures that if we look up a file by a virtual path in
  227. // the VFS that the getDir() will have the virtual path, even if we found
  228. // the file by a 'real' path first. This is required in order to find a
  229. // module's structure when its headers/module map are mapped in the VFS.
  230. // We should remove this as soon as we can properly support a file having
  231. // multiple names.
  232. if (DirInfo != UFE.Dir && Data.IsVFSMapped)
  233. UFE.Dir = DirInfo;
  234. // Always update the name to use the last name by which a file was accessed.
  235. // FIXME: Neither this nor always using the first name is correct; we want
  236. // to switch towards a design where we return a FileName object that
  237. // encapsulates both the name by which the file was accessed and the
  238. // corresponding FileEntry.
  239. UFE.Name = InterndFileName;
  240. return &UFE;
  241. }
  242. // Otherwise, we don't have this file yet, add it.
  243. UFE.Name = InterndFileName;
  244. UFE.Size = Data.Size;
  245. UFE.ModTime = Data.ModTime;
  246. UFE.Dir = DirInfo;
  247. UFE.UID = NextFileUID++;
  248. UFE.UniqueID = Data.UniqueID;
  249. UFE.IsNamedPipe = Data.IsNamedPipe;
  250. UFE.InPCH = Data.InPCH;
  251. UFE.IsValid = true;
  252. // Note File and DeferredOpen were initialized above.
  253. return &UFE;
  254. }
  255. const FileEntry *
  256. FileManager::getVirtualFile(StringRef Filename, off_t Size,
  257. time_t ModificationTime) {
  258. ++NumFileLookups;
  259. // See if there is already an entry in the map.
  260. auto &NamedFileEnt =
  261. *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
  262. // See if there is already an entry in the map.
  263. if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE)
  264. return NamedFileEnt.second;
  265. ++NumFileCacheMisses;
  266. // By default, initialize it to invalid.
  267. NamedFileEnt.second = NON_EXISTENT_FILE;
  268. addAncestorsAsVirtualDirs(Filename);
  269. FileEntry *UFE = nullptr;
  270. // Now that all ancestors of Filename are in the cache, the
  271. // following call is guaranteed to find the DirectoryEntry from the
  272. // cache.
  273. const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
  274. /*CacheFailure=*/true);
  275. assert(DirInfo &&
  276. "The directory of a virtual file should already be in the cache.");
  277. // Check to see if the file exists. If so, drop the virtual file
  278. FileData Data;
  279. const char *InterndFileName = NamedFileEnt.first().data();
  280. if (getStatValue(InterndFileName, Data, true, nullptr) == 0) {
  281. Data.Size = Size;
  282. Data.ModTime = ModificationTime;
  283. UFE = &UniqueRealFiles[Data.UniqueID];
  284. NamedFileEnt.second = UFE;
  285. // If we had already opened this file, close it now so we don't
  286. // leak the descriptor. We're not going to use the file
  287. // descriptor anyway, since this is a virtual file.
  288. if (UFE->File)
  289. UFE->closeFile();
  290. // If we already have an entry with this inode, return it.
  291. if (UFE->isValid())
  292. return UFE;
  293. UFE->UniqueID = Data.UniqueID;
  294. UFE->IsNamedPipe = Data.IsNamedPipe;
  295. UFE->InPCH = Data.InPCH;
  296. fillRealPathName(UFE, Data.Name);
  297. }
  298. if (!UFE) {
  299. VirtualFileEntries.push_back(llvm::make_unique<FileEntry>());
  300. UFE = VirtualFileEntries.back().get();
  301. NamedFileEnt.second = UFE;
  302. }
  303. UFE->Name = InterndFileName;
  304. UFE->Size = Size;
  305. UFE->ModTime = ModificationTime;
  306. UFE->Dir = DirInfo;
  307. UFE->UID = NextFileUID++;
  308. UFE->IsValid = true;
  309. UFE->File.reset();
  310. UFE->DeferredOpen = false;
  311. return UFE;
  312. }
  313. bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
  314. StringRef pathRef(path.data(), path.size());
  315. if (FileSystemOpts.WorkingDir.empty()
  316. || llvm::sys::path::is_absolute(pathRef))
  317. return false;
  318. SmallString<128> NewPath(FileSystemOpts.WorkingDir);
  319. llvm::sys::path::append(NewPath, pathRef);
  320. path = NewPath;
  321. return true;
  322. }
  323. bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
  324. bool Changed = FixupRelativePath(Path);
  325. if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
  326. FS->makeAbsolute(Path);
  327. Changed = true;
  328. }
  329. return Changed;
  330. }
  331. void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
  332. llvm::SmallString<128> AbsPath(FileName);
  333. // This is not the same as `VFS::getRealPath()`, which resolves symlinks
  334. // but can be very expensive on real file systems.
  335. // FIXME: the semantic of RealPathName is unclear, and the name might be
  336. // misleading. We need to clean up the interface here.
  337. makeAbsolutePath(AbsPath);
  338. llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
  339. UFE->RealPathName = AbsPath.str();
  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, bool isVolatile) {
  372. if (FileSystemOpts.WorkingDir.empty())
  373. return FS->getBufferForFile(Filename, -1, true, isVolatile);
  374. SmallString<128> FilePath(Filename);
  375. FixupRelativePath(FilePath);
  376. return FS->getBufferForFile(FilePath.c_str(), -1, true, isVolatile);
  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<llvm::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. llvm::vfs::Status &Result) {
  396. SmallString<128> FilePath(Path);
  397. FixupRelativePath(FilePath);
  398. llvm::ErrorOr<llvm::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. SmallString<4096> CanonicalNameBuf;
  440. if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
  441. CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
  442. CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
  443. return CanonicalName;
  444. }
  445. void FileManager::PrintStats() const {
  446. llvm::errs() << "\n*** File Manager Stats:\n";
  447. llvm::errs() << UniqueRealFiles.size() << " real files found, "
  448. << UniqueRealDirs.size() << " real dirs found.\n";
  449. llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
  450. << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
  451. llvm::errs() << NumDirLookups << " dir lookups, "
  452. << NumDirCacheMisses << " dir cache misses.\n";
  453. llvm::errs() << NumFileLookups << " file lookups, "
  454. << NumFileCacheMisses << " file cache misses.\n";
  455. //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
  456. }