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