FileManager.cpp revision 6a1f49423baf6fa0358f396f0d926a3263cb5ff9
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/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/llvm-config.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, 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, &FileDescriptor)) {
380    // There's no real file at the given path.
381    if (!CacheFailure)
382      SeenFileEntries.erase(Filename);
383
384    return 0;
385  }
386
387  if (FileDescriptor != -1 && !openFile) {
388    close(FileDescriptor);
389    FileDescriptor = -1;
390  }
391
392  // It exists.  See if we have already opened a file with the same inode.
393  // This occurs when one dir is symlinked to another, for example.
394  FileEntry &UFE = UniqueRealFiles.getFile(InterndFileName, StatBuf);
395
396  NamedFileEnt.setValue(&UFE);
397  if (UFE.getName()) { // Already have an entry with this inode, return it.
398    // If the stat process opened the file, close it to avoid a FD leak.
399    if (FileDescriptor != -1)
400      close(FileDescriptor);
401
402    return &UFE;
403  }
404
405  // Otherwise, we don't have this directory yet, add it.
406  // FIXME: Change the name to be a char* that points back to the
407  // 'SeenFileEntries' key.
408  UFE.Name    = InterndFileName;
409  UFE.Size    = StatBuf.st_size;
410  UFE.ModTime = StatBuf.st_mtime;
411  UFE.Dir     = DirInfo;
412  UFE.UID     = NextFileUID++;
413  UFE.FD      = FileDescriptor;
414  return &UFE;
415}
416
417const FileEntry *
418FileManager::getVirtualFile(StringRef Filename, off_t Size,
419                            time_t ModificationTime) {
420  ++NumFileLookups;
421
422  // See if there is already an entry in the map.
423  llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
424    SeenFileEntries.GetOrCreateValue(Filename);
425
426  // See if there is already an entry in the map.
427  if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
428    return NamedFileEnt.getValue();
429
430  ++NumFileCacheMisses;
431
432  // By default, initialize it to invalid.
433  NamedFileEnt.setValue(NON_EXISTENT_FILE);
434
435  addAncestorsAsVirtualDirs(Filename);
436  FileEntry *UFE = 0;
437
438  // Now that all ancestors of Filename are in the cache, the
439  // following call is guaranteed to find the DirectoryEntry from the
440  // cache.
441  const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
442                                                       /*CacheFailure=*/true);
443  assert(DirInfo &&
444         "The directory of a virtual file should already be in the cache.");
445
446  // Check to see if the file exists. If so, drop the virtual file
447  int FileDescriptor = -1;
448  struct stat StatBuf;
449  const char *InterndFileName = NamedFileEnt.getKeyData();
450  if (getStatValue(InterndFileName, StatBuf, &FileDescriptor) == 0) {
451    // If the stat process opened the file, close it to avoid a FD leak.
452    if (FileDescriptor != -1)
453      close(FileDescriptor);
454
455    StatBuf.st_size = Size;
456    StatBuf.st_mtime = ModificationTime;
457    UFE = &UniqueRealFiles.getFile(InterndFileName, StatBuf);
458
459    NamedFileEnt.setValue(UFE);
460
461    // If we had already opened this file, close it now so we don't
462    // leak the descriptor. We're not going to use the file
463    // descriptor anyway, since this is a virtual file.
464    if (UFE->FD != -1) {
465      close(UFE->FD);
466      UFE->FD = -1;
467    }
468
469    // If we already have an entry with this inode, return it.
470    if (UFE->getName())
471      return UFE;
472  }
473
474  if (!UFE) {
475    UFE = new FileEntry();
476    VirtualFileEntries.push_back(UFE);
477    NamedFileEnt.setValue(UFE);
478  }
479
480  UFE->Name    = InterndFileName;
481  UFE->Size    = Size;
482  UFE->ModTime = ModificationTime;
483  UFE->Dir     = DirInfo;
484  UFE->UID     = NextFileUID++;
485  UFE->FD      = -1;
486  return UFE;
487}
488
489void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
490  StringRef pathRef(path.data(), path.size());
491
492  if (FileSystemOpts.WorkingDir.empty()
493      || llvm::sys::path::is_absolute(pathRef))
494    return;
495
496  SmallString<128> NewPath(FileSystemOpts.WorkingDir);
497  llvm::sys::path::append(NewPath, pathRef);
498  path = NewPath;
499}
500
501llvm::MemoryBuffer *FileManager::
502getBufferForFile(const FileEntry *Entry, std::string *ErrorStr,
503                 bool isVolatile) {
504  OwningPtr<llvm::MemoryBuffer> Result;
505  llvm::error_code ec;
506
507  uint64_t FileSize = Entry->getSize();
508  // If there's a high enough chance that the file have changed since we
509  // got its size, force a stat before opening it.
510  if (isVolatile)
511    FileSize = -1;
512
513  const char *Filename = Entry->getName();
514  // If the file is already open, use the open file descriptor.
515  if (Entry->FD != -1) {
516    ec = llvm::MemoryBuffer::getOpenFile(Entry->FD, Filename, Result, FileSize);
517    if (ErrorStr)
518      *ErrorStr = ec.message();
519
520    close(Entry->FD);
521    Entry->FD = -1;
522    return Result.take();
523  }
524
525  // Otherwise, open the file.
526
527  if (FileSystemOpts.WorkingDir.empty()) {
528    ec = llvm::MemoryBuffer::getFile(Filename, Result, FileSize);
529    if (ec && ErrorStr)
530      *ErrorStr = ec.message();
531    return Result.take();
532  }
533
534  SmallString<128> FilePath(Entry->getName());
535  FixupRelativePath(FilePath);
536  ec = llvm::MemoryBuffer::getFile(FilePath.str(), Result, FileSize);
537  if (ec && ErrorStr)
538    *ErrorStr = ec.message();
539  return Result.take();
540}
541
542llvm::MemoryBuffer *FileManager::
543getBufferForFile(StringRef Filename, std::string *ErrorStr) {
544  OwningPtr<llvm::MemoryBuffer> Result;
545  llvm::error_code ec;
546  if (FileSystemOpts.WorkingDir.empty()) {
547    ec = llvm::MemoryBuffer::getFile(Filename, Result);
548    if (ec && ErrorStr)
549      *ErrorStr = ec.message();
550    return Result.take();
551  }
552
553  SmallString<128> FilePath(Filename);
554  FixupRelativePath(FilePath);
555  ec = llvm::MemoryBuffer::getFile(FilePath.c_str(), Result);
556  if (ec && ErrorStr)
557    *ErrorStr = ec.message();
558  return Result.take();
559}
560
561/// getStatValue - Get the 'stat' information for the specified path,
562/// using the cache to accelerate it if possible.  This returns true
563/// if the path points to a virtual file or does not exist, or returns
564/// false if it's an existent real file.  If FileDescriptor is NULL,
565/// do directory look-up instead of file look-up.
566bool FileManager::getStatValue(const char *Path, struct stat &StatBuf,
567                               int *FileDescriptor) {
568  // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
569  // absolute!
570  if (FileSystemOpts.WorkingDir.empty())
571    return FileSystemStatCache::get(Path, StatBuf, FileDescriptor,
572                                    StatCache.get());
573
574  SmallString<128> FilePath(Path);
575  FixupRelativePath(FilePath);
576
577  return FileSystemStatCache::get(FilePath.c_str(), StatBuf, FileDescriptor,
578                                  StatCache.get());
579}
580
581bool FileManager::getNoncachedStatValue(StringRef Path,
582                                        struct stat &StatBuf) {
583  SmallString<128> FilePath(Path);
584  FixupRelativePath(FilePath);
585
586  return ::stat(FilePath.c_str(), &StatBuf) != 0;
587}
588
589void FileManager::invalidateCache(const FileEntry *Entry) {
590  assert(Entry && "Cannot invalidate a NULL FileEntry");
591
592  SeenFileEntries.erase(Entry->getName());
593
594  // FileEntry invalidation should not block future optimizations in the file
595  // caches. Possible alternatives are cache truncation (invalidate last N) or
596  // invalidation of the whole cache.
597  UniqueRealFiles.erase(Entry);
598}
599
600
601void FileManager::GetUniqueIDMapping(
602                   SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
603  UIDToFiles.clear();
604  UIDToFiles.resize(NextFileUID);
605
606  // Map file entries
607  for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
608         FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
609       FE != FEEnd; ++FE)
610    if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
611      UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
612
613  // Map virtual file entries
614  for (SmallVector<FileEntry*, 4>::const_iterator
615         VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
616       VFE != VFEEnd; ++VFE)
617    if (*VFE && *VFE != NON_EXISTENT_FILE)
618      UIDToFiles[(*VFE)->getUID()] = *VFE;
619}
620
621void FileManager::modifyFileEntry(FileEntry *File,
622                                  off_t Size, time_t ModificationTime) {
623  File->Size = Size;
624  File->ModTime = ModificationTime;
625}
626
627
628void FileManager::PrintStats() const {
629  llvm::errs() << "\n*** File Manager Stats:\n";
630  llvm::errs() << UniqueRealFiles.size() << " real files found, "
631               << UniqueRealDirs.size() << " real dirs found.\n";
632  llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
633               << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
634  llvm::errs() << NumDirLookups << " dir lookups, "
635               << NumDirCacheMisses << " dir cache misses.\n";
636  llvm::errs() << NumFileLookups << " file lookups, "
637               << NumFileCacheMisses << " file cache misses.\n";
638
639  //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
640}
641