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 <string>
  29. using namespace clang;
  30. /// NON_EXISTENT_DIR - A special value distinct from null that is used to
  31. /// represent a dir name that doesn't exist on the disk.
  32. #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
  33. /// NON_EXISTENT_FILE - A special value distinct from null that is used to
  34. /// represent a filename that doesn't exist on the disk.
  35. #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
  36. //===----------------------------------------------------------------------===//
  37. // Common logic.
  38. //===----------------------------------------------------------------------===//
  39. FileManager::FileManager(const FileSystemOptions &FSO,
  40. IntrusiveRefCntPtr<vfs::FileSystem> FS)
  41. : FS(FS), FileSystemOpts(FSO),
  42. SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
  43. NumDirLookups = NumFileLookups = 0;
  44. NumDirCacheMisses = NumFileCacheMisses = 0;
  45. // If the caller doesn't provide a virtual file system, just grab the real
  46. // file system.
  47. if (!FS)
  48. this->FS = vfs::getRealFileSystem();
  49. }
  50. FileManager::~FileManager() = default;
  51. void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache,
  52. bool AtBeginning) {
  53. assert(statCache && "No stat cache provided?");
  54. if (AtBeginning || !StatCache.get()) {
  55. statCache->setNextStatCache(std::move(StatCache));
  56. StatCache = std::move(statCache);
  57. return;
  58. }
  59. FileSystemStatCache *LastCache = StatCache.get();
  60. while (LastCache->getNextStatCache())
  61. LastCache = LastCache->getNextStatCache();
  62. LastCache->setNextStatCache(std::move(statCache));
  63. }
  64. void FileManager::removeStatCache(FileSystemStatCache *statCache) {
  65. if (!statCache)
  66. return;
  67. if (StatCache.get() == statCache) {
  68. // This is the first stat cache.
  69. StatCache = StatCache->takeNextStatCache();
  70. return;
  71. }
  72. // Find the stat cache in the list.
  73. FileSystemStatCache *PrevCache = StatCache.get();
  74. while (PrevCache && PrevCache->getNextStatCache() != statCache)
  75. PrevCache = PrevCache->getNextStatCache();
  76. assert(PrevCache && "Stat cache not found for removal");
  77. PrevCache->setNextStatCache(statCache->takeNextStatCache());
  78. }
  79. void FileManager::clearStatCaches() {
  80. StatCache.reset();
  81. }
  82. /// \brief Retrieve the directory that the given file name resides in.
  83. /// Filename can point to either a real file or a virtual file.
  84. static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
  85. StringRef Filename,
  86. bool CacheFailure) {
  87. if (Filename.empty())
  88. return nullptr;
  89. if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
  90. return nullptr; // If Filename is a directory.
  91. StringRef DirName = llvm::sys::path::parent_path(Filename);
  92. // Use the current directory if file has no path component.
  93. if (DirName.empty())
  94. DirName = ".";
  95. return FileMgr.getDirectory(DirName, CacheFailure);
  96. }
  97. /// Add all ancestors of the given path (pointing to either a file or
  98. /// a directory) as virtual directories.
  99. void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
  100. StringRef DirName = llvm::sys::path::parent_path(Path);
  101. if (DirName.empty())
  102. DirName = ".";
  103. auto &NamedDirEnt =
  104. *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
  105. // When caching a virtual directory, we always cache its ancestors
  106. // at the same time. Therefore, if DirName is already in the cache,
  107. // we don't need to recurse as its ancestors must also already be in
  108. // the cache.
  109. if (NamedDirEnt.second && NamedDirEnt.second != NON_EXISTENT_DIR)
  110. return;
  111. // Add the virtual directory to the cache.
  112. auto UDE = llvm::make_unique<DirectoryEntry>();
  113. UDE->Name = NamedDirEnt.first().data();
  114. NamedDirEnt.second = UDE.get();
  115. VirtualDirectoryEntries.push_back(std::move(UDE));
  116. // Recursively add the other ancestors.
  117. addAncestorsAsVirtualDirs(DirName);
  118. }
  119. const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
  120. bool CacheFailure) {
  121. // stat doesn't like trailing separators except for root directory.
  122. // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
  123. // (though it can strip '\\')
  124. if (DirName.size() > 1 &&
  125. DirName != llvm::sys::path::root_path(DirName) &&
  126. llvm::sys::path::is_separator(DirName.back()))
  127. DirName = DirName.substr(0, DirName.size()-1);
  128. #ifdef LLVM_ON_WIN32
  129. // Fixing a problem with "clang C:test.c" on Windows.
  130. // Stat("C:") does not recognize "C:" as a valid directory
  131. std::string DirNameStr;
  132. if (DirName.size() > 1 && DirName.back() == ':' &&
  133. DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
  134. DirNameStr = DirName.str() + '.';
  135. DirName = DirNameStr;
  136. }
  137. #endif
  138. ++NumDirLookups;
  139. auto &NamedDirEnt =
  140. *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
  141. // See if there was already an entry in the map. Note that the map
  142. // contains both virtual and real directories.
  143. if (NamedDirEnt.second)
  144. return NamedDirEnt.second == NON_EXISTENT_DIR ? nullptr
  145. : NamedDirEnt.second;
  146. ++NumDirCacheMisses;
  147. // By default, initialize it to invalid.
  148. NamedDirEnt.second = NON_EXISTENT_DIR;
  149. // Get the null-terminated directory name as stored as the key of the
  150. // SeenDirEntries map.
  151. const char *InterndDirName = NamedDirEnt.first().data();
  152. // Check to see if the directory exists.
  153. FileData Data;
  154. if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) {
  155. // There's no real directory at the given path.
  156. if (!CacheFailure)
  157. SeenDirEntries.erase(DirName);
  158. return nullptr;
  159. }
  160. // It exists. See if we have already opened a directory with the
  161. // same inode (this occurs on Unix-like systems when one dir is
  162. // symlinked to another, for example) or the same path (on
  163. // Windows).
  164. DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID];
  165. NamedDirEnt.second = &UDE;
  166. if (!UDE.getName()) {
  167. // We don't have this directory yet, add it. We use the string
  168. // key from the SeenDirEntries map as the string.
  169. UDE.Name = InterndDirName;
  170. }
  171. return &UDE;
  172. }
  173. const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
  174. bool CacheFailure) {
  175. ++NumFileLookups;
  176. // See if there is already an entry in the map.
  177. auto &NamedFileEnt =
  178. *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
  179. // See if there is already an entry in the map.
  180. if (NamedFileEnt.second)
  181. return NamedFileEnt.second == NON_EXISTENT_FILE ? nullptr
  182. : NamedFileEnt.second;
  183. ++NumFileCacheMisses;
  184. // By default, initialize it to invalid.
  185. NamedFileEnt.second = NON_EXISTENT_FILE;
  186. // Get the null-terminated file name as stored as the key of the
  187. // SeenFileEntries map.
  188. const char *InterndFileName = NamedFileEnt.first().data();
  189. // Look up the directory for the file. When looking up something like
  190. // sys/foo.h we'll discover all of the search directories that have a 'sys'
  191. // subdirectory. This will let us avoid having to waste time on known-to-fail
  192. // searches when we go to find sys/bar.h, because all the search directories
  193. // without a 'sys' subdir will get a cached failure result.
  194. const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
  195. CacheFailure);
  196. if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
  197. if (!CacheFailure)
  198. SeenFileEntries.erase(Filename);
  199. return nullptr;
  200. }
  201. // FIXME: Use the directory info to prune this, before doing the stat syscall.
  202. // FIXME: This will reduce the # syscalls.
  203. // Nope, there isn't. Check to see if the file exists.
  204. std::unique_ptr<vfs::File> F;
  205. FileData Data;
  206. if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) {
  207. // There's no real file at the given path.
  208. if (!CacheFailure)
  209. SeenFileEntries.erase(Filename);
  210. return nullptr;
  211. }
  212. assert((openFile || !F) && "undesired open file");
  213. // It exists. See if we have already opened a file with the same inode.
  214. // This occurs when one dir is symlinked to another, for example.
  215. FileEntry &UFE = UniqueRealFiles[Data.UniqueID];
  216. NamedFileEnt.second = &UFE;
  217. // If the name returned by getStatValue is different than Filename, re-intern
  218. // the name.
  219. if (Data.Name != Filename) {
  220. auto &NamedFileEnt =
  221. *SeenFileEntries.insert(std::make_pair(Data.Name, nullptr)).first;
  222. if (!NamedFileEnt.second)
  223. NamedFileEnt.second = &UFE;
  224. else
  225. assert(NamedFileEnt.second == &UFE &&
  226. "filename from getStatValue() refers to wrong file");
  227. InterndFileName = NamedFileEnt.first().data();
  228. }
  229. if (UFE.isValid()) { // Already have an entry with this inode, return it.
  230. // FIXME: this hack ensures that if we look up a file by a virtual path in
  231. // the VFS that the getDir() will have the virtual path, even if we found
  232. // the file by a 'real' path first. This is required in order to find a
  233. // module's structure when its headers/module map are mapped in the VFS.
  234. // We should remove this as soon as we can properly support a file having
  235. // multiple names.
  236. if (DirInfo != UFE.Dir && Data.IsVFSMapped)
  237. UFE.Dir = DirInfo;
  238. // Always update the name to use the last name by which a file was accessed.
  239. // FIXME: Neither this nor always using the first name is correct; we want
  240. // to switch towards a design where we return a FileName object that
  241. // encapsulates both the name by which the file was accessed and the
  242. // corresponding FileEntry.
  243. UFE.Name = InterndFileName;
  244. return &UFE;
  245. }
  246. // Otherwise, we don't have this file yet, add it.
  247. UFE.Name = InterndFileName;
  248. UFE.Size = Data.Size;
  249. UFE.ModTime = Data.ModTime;
  250. UFE.Dir = DirInfo;
  251. UFE.UID = NextFileUID++;
  252. UFE.UniqueID = Data.UniqueID;
  253. UFE.IsNamedPipe = Data.IsNamedPipe;
  254. UFE.InPCH = Data.InPCH;
  255. UFE.File = std::move(F);
  256. UFE.IsValid = true;
  257. if (UFE.File)
  258. if (auto RealPathName = UFE.File->getName())
  259. UFE.RealPathName = *RealPathName;
  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. }