FileManager.cpp 19 KB

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