]> granicus.if.org Git - clang/blob - include/clang/Basic/FileManager.h
Reapply r202420 hopefully fixed for other STLs
[clang] / include / clang / Basic / FileManager.h
1 //===--- FileManager.h - File System Probing and Caching --------*- C++ -*-===//
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 /// \file
11 /// \brief Defines the clang::FileManager interface and associated types.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CLANG_FILEMANAGER_H
16 #define LLVM_CLANG_FILEMANAGER_H
17
18 #include "clang/Basic/FileSystemOptions.h"
19 #include "clang/Basic/LLVM.h"
20 #include "clang/Basic/VirtualFileSystem.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/IntrusiveRefCntPtr.h"
23 #include "llvm/ADT/OwningPtr.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/Support/Allocator.h"
28 // FIXME: Enhance libsystem to support inode and other fields in stat.
29 #include <sys/types.h>
30 #include <map>
31
32 #ifdef _MSC_VER
33 typedef unsigned short mode_t;
34 #endif
35
36 struct stat;
37
38 namespace llvm {
39 class MemoryBuffer;
40 }
41
42 namespace clang {
43 class FileManager;
44 class FileSystemStatCache;
45
46 /// \brief Cached information about one directory (either on disk or in
47 /// the virtual file system).
48 class DirectoryEntry {
49   const char *Name;   // Name of the directory.
50   friend class FileManager;
51 public:
52   DirectoryEntry() : Name(0) {}
53   const char *getName() const { return Name; }
54 };
55
56 /// \brief Cached information about one file (either on disk
57 /// or in the virtual file system).
58 ///
59 /// If the 'File' member is valid, then this FileEntry has an open file
60 /// descriptor for the file.
61 class FileEntry {
62   const char *Name;           // Name of the file.
63   off_t Size;                 // File size in bytes.
64   time_t ModTime;             // Modification time of file.
65   const DirectoryEntry *Dir;  // Directory file lives in.
66   unsigned UID;               // A unique (small) ID for the file.
67   llvm::sys::fs::UniqueID UniqueID;
68   bool IsNamedPipe;
69   bool InPCH;
70   bool IsValid;               // Is this \c FileEntry initialized and valid?
71
72   /// \brief The open file, if it is owned by the \p FileEntry.
73   mutable OwningPtr<vfs::File> File;
74   friend class FileManager;
75
76   void closeFile() const {
77     File.reset(0); // rely on destructor to close File
78   }
79
80   void operator=(const FileEntry &) LLVM_DELETED_FUNCTION;
81
82 public:
83   FileEntry()
84       : Name(0), UniqueID(0, 0), IsNamedPipe(false), InPCH(false),
85         IsValid(false)
86   {}
87
88   // FIXME: this is here to allow putting FileEntry in std::map.  Once we have
89   // emplace, we shouldn't need a copy constructor anymore.
90   FileEntry(const FileEntry &FE) {
91     memcpy(this, &FE, sizeof(FE));
92     assert(!isValid() && "Cannot copy an initialized FileEntry");
93   }
94
95   const char *getName() const { return Name; }
96   bool isValid() const { return IsValid; }
97   off_t getSize() const { return Size; }
98   unsigned getUID() const { return UID; }
99   const llvm::sys::fs::UniqueID &getUniqueID() const { return UniqueID; }
100   bool isInPCH() const { return InPCH; }
101   time_t getModificationTime() const { return ModTime; }
102
103   /// \brief Return the directory the file lives in.
104   const DirectoryEntry *getDir() const { return Dir; }
105
106   bool operator<(const FileEntry &RHS) const { return UniqueID < RHS.UniqueID; }
107
108   /// \brief Check whether the file is a named pipe (and thus can't be opened by
109   /// the native FileManager methods).
110   bool isNamedPipe() const { return IsNamedPipe; }
111 };
112
113 struct FileData;
114
115 /// \brief Implements support for file system lookup, file system caching,
116 /// and directory search management.
117 ///
118 /// This also handles more advanced properties, such as uniquing files based
119 /// on "inode", so that a file with two names (e.g. symlinked) will be treated
120 /// as a single file.
121 ///
122 class FileManager : public RefCountedBase<FileManager> {
123   IntrusiveRefCntPtr<vfs::FileSystem> FS;
124   FileSystemOptions FileSystemOpts;
125
126   /// \brief Cache for existing real directories.
127   std::map<llvm::sys::fs::UniqueID, DirectoryEntry> UniqueRealDirs;
128
129   /// \brief Cache for existing real files.
130   std::map<llvm::sys::fs::UniqueID, FileEntry> UniqueRealFiles;
131
132   /// \brief The virtual directories that we have allocated.
133   ///
134   /// For each virtual file (e.g. foo/bar/baz.cpp), we add all of its parent
135   /// directories (foo/ and foo/bar/) here.
136   SmallVector<DirectoryEntry*, 4> VirtualDirectoryEntries;
137   /// \brief The virtual files that we have allocated.
138   SmallVector<FileEntry*, 4> VirtualFileEntries;
139
140   /// \brief A cache that maps paths to directory entries (either real or
141   /// virtual) we have looked up
142   ///
143   /// The actual Entries for real directories/files are
144   /// owned by UniqueRealDirs/UniqueRealFiles above, while the Entries
145   /// for virtual directories/files are owned by
146   /// VirtualDirectoryEntries/VirtualFileEntries above.
147   ///
148   llvm::StringMap<DirectoryEntry*, llvm::BumpPtrAllocator> SeenDirEntries;
149
150   /// \brief A cache that maps paths to file entries (either real or
151   /// virtual) we have looked up.
152   ///
153   /// \see SeenDirEntries
154   llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator> SeenFileEntries;
155
156   /// \brief The canonical names of directories.
157   llvm::DenseMap<const DirectoryEntry *, llvm::StringRef> CanonicalDirNames;
158
159   /// \brief Storage for canonical names that we have computed.
160   llvm::BumpPtrAllocator CanonicalNameStorage;
161
162   /// \brief Each FileEntry we create is assigned a unique ID #.
163   ///
164   unsigned NextFileUID;
165
166   // Statistics.
167   unsigned NumDirLookups, NumFileLookups;
168   unsigned NumDirCacheMisses, NumFileCacheMisses;
169
170   // Caching.
171   OwningPtr<FileSystemStatCache> StatCache;
172
173   bool getStatValue(const char *Path, FileData &Data, bool isFile,
174                     vfs::File **F);
175
176   /// Add all ancestors of the given path (pointing to either a file
177   /// or a directory) as virtual directories.
178   void addAncestorsAsVirtualDirs(StringRef Path);
179
180 public:
181   FileManager(const FileSystemOptions &FileSystemOpts,
182               IntrusiveRefCntPtr<vfs::FileSystem> FS = 0);
183   ~FileManager();
184
185   /// \brief Installs the provided FileSystemStatCache object within
186   /// the FileManager.
187   ///
188   /// Ownership of this object is transferred to the FileManager.
189   ///
190   /// \param statCache the new stat cache to install. Ownership of this
191   /// object is transferred to the FileManager.
192   ///
193   /// \param AtBeginning whether this new stat cache must be installed at the
194   /// beginning of the chain of stat caches. Otherwise, it will be added to
195   /// the end of the chain.
196   void addStatCache(FileSystemStatCache *statCache, bool AtBeginning = false);
197
198   /// \brief Removes the specified FileSystemStatCache object from the manager.
199   void removeStatCache(FileSystemStatCache *statCache);
200
201   /// \brief Removes all FileSystemStatCache objects from the manager.
202   void clearStatCaches();
203
204   /// \brief Lookup, cache, and verify the specified directory (real or
205   /// virtual).
206   ///
207   /// This returns NULL if the directory doesn't exist.
208   ///
209   /// \param CacheFailure If true and the file does not exist, we'll cache
210   /// the failure to find this file.
211   const DirectoryEntry *getDirectory(StringRef DirName,
212                                      bool CacheFailure = true);
213
214   /// \brief Lookup, cache, and verify the specified file (real or
215   /// virtual).
216   ///
217   /// This returns NULL if the file doesn't exist.
218   ///
219   /// \param OpenFile if true and the file exists, it will be opened.
220   ///
221   /// \param CacheFailure If true and the file does not exist, we'll cache
222   /// the failure to find this file.
223   const FileEntry *getFile(StringRef Filename, bool OpenFile = false,
224                            bool CacheFailure = true);
225
226   /// \brief Returns the current file system options
227   const FileSystemOptions &getFileSystemOptions() { return FileSystemOpts; }
228
229   IntrusiveRefCntPtr<vfs::FileSystem> getVirtualFileSystem() const {
230     return FS;
231   }
232
233   /// \brief Retrieve a file entry for a "virtual" file that acts as
234   /// if there were a file with the given name on disk.
235   ///
236   /// The file itself is not accessed.
237   const FileEntry *getVirtualFile(StringRef Filename, off_t Size,
238                                   time_t ModificationTime);
239
240   /// \brief Open the specified file as a MemoryBuffer, returning a new
241   /// MemoryBuffer if successful, otherwise returning null.
242   llvm::MemoryBuffer *getBufferForFile(const FileEntry *Entry,
243                                        std::string *ErrorStr = 0,
244                                        bool isVolatile = false);
245   llvm::MemoryBuffer *getBufferForFile(StringRef Filename,
246                                        std::string *ErrorStr = 0);
247
248   /// \brief Get the 'stat' information for the given \p Path.
249   ///
250   /// If the path is relative, it will be resolved against the WorkingDir of the
251   /// FileManager's FileSystemOptions.
252   ///
253   /// \returns false on success, true on error.
254   bool getNoncachedStatValue(StringRef Path,
255                              vfs::Status &Result);
256
257   /// \brief Remove the real file \p Entry from the cache.
258   void invalidateCache(const FileEntry *Entry);
259
260   /// \brief If path is not absolute and FileSystemOptions set the working
261   /// directory, the path is modified to be relative to the given
262   /// working directory.
263   void FixupRelativePath(SmallVectorImpl<char> &path) const;
264
265   /// \brief Produce an array mapping from the unique IDs assigned to each
266   /// file to the corresponding FileEntry pointer.
267   void GetUniqueIDMapping(
268                     SmallVectorImpl<const FileEntry *> &UIDToFiles) const;
269
270   /// \brief Modifies the size and modification time of a previously created
271   /// FileEntry. Use with caution.
272   static void modifyFileEntry(FileEntry *File, off_t Size,
273                               time_t ModificationTime);
274
275   /// \brief Retrieve the canonical name for a given directory.
276   ///
277   /// This is a very expensive operation, despite its results being cached,
278   /// and should only be used when the physical layout of the file system is
279   /// required, which is (almost) never.
280   StringRef getCanonicalName(const DirectoryEntry *Dir);
281
282   void PrintStats() const;
283 };
284
285 }  // end namespace clang
286
287 #endif