FileManager.cpp 18 KB

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