FileManager.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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/ADT/StringExtras.h"
  23. #include "llvm/Support/FileSystem.h"
  24. #include "llvm/Support/MemoryBuffer.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include "llvm/Support/Path.h"
  27. #include "llvm/Support/system_error.h"
  28. #include "llvm/Config/config.h"
  29. #include <map>
  30. #include <set>
  31. #include <string>
  32. // FIXME: This is terrible, we need this for ::close.
  33. #if !defined(_MSC_VER) && !defined(__MINGW32__)
  34. #include <unistd.h>
  35. #include <sys/uio.h>
  36. #else
  37. #include <io.h>
  38. #endif
  39. using namespace clang;
  40. // FIXME: Enhance libsystem to support inode and other fields.
  41. #include <sys/stat.h>
  42. /// NON_EXISTENT_DIR - A special value distinct from null that is used to
  43. /// represent a dir name that doesn't exist on the disk.
  44. #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
  45. /// NON_EXISTENT_FILE - A special value distinct from null that is used to
  46. /// represent a filename that doesn't exist on the disk.
  47. #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
  48. FileEntry::~FileEntry() {
  49. // If this FileEntry owns an open file descriptor that never got used, close
  50. // it.
  51. if (FD != -1) ::close(FD);
  52. }
  53. //===----------------------------------------------------------------------===//
  54. // Windows.
  55. //===----------------------------------------------------------------------===//
  56. #ifdef LLVM_ON_WIN32
  57. #define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/' || (x) == '\\')
  58. namespace {
  59. static std::string GetFullPath(const char *relPath) {
  60. char *absPathStrPtr = _fullpath(NULL, relPath, 0);
  61. assert(absPathStrPtr && "_fullpath() returned NULL!");
  62. std::string absPath(absPathStrPtr);
  63. free(absPathStrPtr);
  64. return absPath;
  65. }
  66. }
  67. class FileManager::UniqueDirContainer {
  68. /// UniqueDirs - Cache from full path to existing directories/files.
  69. ///
  70. llvm::StringMap<DirectoryEntry> UniqueDirs;
  71. public:
  72. DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) {
  73. std::string FullPath(GetFullPath(Name));
  74. return UniqueDirs.GetOrCreateValue(FullPath).getValue();
  75. }
  76. size_t size() const { return UniqueDirs.size(); }
  77. };
  78. class FileManager::UniqueFileContainer {
  79. /// UniqueFiles - Cache from full path to existing directories/files.
  80. ///
  81. llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;
  82. public:
  83. FileEntry &getFile(const char *Name, struct stat &StatBuf) {
  84. std::string FullPath(GetFullPath(Name));
  85. // LowercaseString because Windows filesystem is case insensitive.
  86. FullPath = llvm::LowercaseString(FullPath);
  87. return UniqueFiles.GetOrCreateValue(FullPath).getValue();
  88. }
  89. size_t size() const { return UniqueFiles.size(); }
  90. };
  91. //===----------------------------------------------------------------------===//
  92. // Unix-like Systems.
  93. //===----------------------------------------------------------------------===//
  94. #else
  95. #define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/')
  96. class FileManager::UniqueDirContainer {
  97. /// UniqueDirs - Cache from ID's to existing directories/files.
  98. std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;
  99. public:
  100. DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) {
  101. return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
  102. }
  103. size_t size() const { return UniqueDirs.size(); }
  104. };
  105. class FileManager::UniqueFileContainer {
  106. /// UniqueFiles - Cache from ID's to existing directories/files.
  107. std::set<FileEntry> UniqueFiles;
  108. public:
  109. FileEntry &getFile(const char *Name, struct stat &StatBuf) {
  110. return
  111. const_cast<FileEntry&>(
  112. *UniqueFiles.insert(FileEntry(StatBuf.st_dev,
  113. StatBuf.st_ino,
  114. StatBuf.st_mode)).first);
  115. }
  116. size_t size() const { return UniqueFiles.size(); }
  117. };
  118. #endif
  119. //===----------------------------------------------------------------------===//
  120. // Common logic.
  121. //===----------------------------------------------------------------------===//
  122. FileManager::FileManager(const FileSystemOptions &FSO)
  123. : FileSystemOpts(FSO),
  124. UniqueDirs(*new UniqueDirContainer()),
  125. UniqueFiles(*new UniqueFileContainer()),
  126. DirEntries(64), FileEntries(64), NextFileUID(0) {
  127. NumDirLookups = NumFileLookups = 0;
  128. NumDirCacheMisses = NumFileCacheMisses = 0;
  129. }
  130. FileManager::~FileManager() {
  131. delete &UniqueDirs;
  132. delete &UniqueFiles;
  133. for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
  134. delete VirtualFileEntries[i];
  135. }
  136. void FileManager::addStatCache(FileSystemStatCache *statCache,
  137. bool AtBeginning) {
  138. assert(statCache && "No stat cache provided?");
  139. if (AtBeginning || StatCache.get() == 0) {
  140. statCache->setNextStatCache(StatCache.take());
  141. StatCache.reset(statCache);
  142. return;
  143. }
  144. FileSystemStatCache *LastCache = StatCache.get();
  145. while (LastCache->getNextStatCache())
  146. LastCache = LastCache->getNextStatCache();
  147. LastCache->setNextStatCache(statCache);
  148. }
  149. void FileManager::removeStatCache(FileSystemStatCache *statCache) {
  150. if (!statCache)
  151. return;
  152. if (StatCache.get() == statCache) {
  153. // This is the first stat cache.
  154. StatCache.reset(StatCache->takeNextStatCache());
  155. return;
  156. }
  157. // Find the stat cache in the list.
  158. FileSystemStatCache *PrevCache = StatCache.get();
  159. while (PrevCache && PrevCache->getNextStatCache() != statCache)
  160. PrevCache = PrevCache->getNextStatCache();
  161. assert(PrevCache && "Stat cache not found for removal");
  162. PrevCache->setNextStatCache(statCache->getNextStatCache());
  163. }
  164. /// \brief Retrieve the directory that the given file name resides in.
  165. static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
  166. llvm::StringRef Filename) {
  167. // Figure out what directory it is in. If the string contains a / in it,
  168. // strip off everything after it.
  169. // FIXME: this logic should be in sys::Path.
  170. size_t SlashPos = Filename.size();
  171. while (SlashPos != 0 && !IS_DIR_SEPARATOR_CHAR(Filename[SlashPos-1]))
  172. --SlashPos;
  173. // Use the current directory if file has no path component.
  174. if (SlashPos == 0)
  175. return FileMgr.getDirectory(".");
  176. if (SlashPos == Filename.size()-1)
  177. return 0; // If filename ends with a /, it's a directory.
  178. // Ignore repeated //'s.
  179. while (SlashPos != 0 && IS_DIR_SEPARATOR_CHAR(Filename[SlashPos-1]))
  180. --SlashPos;
  181. return FileMgr.getDirectory(Filename.substr(0, SlashPos));
  182. }
  183. /// getDirectory - Lookup, cache, and verify the specified directory. This
  184. /// returns null if the directory doesn't exist.
  185. ///
  186. const DirectoryEntry *FileManager::getDirectory(llvm::StringRef Filename) {
  187. // stat doesn't like trailing separators (at least on Windows).
  188. if (Filename.size() > 1 && IS_DIR_SEPARATOR_CHAR(Filename.back()))
  189. Filename = Filename.substr(0, Filename.size()-1);
  190. ++NumDirLookups;
  191. llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
  192. DirEntries.GetOrCreateValue(Filename);
  193. // See if there is already an entry in the map.
  194. if (NamedDirEnt.getValue())
  195. return NamedDirEnt.getValue() == NON_EXISTENT_DIR
  196. ? 0 : NamedDirEnt.getValue();
  197. ++NumDirCacheMisses;
  198. // By default, initialize it to invalid.
  199. NamedDirEnt.setValue(NON_EXISTENT_DIR);
  200. // Get the null-terminated directory name as stored as the key of the
  201. // DirEntries map.
  202. const char *InterndDirName = NamedDirEnt.getKeyData();
  203. // Check to see if the directory exists.
  204. struct stat StatBuf;
  205. if (getStatValue(InterndDirName, StatBuf, 0/*directory lookup*/))
  206. return 0;
  207. // It exists. See if we have already opened a directory with the same inode.
  208. // This occurs when one dir is symlinked to another, for example.
  209. DirectoryEntry &UDE = UniqueDirs.getDirectory(InterndDirName, StatBuf);
  210. NamedDirEnt.setValue(&UDE);
  211. if (UDE.getName()) // Already have an entry with this inode, return it.
  212. return &UDE;
  213. // Otherwise, we don't have this directory yet, add it. We use the string
  214. // key from the DirEntries map as the string.
  215. UDE.Name = InterndDirName;
  216. return &UDE;
  217. }
  218. /// \brief Canonicalize a file or path name by eliminating redundant
  219. /// "foo/.." and "./" path components.
  220. ///
  221. /// Uses the given scratch space to store the resulting string, if needed.
  222. static llvm::StringRef CanonicalizeFileName(llvm::StringRef Filename,
  223. llvm::SmallVectorImpl<char> &Scratch) {
  224. size_t Start = 0;
  225. bool Changed = false;
  226. do {
  227. size_t FirstSlash = Filename.find('/', Start);
  228. if (FirstSlash == llvm::StringRef::npos) {
  229. // No more components. Just copy the rest of the file name, if
  230. // we need to.
  231. if (Changed)
  232. Scratch.append(Filename.begin() + Start, Filename.end());
  233. break;
  234. }
  235. if (Start + 1 == FirstSlash && Filename[Start] == '.') {
  236. // We have './'; remove it.
  237. // If we haven't changed anything previously, copy the
  238. // starting bits here.
  239. if (!Changed) {
  240. Scratch.clear();
  241. Scratch.append(Filename.begin(), Filename.begin() + Start);
  242. Changed = true;
  243. }
  244. // Skip over the './'.
  245. Start = FirstSlash + 1;
  246. continue;
  247. }
  248. size_t SecondSlash = Filename.find('/', FirstSlash + 1);
  249. if (SecondSlash != llvm::StringRef::npos &&
  250. SecondSlash - FirstSlash == 3 &&
  251. Filename[FirstSlash + 1] == '.' &&
  252. Filename[FirstSlash + 2] == '.') {
  253. // We have 'foo/../'; remove it.
  254. // If we haven't changed anything previously, copy the
  255. // starting bits here.
  256. if (!Changed) {
  257. Scratch.clear();
  258. Scratch.append(Filename.begin(), Filename.begin() + Start);
  259. Changed = true;
  260. }
  261. // Skip over the 'foo/..'.
  262. Start = SecondSlash + 1;
  263. continue;
  264. }
  265. if (Changed)
  266. Scratch.append(Filename.begin() + Start,
  267. Filename.begin() + FirstSlash + 1);
  268. Start = FirstSlash + 1;
  269. } while (true);
  270. if (Changed) {
  271. #if 0
  272. llvm::errs() << "Canonicalized \"" << Filename << "\" to \""
  273. << llvm::StringRef(Scratch.data(), Scratch.size()) << "\"\n";
  274. #endif
  275. return llvm::StringRef(Scratch.data(), Scratch.size());
  276. }
  277. return Filename;
  278. }
  279. /// getFile - Lookup, cache, and verify the specified file. This returns null
  280. /// if the file doesn't exist.
  281. ///
  282. const FileEntry *FileManager::getFile(llvm::StringRef Filename) {
  283. llvm::SmallString<128> FilenameScratch;
  284. Filename = CanonicalizeFileName(Filename, FilenameScratch);
  285. ++NumFileLookups;
  286. // See if there is already an entry in the map.
  287. llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
  288. FileEntries.GetOrCreateValue(Filename);
  289. // See if there is already an entry in the map.
  290. if (NamedFileEnt.getValue())
  291. return NamedFileEnt.getValue() == NON_EXISTENT_FILE
  292. ? 0 : NamedFileEnt.getValue();
  293. ++NumFileCacheMisses;
  294. // By default, initialize it to invalid.
  295. NamedFileEnt.setValue(NON_EXISTENT_FILE);
  296. // Get the null-terminated file name as stored as the key of the
  297. // FileEntries map.
  298. const char *InterndFileName = NamedFileEnt.getKeyData();
  299. // Look up the directory for the file. When looking up something like
  300. // sys/foo.h we'll discover all of the search directories that have a 'sys'
  301. // subdirectory. This will let us avoid having to waste time on known-to-fail
  302. // searches when we go to find sys/bar.h, because all the search directories
  303. // without a 'sys' subdir will get a cached failure result.
  304. const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename);
  305. if (DirInfo == 0) // Directory doesn't exist, file can't exist.
  306. return 0;
  307. // FIXME: Use the directory info to prune this, before doing the stat syscall.
  308. // FIXME: This will reduce the # syscalls.
  309. // Nope, there isn't. Check to see if the file exists.
  310. int FileDescriptor = -1;
  311. struct stat StatBuf;
  312. if (getStatValue(InterndFileName, StatBuf, &FileDescriptor))
  313. return 0;
  314. // It exists. See if we have already opened a file with the same inode.
  315. // This occurs when one dir is symlinked to another, for example.
  316. FileEntry &UFE = UniqueFiles.getFile(InterndFileName, StatBuf);
  317. NamedFileEnt.setValue(&UFE);
  318. if (UFE.getName()) { // Already have an entry with this inode, return it.
  319. // If the stat process opened the file, close it to avoid a FD leak.
  320. if (FileDescriptor != -1)
  321. close(FileDescriptor);
  322. return &UFE;
  323. }
  324. // Otherwise, we don't have this directory yet, add it.
  325. // FIXME: Change the name to be a char* that points back to the 'FileEntries'
  326. // key.
  327. UFE.Name = InterndFileName;
  328. UFE.Size = StatBuf.st_size;
  329. UFE.ModTime = StatBuf.st_mtime;
  330. UFE.Dir = DirInfo;
  331. UFE.UID = NextFileUID++;
  332. UFE.FD = FileDescriptor;
  333. return &UFE;
  334. }
  335. const FileEntry *
  336. FileManager::getVirtualFile(llvm::StringRef Filename, off_t Size,
  337. time_t ModificationTime) {
  338. llvm::SmallString<128> FilenameScratch;
  339. Filename = CanonicalizeFileName(Filename, FilenameScratch);
  340. ++NumFileLookups;
  341. // See if there is already an entry in the map.
  342. llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
  343. FileEntries.GetOrCreateValue(Filename);
  344. // See if there is already an entry in the map.
  345. if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
  346. return NamedFileEnt.getValue();
  347. ++NumFileCacheMisses;
  348. // By default, initialize it to invalid.
  349. NamedFileEnt.setValue(NON_EXISTENT_FILE);
  350. // We allow the directory to not exist. If it does exist we store it.
  351. //
  352. const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename);
  353. FileEntry *UFE = new FileEntry();
  354. VirtualFileEntries.push_back(UFE);
  355. NamedFileEnt.setValue(UFE);
  356. // Get the null-terminated file name as stored as the key of the
  357. // FileEntries map.
  358. const char *InterndFileName = NamedFileEnt.getKeyData();
  359. UFE->Name = InterndFileName;
  360. UFE->Size = Size;
  361. UFE->ModTime = ModificationTime;
  362. UFE->Dir = DirInfo;
  363. UFE->UID = NextFileUID++;
  364. // If this virtual file resolves to a file, also map that file to the
  365. // newly-created file entry.
  366. int FileDescriptor = -1;
  367. struct stat StatBuf;
  368. if (getStatValue(InterndFileName, StatBuf, &FileDescriptor)) {
  369. // If the stat process opened the file, close it to avoid a FD leak.
  370. if (FileDescriptor != -1)
  371. close(FileDescriptor);
  372. return UFE;
  373. }
  374. UFE->FD = FileDescriptor;
  375. llvm::SmallString<128> FilePath(UFE->Name);
  376. llvm::sys::fs::make_absolute(FilePath);
  377. FileEntries[FilePath] = UFE;
  378. return UFE;
  379. }
  380. void FileManager::FixupRelativePath(llvm::sys::Path &path,
  381. const FileSystemOptions &FSOpts) {
  382. if (FSOpts.WorkingDir.empty() || llvm::sys::path::is_absolute(path.str()))
  383. return;
  384. llvm::SmallString<128> NewPath(FSOpts.WorkingDir);
  385. llvm::sys::path::append(NewPath, path.str());
  386. path = NewPath;
  387. }
  388. llvm::MemoryBuffer *FileManager::
  389. getBufferForFile(const FileEntry *Entry, std::string *ErrorStr) {
  390. llvm::OwningPtr<llvm::MemoryBuffer> Result;
  391. llvm::error_code ec;
  392. if (FileSystemOpts.WorkingDir.empty()) {
  393. const char *Filename = Entry->getName();
  394. // If the file is already open, use the open file descriptor.
  395. if (Entry->FD != -1) {
  396. ec = llvm::MemoryBuffer::getOpenFile(Entry->FD, Filename, Result,
  397. Entry->getSize());
  398. if (ErrorStr)
  399. *ErrorStr = ec.message();
  400. // getOpenFile will have closed the file descriptor, don't reuse or
  401. // reclose it.
  402. Entry->FD = -1;
  403. return Result.take();
  404. }
  405. // Otherwise, open the file.
  406. ec = llvm::MemoryBuffer::getFile(Filename, Result, Entry->getSize());
  407. if (ec && ErrorStr)
  408. *ErrorStr = ec.message();
  409. return Result.take();
  410. }
  411. llvm::sys::Path FilePath(Entry->getName());
  412. FixupRelativePath(FilePath, FileSystemOpts);
  413. ec = llvm::MemoryBuffer::getFile(FilePath.c_str(), Result, Entry->getSize());
  414. if (ec && ErrorStr)
  415. *ErrorStr = ec.message();
  416. return Result.take();
  417. }
  418. llvm::MemoryBuffer *FileManager::
  419. getBufferForFile(llvm::StringRef Filename, std::string *ErrorStr) {
  420. llvm::OwningPtr<llvm::MemoryBuffer> Result;
  421. llvm::error_code ec;
  422. if (FileSystemOpts.WorkingDir.empty()) {
  423. ec = llvm::MemoryBuffer::getFile(Filename, Result);
  424. if (ec && ErrorStr)
  425. *ErrorStr = ec.message();
  426. return Result.take();
  427. }
  428. llvm::sys::Path FilePath(Filename);
  429. FixupRelativePath(FilePath, FileSystemOpts);
  430. ec = llvm::MemoryBuffer::getFile(FilePath.c_str(), Result);
  431. if (ec && ErrorStr)
  432. *ErrorStr = ec.message();
  433. return Result.take();
  434. }
  435. /// getStatValue - Get the 'stat' information for the specified path, using the
  436. /// cache to accelerate it if possible. This returns true if the path does not
  437. /// exist or false if it exists.
  438. ///
  439. /// The isForDir member indicates whether this is a directory lookup or not.
  440. /// This will return failure if the lookup isn't the expected kind.
  441. bool FileManager::getStatValue(const char *Path, struct stat &StatBuf,
  442. int *FileDescriptor) {
  443. // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
  444. // absolute!
  445. if (FileSystemOpts.WorkingDir.empty())
  446. return FileSystemStatCache::get(Path, StatBuf, FileDescriptor,
  447. StatCache.get());
  448. llvm::sys::Path FilePath(Path);
  449. FixupRelativePath(FilePath, FileSystemOpts);
  450. return FileSystemStatCache::get(FilePath.c_str(), StatBuf, FileDescriptor,
  451. StatCache.get());
  452. }
  453. void FileManager::PrintStats() const {
  454. llvm::errs() << "\n*** File Manager Stats:\n";
  455. llvm::errs() << UniqueFiles.size() << " files found, "
  456. << UniqueDirs.size() << " dirs found.\n";
  457. llvm::errs() << NumDirLookups << " dir lookups, "
  458. << NumDirCacheMisses << " dir cache misses.\n";
  459. llvm::errs() << NumFileLookups << " file lookups, "
  460. << NumFileCacheMisses << " file cache misses.\n";
  461. //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
  462. }