FileManager.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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(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 = 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. /// 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 _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. llvm::SmallString<128> AbsPath(InterndFileName);
  264. // This is not the same as `VFS::getRealPath()`, which resolves symlinks but
  265. // can be very expensive on real file systems.
  266. // FIXME: the semantic of RealPathName is unclear, and the name might be
  267. // misleading. We need to clean up the interface here.
  268. makeAbsolutePath(AbsPath);
  269. llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
  270. UFE.RealPathName = AbsPath.str();
  271. return &UFE;
  272. }
  273. const FileEntry *
  274. FileManager::getVirtualFile(StringRef Filename, off_t Size,
  275. time_t ModificationTime) {
  276. ++NumFileLookups;
  277. // See if there is already an entry in the map.
  278. auto &NamedFileEnt =
  279. *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
  280. // See if there is already an entry in the map.
  281. if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE)
  282. return NamedFileEnt.second;
  283. ++NumFileCacheMisses;
  284. // By default, initialize it to invalid.
  285. NamedFileEnt.second = NON_EXISTENT_FILE;
  286. addAncestorsAsVirtualDirs(Filename);
  287. FileEntry *UFE = nullptr;
  288. // Now that all ancestors of Filename are in the cache, the
  289. // following call is guaranteed to find the DirectoryEntry from the
  290. // cache.
  291. const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
  292. /*CacheFailure=*/true);
  293. assert(DirInfo &&
  294. "The directory of a virtual file should already be in the cache.");
  295. // Check to see if the file exists. If so, drop the virtual file
  296. FileData Data;
  297. const char *InterndFileName = NamedFileEnt.first().data();
  298. if (getStatValue(InterndFileName, Data, true, nullptr) == 0) {
  299. Data.Size = Size;
  300. Data.ModTime = ModificationTime;
  301. UFE = &UniqueRealFiles[Data.UniqueID];
  302. NamedFileEnt.second = UFE;
  303. // If we had already opened this file, close it now so we don't
  304. // leak the descriptor. We're not going to use the file
  305. // descriptor anyway, since this is a virtual file.
  306. if (UFE->File)
  307. UFE->closeFile();
  308. // If we already have an entry with this inode, return it.
  309. if (UFE->isValid())
  310. return UFE;
  311. UFE->UniqueID = Data.UniqueID;
  312. UFE->IsNamedPipe = Data.IsNamedPipe;
  313. UFE->InPCH = Data.InPCH;
  314. }
  315. if (!UFE) {
  316. VirtualFileEntries.push_back(llvm::make_unique<FileEntry>());
  317. UFE = VirtualFileEntries.back().get();
  318. NamedFileEnt.second = UFE;
  319. }
  320. UFE->Name = InterndFileName;
  321. UFE->Size = Size;
  322. UFE->ModTime = ModificationTime;
  323. UFE->Dir = DirInfo;
  324. UFE->UID = NextFileUID++;
  325. UFE->IsValid = true;
  326. UFE->File.reset();
  327. return UFE;
  328. }
  329. bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
  330. StringRef pathRef(path.data(), path.size());
  331. if (FileSystemOpts.WorkingDir.empty()
  332. || llvm::sys::path::is_absolute(pathRef))
  333. return false;
  334. SmallString<128> NewPath(FileSystemOpts.WorkingDir);
  335. llvm::sys::path::append(NewPath, pathRef);
  336. path = NewPath;
  337. return true;
  338. }
  339. bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
  340. bool Changed = FixupRelativePath(Path);
  341. if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
  342. FS->makeAbsolute(Path);
  343. Changed = true;
  344. }
  345. return Changed;
  346. }
  347. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
  348. FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
  349. bool ShouldCloseOpenFile) {
  350. uint64_t FileSize = Entry->getSize();
  351. // If there's a high enough chance that the file have changed since we
  352. // got its size, force a stat before opening it.
  353. if (isVolatile)
  354. FileSize = -1;
  355. StringRef Filename = Entry->getName();
  356. // If the file is already open, use the open file descriptor.
  357. if (Entry->File) {
  358. auto Result =
  359. Entry->File->getBuffer(Filename, FileSize,
  360. /*RequiresNullTerminator=*/true, isVolatile);
  361. // FIXME: we need a set of APIs that can make guarantees about whether a
  362. // FileEntry is open or not.
  363. if (ShouldCloseOpenFile)
  364. Entry->closeFile();
  365. return Result;
  366. }
  367. // Otherwise, open the file.
  368. if (FileSystemOpts.WorkingDir.empty())
  369. return FS->getBufferForFile(Filename, FileSize,
  370. /*RequiresNullTerminator=*/true, isVolatile);
  371. SmallString<128> FilePath(Entry->getName());
  372. FixupRelativePath(FilePath);
  373. return FS->getBufferForFile(FilePath, FileSize,
  374. /*RequiresNullTerminator=*/true, isVolatile);
  375. }
  376. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
  377. FileManager::getBufferForFile(StringRef Filename, bool isVolatile) {
  378. if (FileSystemOpts.WorkingDir.empty())
  379. return FS->getBufferForFile(Filename, -1, true, isVolatile);
  380. SmallString<128> FilePath(Filename);
  381. FixupRelativePath(FilePath);
  382. return FS->getBufferForFile(FilePath.c_str(), -1, true, isVolatile);
  383. }
  384. /// getStatValue - Get the 'stat' information for the specified path,
  385. /// using the cache to accelerate it if possible. This returns true
  386. /// if the path points to a virtual file or does not exist, or returns
  387. /// false if it's an existent real file. If FileDescriptor is NULL,
  388. /// do directory look-up instead of file look-up.
  389. bool FileManager::getStatValue(StringRef Path, FileData &Data, bool isFile,
  390. std::unique_ptr<vfs::File> *F) {
  391. // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
  392. // absolute!
  393. if (FileSystemOpts.WorkingDir.empty())
  394. return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
  395. SmallString<128> FilePath(Path);
  396. FixupRelativePath(FilePath);
  397. return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
  398. StatCache.get(), *FS);
  399. }
  400. bool FileManager::getNoncachedStatValue(StringRef Path,
  401. vfs::Status &Result) {
  402. SmallString<128> FilePath(Path);
  403. FixupRelativePath(FilePath);
  404. llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str());
  405. if (!S)
  406. return true;
  407. Result = *S;
  408. return false;
  409. }
  410. void FileManager::invalidateCache(const FileEntry *Entry) {
  411. assert(Entry && "Cannot invalidate a NULL FileEntry");
  412. SeenFileEntries.erase(Entry->getName());
  413. // FileEntry invalidation should not block future optimizations in the file
  414. // caches. Possible alternatives are cache truncation (invalidate last N) or
  415. // invalidation of the whole cache.
  416. UniqueRealFiles.erase(Entry->getUniqueID());
  417. }
  418. void FileManager::GetUniqueIDMapping(
  419. SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
  420. UIDToFiles.clear();
  421. UIDToFiles.resize(NextFileUID);
  422. // Map file entries
  423. for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
  424. FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
  425. FE != FEEnd; ++FE)
  426. if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
  427. UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
  428. // Map virtual file entries
  429. for (const auto &VFE : VirtualFileEntries)
  430. if (VFE && VFE.get() != NON_EXISTENT_FILE)
  431. UIDToFiles[VFE->getUID()] = VFE.get();
  432. }
  433. void FileManager::modifyFileEntry(FileEntry *File,
  434. off_t Size, time_t ModificationTime) {
  435. File->Size = Size;
  436. File->ModTime = ModificationTime;
  437. }
  438. StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
  439. // FIXME: use llvm::sys::fs::canonical() when it gets implemented
  440. llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
  441. = CanonicalDirNames.find(Dir);
  442. if (Known != CanonicalDirNames.end())
  443. return Known->second;
  444. StringRef CanonicalName(Dir->getName());
  445. SmallString<4096> CanonicalNameBuf;
  446. if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
  447. CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
  448. CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
  449. return CanonicalName;
  450. }
  451. void FileManager::PrintStats() const {
  452. llvm::errs() << "\n*** File Manager Stats:\n";
  453. llvm::errs() << UniqueRealFiles.size() << " real files found, "
  454. << UniqueRealDirs.size() << " real dirs found.\n";
  455. llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
  456. << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
  457. llvm::errs() << NumDirLookups << " dir lookups, "
  458. << NumDirCacheMisses << " dir cache misses.\n";
  459. llvm::errs() << NumFileLookups << " file lookups, "
  460. << NumFileCacheMisses << " file cache misses.\n";
  461. //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
  462. }