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