FileManager.cpp 19 KB

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