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