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