FileManager.cpp revision e5d30e3b403539b10aaa52f03875a2243bf88904
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
20#include "clang/Basic/FileManager.h"
21#include "clang/Basic/FileSystemStatCache.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/Config/llvm-config.h"
24#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/MemoryBuffer.h"
26#include "llvm/Support/Path.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/Support/system_error.h"
29#include <map>
30#include <set>
31#include <string>
32
33// FIXME: This is terrible, we need this for ::close.
34#if !defined(_MSC_VER) && !defined(__MINGW32__)
35#include <unistd.h>
36#include <sys/uio.h>
37#else
38#include <io.h>
39#ifndef S_ISFIFO
40#define S_ISFIFO(x) (0)
41#endif
42#endif
43using namespace clang;
44
45// FIXME: Enhance libsystem to support inode and other fields.
46#include <sys/stat.h>
47
48/// NON_EXISTENT_DIR - A special value distinct from null that is used to
49/// represent a dir name that doesn't exist on the disk.
50#define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
51
52/// NON_EXISTENT_FILE - A special value distinct from null that is used to
53/// represent a filename that doesn't exist on the disk.
54#define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
55
56
57FileEntry::~FileEntry() {
58  // If this FileEntry owns an open file descriptor that never got used, close
59  // it.
60  if (FD != -1) ::close(FD);
61}
62
63bool FileEntry::isNamedPipe() const {
64  return S_ISFIFO(FileMode);
65}
66
67//===----------------------------------------------------------------------===//
68// Windows.
69//===----------------------------------------------------------------------===//
70
71#ifdef LLVM_ON_WIN32
72
73namespace {
74  static std::string GetFullPath(const char *relPath) {
75    char *absPathStrPtr = _fullpath(NULL, relPath, 0);
76    assert(absPathStrPtr && "_fullpath() returned NULL!");
77
78    std::string absPath(absPathStrPtr);
79
80    free(absPathStrPtr);
81    return absPath;
82  }
83}
84
85class FileManager::UniqueDirContainer {
86  /// UniqueDirs - Cache from full path to existing directories/files.
87  ///
88  llvm::StringMap<DirectoryEntry> UniqueDirs;
89
90public:
91  /// getDirectory - Return an existing DirectoryEntry with the given
92  /// name if there is already one; otherwise create and return a
93  /// default-constructed DirectoryEntry.
94  DirectoryEntry &getDirectory(const char *Name,
95                               const struct stat & /*StatBuf*/) {
96    std::string FullPath(GetFullPath(Name));
97    return UniqueDirs.GetOrCreateValue(FullPath).getValue();
98  }
99
100  size_t size() const { return UniqueDirs.size(); }
101};
102
103class FileManager::UniqueFileContainer {
104  /// UniqueFiles - Cache from full path to existing directories/files.
105  ///
106  llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;
107
108public:
109  /// getFile - Return an existing FileEntry with the given name if
110  /// there is already one; otherwise create and return a
111  /// default-constructed FileEntry.
112  FileEntry &getFile(const char *Name, const struct stat & /*StatBuf*/) {
113    std::string FullPath(GetFullPath(Name));
114
115    // Lowercase string because Windows filesystem is case insensitive.
116    FullPath = StringRef(FullPath).lower();
117    return UniqueFiles.GetOrCreateValue(FullPath).getValue();
118  }
119
120  size_t size() const { return UniqueFiles.size(); }
121
122  void erase(const FileEntry *Entry) {
123    std::string FullPath(GetFullPath(Entry->getName()));
124
125    // Lowercase string because Windows filesystem is case insensitive.
126    FullPath = StringRef(FullPath).lower();
127    UniqueFiles.erase(FullPath);
128  }
129};
130
131//===----------------------------------------------------------------------===//
132// Unix-like Systems.
133//===----------------------------------------------------------------------===//
134
135#else
136
137class FileManager::UniqueDirContainer {
138  /// UniqueDirs - Cache from ID's to existing directories/files.
139  std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;
140
141public:
142  /// getDirectory - Return an existing DirectoryEntry with the given
143  /// ID's if there is already one; otherwise create and return a
144  /// default-constructed DirectoryEntry.
145  DirectoryEntry &getDirectory(const char * /*Name*/,
146                               const struct stat &StatBuf) {
147    return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
148  }
149
150  size_t size() const { return UniqueDirs.size(); }
151};
152
153class FileManager::UniqueFileContainer {
154  /// UniqueFiles - Cache from ID's to existing directories/files.
155  std::set<FileEntry> UniqueFiles;
156
157public:
158  /// getFile - Return an existing FileEntry with the given ID's if
159  /// there is already one; otherwise create and return a
160  /// default-constructed FileEntry.
161  FileEntry &getFile(const char * /*Name*/, const struct stat &StatBuf) {
162    return
163      const_cast<FileEntry&>(
164                    *UniqueFiles.insert(FileEntry(StatBuf.st_dev,
165                                                  StatBuf.st_ino,
166                                                  StatBuf.st_mode)).first);
167  }
168
169  size_t size() const { return UniqueFiles.size(); }
170
171  void erase(const FileEntry *Entry) { UniqueFiles.erase(*Entry); }
172};
173
174#endif
175
176//===----------------------------------------------------------------------===//
177// Common logic.
178//===----------------------------------------------------------------------===//
179
180FileManager::FileManager(const FileSystemOptions &FSO)
181  : FileSystemOpts(FSO),
182    UniqueRealDirs(*new UniqueDirContainer()),
183    UniqueRealFiles(*new UniqueFileContainer()),
184    SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
185  NumDirLookups = NumFileLookups = 0;
186  NumDirCacheMisses = NumFileCacheMisses = 0;
187}
188
189FileManager::~FileManager() {
190  delete &UniqueRealDirs;
191  delete &UniqueRealFiles;
192  for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
193    delete VirtualFileEntries[i];
194  for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
195    delete VirtualDirectoryEntries[i];
196}
197
198void FileManager::addStatCache(FileSystemStatCache *statCache,
199                               bool AtBeginning) {
200  assert(statCache && "No stat cache provided?");
201  if (AtBeginning || StatCache.get() == 0) {
202    statCache->setNextStatCache(StatCache.take());
203    StatCache.reset(statCache);
204    return;
205  }
206
207  FileSystemStatCache *LastCache = StatCache.get();
208  while (LastCache->getNextStatCache())
209    LastCache = LastCache->getNextStatCache();
210
211  LastCache->setNextStatCache(statCache);
212}
213
214void FileManager::removeStatCache(FileSystemStatCache *statCache) {
215  if (!statCache)
216    return;
217
218  if (StatCache.get() == statCache) {
219    // This is the first stat cache.
220    StatCache.reset(StatCache->takeNextStatCache());
221    return;
222  }
223
224  // Find the stat cache in the list.
225  FileSystemStatCache *PrevCache = StatCache.get();
226  while (PrevCache && PrevCache->getNextStatCache() != statCache)
227    PrevCache = PrevCache->getNextStatCache();
228
229  assert(PrevCache && "Stat cache not found for removal");
230  PrevCache->setNextStatCache(statCache->getNextStatCache());
231}
232
233void FileManager::clearStatCaches() {
234  StatCache.reset(0);
235}
236
237/// \brief Retrieve the directory that the given file name resides in.
238/// Filename can point to either a real file or a virtual file.
239static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
240                                                  StringRef Filename,
241                                                  bool CacheFailure) {
242  if (Filename.empty())
243    return NULL;
244
245  if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
246    return NULL;  // If Filename is a directory.
247
248  StringRef DirName = llvm::sys::path::parent_path(Filename);
249  // Use the current directory if file has no path component.
250  if (DirName.empty())
251    DirName = ".";
252
253  return FileMgr.getDirectory(DirName, CacheFailure);
254}
255
256/// Add all ancestors of the given path (pointing to either a file or
257/// a directory) as virtual directories.
258void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
259  StringRef DirName = llvm::sys::path::parent_path(Path);
260  if (DirName.empty())
261    return;
262
263  llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
264    SeenDirEntries.GetOrCreateValue(DirName);
265
266  // When caching a virtual directory, we always cache its ancestors
267  // at the same time.  Therefore, if DirName is already in the cache,
268  // we don't need to recurse as its ancestors must also already be in
269  // the cache.
270  if (NamedDirEnt.getValue())
271    return;
272
273  // Add the virtual directory to the cache.
274  DirectoryEntry *UDE = new DirectoryEntry;
275  UDE->Name = NamedDirEnt.getKeyData();
276  NamedDirEnt.setValue(UDE);
277  VirtualDirectoryEntries.push_back(UDE);
278
279  // Recursively add the other ancestors.
280  addAncestorsAsVirtualDirs(DirName);
281}
282
283const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
284                                                bool CacheFailure) {
285  // stat doesn't like trailing separators except for root directory.
286  // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
287  // (though it can strip '\\')
288  if (DirName.size() > 1 &&
289      DirName != llvm::sys::path::root_path(DirName) &&
290      llvm::sys::path::is_separator(DirName.back()))
291    DirName = DirName.substr(0, DirName.size()-1);
292
293  ++NumDirLookups;
294  llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
295    SeenDirEntries.GetOrCreateValue(DirName);
296
297  // See if there was already an entry in the map.  Note that the map
298  // contains both virtual and real directories.
299  if (NamedDirEnt.getValue())
300    return NamedDirEnt.getValue() == NON_EXISTENT_DIR
301              ? 0 : NamedDirEnt.getValue();
302
303  ++NumDirCacheMisses;
304
305  // By default, initialize it to invalid.
306  NamedDirEnt.setValue(NON_EXISTENT_DIR);
307
308  // Get the null-terminated directory name as stored as the key of the
309  // SeenDirEntries map.
310  const char *InterndDirName = NamedDirEnt.getKeyData();
311
312  // Check to see if the directory exists.
313  struct stat StatBuf;
314  if (getStatValue(InterndDirName, StatBuf, false, 0/*directory lookup*/)) {
315    // There's no real directory at the given path.
316    if (!CacheFailure)
317      SeenDirEntries.erase(DirName);
318    return 0;
319  }
320
321  // It exists.  See if we have already opened a directory with the
322  // same inode (this occurs on Unix-like systems when one dir is
323  // symlinked to another, for example) or the same path (on
324  // Windows).
325  DirectoryEntry &UDE = UniqueRealDirs.getDirectory(InterndDirName, StatBuf);
326
327  NamedDirEnt.setValue(&UDE);
328  if (!UDE.getName()) {
329    // We don't have this directory yet, add it.  We use the string
330    // key from the SeenDirEntries map as the string.
331    UDE.Name  = InterndDirName;
332  }
333
334  return &UDE;
335}
336
337const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
338                                      bool CacheFailure) {
339  ++NumFileLookups;
340
341  // See if there is already an entry in the map.
342  llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
343    SeenFileEntries.GetOrCreateValue(Filename);
344
345  // See if there is already an entry in the map.
346  if (NamedFileEnt.getValue())
347    return NamedFileEnt.getValue() == NON_EXISTENT_FILE
348                 ? 0 : NamedFileEnt.getValue();
349
350  ++NumFileCacheMisses;
351
352  // By default, initialize it to invalid.
353  NamedFileEnt.setValue(NON_EXISTENT_FILE);
354
355  // Get the null-terminated file name as stored as the key of the
356  // SeenFileEntries map.
357  const char *InterndFileName = NamedFileEnt.getKeyData();
358
359  // Look up the directory for the file.  When looking up something like
360  // sys/foo.h we'll discover all of the search directories that have a 'sys'
361  // subdirectory.  This will let us avoid having to waste time on known-to-fail
362  // searches when we go to find sys/bar.h, because all the search directories
363  // without a 'sys' subdir will get a cached failure result.
364  const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
365                                                       CacheFailure);
366  if (DirInfo == 0) {  // Directory doesn't exist, file can't exist.
367    if (!CacheFailure)
368      SeenFileEntries.erase(Filename);
369
370    return 0;
371  }
372
373  // FIXME: Use the directory info to prune this, before doing the stat syscall.
374  // FIXME: This will reduce the # syscalls.
375
376  // Nope, there isn't.  Check to see if the file exists.
377  int FileDescriptor = -1;
378  struct stat StatBuf;
379  if (getStatValue(InterndFileName, StatBuf, true,
380                   openFile ? &FileDescriptor : 0)) {
381    // There's no real file at the given path.
382    if (!CacheFailure)
383      SeenFileEntries.erase(Filename);
384
385    return 0;
386  }
387
388  if (FileDescriptor != -1 && !openFile) {
389    close(FileDescriptor);
390    FileDescriptor = -1;
391  }
392
393  // It exists.  See if we have already opened a file with the same inode.
394  // This occurs when one dir is symlinked to another, for example.
395  FileEntry &UFE = UniqueRealFiles.getFile(InterndFileName, StatBuf);
396
397  NamedFileEnt.setValue(&UFE);
398  if (UFE.getName()) { // Already have an entry with this inode, return it.
399    // If the stat process opened the file, close it to avoid a FD leak.
400    if (FileDescriptor != -1)
401      close(FileDescriptor);
402
403    return &UFE;
404  }
405
406  // Otherwise, we don't have this directory yet, add it.
407  // FIXME: Change the name to be a char* that points back to the
408  // 'SeenFileEntries' key.
409  UFE.Name    = InterndFileName;
410  UFE.Size    = StatBuf.st_size;
411  UFE.ModTime = StatBuf.st_mtime;
412  UFE.Dir     = DirInfo;
413  UFE.UID     = NextFileUID++;
414  UFE.FD      = FileDescriptor;
415  return &UFE;
416}
417
418const FileEntry *
419FileManager::getVirtualFile(StringRef Filename, off_t Size,
420                            time_t ModificationTime) {
421  ++NumFileLookups;
422
423  // See if there is already an entry in the map.
424  llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
425    SeenFileEntries.GetOrCreateValue(Filename);
426
427  // See if there is already an entry in the map.
428  if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
429    return NamedFileEnt.getValue();
430
431  ++NumFileCacheMisses;
432
433  // By default, initialize it to invalid.
434  NamedFileEnt.setValue(NON_EXISTENT_FILE);
435
436  addAncestorsAsVirtualDirs(Filename);
437  FileEntry *UFE = 0;
438
439  // Now that all ancestors of Filename are in the cache, the
440  // following call is guaranteed to find the DirectoryEntry from the
441  // cache.
442  const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
443                                                       /*CacheFailure=*/true);
444  assert(DirInfo &&
445         "The directory of a virtual file should already be in the cache.");
446
447  // Check to see if the file exists. If so, drop the virtual file
448  struct stat StatBuf;
449  const char *InterndFileName = NamedFileEnt.getKeyData();
450  if (getStatValue(InterndFileName, StatBuf, true, 0) == 0) {
451    StatBuf.st_size = Size;
452    StatBuf.st_mtime = ModificationTime;
453    UFE = &UniqueRealFiles.getFile(InterndFileName, StatBuf);
454
455    NamedFileEnt.setValue(UFE);
456
457    // If we had already opened this file, close it now so we don't
458    // leak the descriptor. We're not going to use the file
459    // descriptor anyway, since this is a virtual file.
460    if (UFE->FD != -1) {
461      close(UFE->FD);
462      UFE->FD = -1;
463    }
464
465    // If we already have an entry with this inode, return it.
466    if (UFE->getName())
467      return UFE;
468  }
469
470  if (!UFE) {
471    UFE = new FileEntry();
472    VirtualFileEntries.push_back(UFE);
473    NamedFileEnt.setValue(UFE);
474  }
475
476  UFE->Name    = InterndFileName;
477  UFE->Size    = Size;
478  UFE->ModTime = ModificationTime;
479  UFE->Dir     = DirInfo;
480  UFE->UID     = NextFileUID++;
481  UFE->FD      = -1;
482  return UFE;
483}
484
485void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
486  StringRef pathRef(path.data(), path.size());
487
488  if (FileSystemOpts.WorkingDir.empty()
489      || llvm::sys::path::is_absolute(pathRef))
490    return;
491
492  SmallString<128> NewPath(FileSystemOpts.WorkingDir);
493  llvm::sys::path::append(NewPath, pathRef);
494  path = NewPath;
495}
496
497llvm::MemoryBuffer *FileManager::
498getBufferForFile(const FileEntry *Entry, std::string *ErrorStr,
499                 bool isVolatile) {
500  OwningPtr<llvm::MemoryBuffer> Result;
501  llvm::error_code ec;
502
503  uint64_t FileSize = Entry->getSize();
504  // If there's a high enough chance that the file have changed since we
505  // got its size, force a stat before opening it.
506  if (isVolatile)
507    FileSize = -1;
508
509  const char *Filename = Entry->getName();
510  // If the file is already open, use the open file descriptor.
511  if (Entry->FD != -1) {
512    ec = llvm::MemoryBuffer::getOpenFile(Entry->FD, Filename, Result, FileSize);
513    if (ErrorStr)
514      *ErrorStr = ec.message();
515
516    close(Entry->FD);
517    Entry->FD = -1;
518    return Result.take();
519  }
520
521  // Otherwise, open the file.
522
523  if (FileSystemOpts.WorkingDir.empty()) {
524    ec = llvm::MemoryBuffer::getFile(Filename, Result, FileSize);
525    if (ec && ErrorStr)
526      *ErrorStr = ec.message();
527    return Result.take();
528  }
529
530  SmallString<128> FilePath(Entry->getName());
531  FixupRelativePath(FilePath);
532  ec = llvm::MemoryBuffer::getFile(FilePath.str(), Result, FileSize);
533  if (ec && ErrorStr)
534    *ErrorStr = ec.message();
535  return Result.take();
536}
537
538llvm::MemoryBuffer *FileManager::
539getBufferForFile(StringRef Filename, std::string *ErrorStr) {
540  OwningPtr<llvm::MemoryBuffer> Result;
541  llvm::error_code ec;
542  if (FileSystemOpts.WorkingDir.empty()) {
543    ec = llvm::MemoryBuffer::getFile(Filename, Result);
544    if (ec && ErrorStr)
545      *ErrorStr = ec.message();
546    return Result.take();
547  }
548
549  SmallString<128> FilePath(Filename);
550  FixupRelativePath(FilePath);
551  ec = llvm::MemoryBuffer::getFile(FilePath.c_str(), Result);
552  if (ec && ErrorStr)
553    *ErrorStr = ec.message();
554  return Result.take();
555}
556
557/// getStatValue - Get the 'stat' information for the specified path,
558/// using the cache to accelerate it if possible.  This returns true
559/// if the path points to a virtual file or does not exist, or returns
560/// false if it's an existent real file.  If FileDescriptor is NULL,
561/// do directory look-up instead of file look-up.
562bool FileManager::getStatValue(const char *Path, struct stat &StatBuf,
563                               bool isFile, int *FileDescriptor) {
564  // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
565  // absolute!
566  if (FileSystemOpts.WorkingDir.empty())
567    return FileSystemStatCache::get(Path, StatBuf, isFile, FileDescriptor,
568                                    StatCache.get());
569
570  SmallString<128> FilePath(Path);
571  FixupRelativePath(FilePath);
572
573  return FileSystemStatCache::get(FilePath.c_str(), StatBuf,
574                                  isFile, FileDescriptor, StatCache.get());
575}
576
577bool FileManager::getNoncachedStatValue(StringRef Path,
578                                        struct stat &StatBuf) {
579  SmallString<128> FilePath(Path);
580  FixupRelativePath(FilePath);
581
582  return ::stat(FilePath.c_str(), &StatBuf) != 0;
583}
584
585void FileManager::invalidateCache(const FileEntry *Entry) {
586  assert(Entry && "Cannot invalidate a NULL FileEntry");
587
588  SeenFileEntries.erase(Entry->getName());
589
590  // FileEntry invalidation should not block future optimizations in the file
591  // caches. Possible alternatives are cache truncation (invalidate last N) or
592  // invalidation of the whole cache.
593  UniqueRealFiles.erase(Entry);
594}
595
596
597void FileManager::GetUniqueIDMapping(
598                   SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
599  UIDToFiles.clear();
600  UIDToFiles.resize(NextFileUID);
601
602  // Map file entries
603  for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
604         FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
605       FE != FEEnd; ++FE)
606    if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
607      UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
608
609  // Map virtual file entries
610  for (SmallVector<FileEntry*, 4>::const_iterator
611         VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
612       VFE != VFEEnd; ++VFE)
613    if (*VFE && *VFE != NON_EXISTENT_FILE)
614      UIDToFiles[(*VFE)->getUID()] = *VFE;
615}
616
617void FileManager::modifyFileEntry(FileEntry *File,
618                                  off_t Size, time_t ModificationTime) {
619  File->Size = Size;
620  File->ModTime = ModificationTime;
621}
622
623
624void FileManager::PrintStats() const {
625  llvm::errs() << "\n*** File Manager Stats:\n";
626  llvm::errs() << UniqueRealFiles.size() << " real files found, "
627               << UniqueRealDirs.size() << " real dirs found.\n";
628  llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
629               << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
630  llvm::errs() << NumDirLookups << " dir lookups, "
631               << NumDirCacheMisses << " dir cache misses.\n";
632  llvm::errs() << NumFileLookups << " file lookups, "
633               << NumFileCacheMisses << " file cache misses.\n";
634
635  //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
636}
637