FileManager.cpp 20 KB

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