blob: b921f3e0d9d85b61b06fdd32288b61e9689b3aa8 [file] [log] [blame]
Chris Lattner226efd32010-11-23 19:19:34 +00001//===--- FileManager.cpp - File System Probing and Caching ----------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
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"
Chris Lattner226efd32010-11-23 19:19:34 +000021#include "clang/Basic/FileSystemStatCache.h"
Chris Lattner2f4a89a2006-10-30 03:55:17 +000022#include "llvm/ADT/SmallString.h"
Michael J. Spencer740857f2010-12-21 16:45:57 +000023#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +000024#include "llvm/Support/MemoryBuffer.h"
Chris Lattner3441b4f2009-08-23 22:45:33 +000025#include "llvm/Support/raw_ostream.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000026#include "llvm/Support/Path.h"
Michael J. Spencerf25faaa2010-12-09 17:36:38 +000027#include "llvm/Support/system_error.h"
Dylan Noblesmith1ced7372011-12-22 22:49:47 +000028#include "llvm/Config/llvm-config.h"
Benjamin Kramer26db6482009-09-05 09:49:39 +000029#include <map>
30#include <set>
31#include <string>
Chris Lattner278038b2010-11-23 21:53:15 +000032
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
Chris Lattner22eb9722006-06-18 05:43:12 +000040using namespace clang;
41
42// FIXME: Enhance libsystem to support inode and other fields.
43#include <sys/stat.h>
44
Ted Kremenek8d71e252008-01-11 20:42:05 +000045/// NON_EXISTENT_DIR - A special value distinct from null that is used to
Chris Lattneraf653752006-10-30 03:06:54 +000046/// represent a dir name that doesn't exist on the disk.
Ted Kremenek8d71e252008-01-11 20:42:05 +000047#define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
Chris Lattneraf653752006-10-30 03:06:54 +000048
Chris Lattner9624b692010-11-23 20:50:22 +000049/// 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
54FileEntry::~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
Ted Kremenek5c04bd82009-01-28 00:27:31 +000060//===----------------------------------------------------------------------===//
61// Windows.
62//===----------------------------------------------------------------------===//
63
Ted Kremenekd87eef82008-02-24 03:15:25 +000064#ifdef LLVM_ON_WIN32
65
Ted Kremenekd87eef82008-02-24 03:15:25 +000066namespace {
Mike Stump11289f42009-09-09 15:08:12 +000067 static std::string GetFullPath(const char *relPath) {
Ted Kremenekd87eef82008-02-24 03:15:25 +000068 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
78class FileManager::UniqueDirContainer {
79 /// UniqueDirs - Cache from full path to existing directories/files.
80 ///
Mike Stump11289f42009-09-09 15:08:12 +000081 llvm::StringMap<DirectoryEntry> UniqueDirs;
Ted Kremenekd87eef82008-02-24 03:15:25 +000082
83public:
Zhanyong Wane1dd3e22011-02-11 18:44:49 +000084 /// 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*/) {
Ted Kremenekd87eef82008-02-24 03:15:25 +000089 std::string FullPath(GetFullPath(Name));
Chris Lattner966b25b2010-11-23 20:30:42 +000090 return UniqueDirs.GetOrCreateValue(FullPath).getValue();
Ted Kremenekd87eef82008-02-24 03:15:25 +000091 }
Mike Stump11289f42009-09-09 15:08:12 +000092
Chris Lattner966b25b2010-11-23 20:30:42 +000093 size_t size() const { return UniqueDirs.size(); }
Ted Kremenekd87eef82008-02-24 03:15:25 +000094};
95
96class FileManager::UniqueFileContainer {
97 /// UniqueFiles - Cache from full path to existing directories/files.
98 ///
Ted Kremenek1502b7e2009-01-28 01:01:07 +000099 llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;
Ted Kremenekd87eef82008-02-24 03:15:25 +0000100
101public:
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000102 /// 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*/) {
Ted Kremenekd87eef82008-02-24 03:15:25 +0000106 std::string FullPath(GetFullPath(Name));
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000107
Benjamin Kramer44f91da2011-11-06 20:36:48 +0000108 // Lowercase string because Windows filesystem is case insensitive.
109 FullPath = StringRef(FullPath).lower();
Chris Lattner966b25b2010-11-23 20:30:42 +0000110 return UniqueFiles.GetOrCreateValue(FullPath).getValue();
Ted Kremenekd87eef82008-02-24 03:15:25 +0000111 }
112
Chris Lattner966b25b2010-11-23 20:30:42 +0000113 size_t size() const { return UniqueFiles.size(); }
Axel Naumann38179d92012-06-27 09:17:42 +0000114
Axel Naumann23c1676d2012-07-11 09:41:34 +0000115 void erase(const FileEntry *Entry) {
116 std::string FullPath(GetFullPath(Entry->getName()));
117
118 // Lowercase string because Windows filesystem is case insensitive.
119 FullPath = StringRef(FullPath).lower();
120 UniqueFiles.erase(FullPath);
121 }
Ted Kremenekd87eef82008-02-24 03:15:25 +0000122};
123
Ted Kremenek5c04bd82009-01-28 00:27:31 +0000124//===----------------------------------------------------------------------===//
125// Unix-like Systems.
126//===----------------------------------------------------------------------===//
127
Ted Kremenekd87eef82008-02-24 03:15:25 +0000128#else
129
Ted Kremenekd87eef82008-02-24 03:15:25 +0000130class FileManager::UniqueDirContainer {
131 /// UniqueDirs - Cache from ID's to existing directories/files.
Mike Stump11289f42009-09-09 15:08:12 +0000132 std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;
Ted Kremenekd87eef82008-02-24 03:15:25 +0000133
134public:
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000135 /// getDirectory - Return an existing DirectoryEntry with the given
136 /// ID's if there is already one; otherwise create and return a
137 /// default-constructed DirectoryEntry.
138 DirectoryEntry &getDirectory(const char * /*Name*/,
139 const struct stat &StatBuf) {
Ted Kremenekd87eef82008-02-24 03:15:25 +0000140 return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
141 }
142
Chris Lattner966b25b2010-11-23 20:30:42 +0000143 size_t size() const { return UniqueDirs.size(); }
Ted Kremenekd87eef82008-02-24 03:15:25 +0000144};
145
146class FileManager::UniqueFileContainer {
147 /// UniqueFiles - Cache from ID's to existing directories/files.
Ted Kremenekd87eef82008-02-24 03:15:25 +0000148 std::set<FileEntry> UniqueFiles;
149
150public:
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000151 /// getFile - Return an existing FileEntry with the given ID's if
152 /// there is already one; otherwise create and return a
153 /// default-constructed FileEntry.
154 FileEntry &getFile(const char * /*Name*/, const struct stat &StatBuf) {
Ted Kremenekd87eef82008-02-24 03:15:25 +0000155 return
156 const_cast<FileEntry&>(
157 *UniqueFiles.insert(FileEntry(StatBuf.st_dev,
Ted Kremenek5d7e2e12009-02-12 03:17:57 +0000158 StatBuf.st_ino,
159 StatBuf.st_mode)).first);
Ted Kremenekd87eef82008-02-24 03:15:25 +0000160 }
161
Chris Lattner966b25b2010-11-23 20:30:42 +0000162 size_t size() const { return UniqueFiles.size(); }
Axel Naumann38179d92012-06-27 09:17:42 +0000163
Axel Naumannb3074002012-07-10 16:50:27 +0000164 void erase(const FileEntry *Entry) { UniqueFiles.erase(*Entry); }
Ted Kremenekd87eef82008-02-24 03:15:25 +0000165};
166
167#endif
168
Ted Kremenek5c04bd82009-01-28 00:27:31 +0000169//===----------------------------------------------------------------------===//
170// Common logic.
171//===----------------------------------------------------------------------===//
Ted Kremenekd87eef82008-02-24 03:15:25 +0000172
Chris Lattner3f5a9ef2010-11-23 07:51:02 +0000173FileManager::FileManager(const FileSystemOptions &FSO)
174 : FileSystemOpts(FSO),
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000175 UniqueRealDirs(*new UniqueDirContainer()),
176 UniqueRealFiles(*new UniqueFileContainer()),
177 SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
Ted Kremenekd87eef82008-02-24 03:15:25 +0000178 NumDirLookups = NumFileLookups = 0;
179 NumDirCacheMisses = NumFileCacheMisses = 0;
180}
181
182FileManager::~FileManager() {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000183 delete &UniqueRealDirs;
184 delete &UniqueRealFiles;
Chris Lattner966b25b2010-11-23 20:30:42 +0000185 for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
186 delete VirtualFileEntries[i];
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000187 for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
188 delete VirtualDirectoryEntries[i];
Ted Kremenekd87eef82008-02-24 03:15:25 +0000189}
190
Chris Lattner226efd32010-11-23 19:19:34 +0000191void FileManager::addStatCache(FileSystemStatCache *statCache,
192 bool AtBeginning) {
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000193 assert(statCache && "No stat cache provided?");
194 if (AtBeginning || StatCache.get() == 0) {
195 statCache->setNextStatCache(StatCache.take());
196 StatCache.reset(statCache);
197 return;
198 }
199
Chris Lattner226efd32010-11-23 19:19:34 +0000200 FileSystemStatCache *LastCache = StatCache.get();
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000201 while (LastCache->getNextStatCache())
202 LastCache = LastCache->getNextStatCache();
203
204 LastCache->setNextStatCache(statCache);
205}
206
Chris Lattner226efd32010-11-23 19:19:34 +0000207void FileManager::removeStatCache(FileSystemStatCache *statCache) {
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000208 if (!statCache)
209 return;
210
211 if (StatCache.get() == statCache) {
212 // This is the first stat cache.
213 StatCache.reset(StatCache->takeNextStatCache());
214 return;
215 }
216
217 // Find the stat cache in the list.
Chris Lattner226efd32010-11-23 19:19:34 +0000218 FileSystemStatCache *PrevCache = StatCache.get();
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000219 while (PrevCache && PrevCache->getNextStatCache() != statCache)
220 PrevCache = PrevCache->getNextStatCache();
Chris Lattner9624b692010-11-23 20:50:22 +0000221
222 assert(PrevCache && "Stat cache not found for removal");
223 PrevCache->setNextStatCache(statCache->getNextStatCache());
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000224}
225
Douglas Gregor407e2122009-12-02 18:12:28 +0000226/// \brief Retrieve the directory that the given file name resides in.
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000227/// Filename can point to either a real file or a virtual file.
Douglas Gregor407e2122009-12-02 18:12:28 +0000228static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000229 StringRef Filename,
230 bool CacheFailure) {
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000231 if (Filename.empty())
232 return NULL;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000233
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000234 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
235 return NULL; // If Filename is a directory.
Benjamin Kramer3cf715d2010-11-21 11:32:22 +0000236
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000237 StringRef DirName = llvm::sys::path::parent_path(Filename);
Chris Lattner0c0e8042010-11-21 09:50:16 +0000238 // Use the current directory if file has no path component.
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000239 if (DirName.empty())
240 DirName = ".";
Douglas Gregor407e2122009-12-02 18:12:28 +0000241
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000242 return FileMgr.getDirectory(DirName, CacheFailure);
Douglas Gregor407e2122009-12-02 18:12:28 +0000243}
244
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000245/// Add all ancestors of the given path (pointing to either a file or
246/// a directory) as virtual directories.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000247void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
248 StringRef DirName = llvm::sys::path::parent_path(Path);
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000249 if (DirName.empty())
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000250 return;
251
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000252 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
253 SeenDirEntries.GetOrCreateValue(DirName);
254
255 // When caching a virtual directory, we always cache its ancestors
256 // at the same time. Therefore, if DirName is already in the cache,
257 // we don't need to recurse as its ancestors must also already be in
258 // the cache.
259 if (NamedDirEnt.getValue())
260 return;
261
262 // Add the virtual directory to the cache.
263 DirectoryEntry *UDE = new DirectoryEntry;
264 UDE->Name = NamedDirEnt.getKeyData();
265 NamedDirEnt.setValue(UDE);
266 VirtualDirectoryEntries.push_back(UDE);
267
268 // Recursively add the other ancestors.
269 addAncestorsAsVirtualDirs(DirName);
270}
271
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000272const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
273 bool CacheFailure) {
NAKAMURA Takumi8bd8ee72012-06-16 06:04:10 +0000274 // stat doesn't like trailing separators except for root directory.
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000275 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
276 // (though it can strip '\\')
NAKAMURA Takumi8bd8ee72012-06-16 06:04:10 +0000277 if (DirName.size() > 1 &&
278 DirName != llvm::sys::path::root_path(DirName) &&
279 llvm::sys::path::is_separator(DirName.back()))
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000280 DirName = DirName.substr(0, DirName.size()-1);
281
Chris Lattner22eb9722006-06-18 05:43:12 +0000282 ++NumDirLookups;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000283 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000284 SeenDirEntries.GetOrCreateValue(DirName);
Mike Stump11289f42009-09-09 15:08:12 +0000285
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000286 // See if there was already an entry in the map. Note that the map
287 // contains both virtual and real directories.
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000288 if (NamedDirEnt.getValue())
Ted Kremenek8d71e252008-01-11 20:42:05 +0000289 return NamedDirEnt.getValue() == NON_EXISTENT_DIR
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000290 ? 0 : NamedDirEnt.getValue();
Mike Stump11289f42009-09-09 15:08:12 +0000291
Chris Lattner22eb9722006-06-18 05:43:12 +0000292 ++NumDirCacheMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000293
Chris Lattneraf653752006-10-30 03:06:54 +0000294 // By default, initialize it to invalid.
Ted Kremenek8d71e252008-01-11 20:42:05 +0000295 NamedDirEnt.setValue(NON_EXISTENT_DIR);
Mike Stump11289f42009-09-09 15:08:12 +0000296
Chris Lattner43fd42e2006-10-30 03:40:58 +0000297 // Get the null-terminated directory name as stored as the key of the
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000298 // SeenDirEntries map.
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000299 const char *InterndDirName = NamedDirEnt.getKeyData();
Mike Stump11289f42009-09-09 15:08:12 +0000300
Chris Lattneraf653752006-10-30 03:06:54 +0000301 // Check to see if the directory exists.
Chris Lattner22eb9722006-06-18 05:43:12 +0000302 struct stat StatBuf;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000303 if (getStatValue(InterndDirName, StatBuf, 0/*directory lookup*/)) {
304 // There's no real directory at the given path.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000305 if (!CacheFailure)
306 SeenDirEntries.erase(DirName);
Chris Lattner22eb9722006-06-18 05:43:12 +0000307 return 0;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000308 }
Ted Kremenekd87eef82008-02-24 03:15:25 +0000309
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000310 // It exists. See if we have already opened a directory with the
311 // same inode (this occurs on Unix-like systems when one dir is
312 // symlinked to another, for example) or the same path (on
313 // Windows).
314 DirectoryEntry &UDE = UniqueRealDirs.getDirectory(InterndDirName, StatBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000315
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000316 NamedDirEnt.setValue(&UDE);
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000317 if (!UDE.getName()) {
318 // We don't have this directory yet, add it. We use the string
319 // key from the SeenDirEntries map as the string.
320 UDE.Name = InterndDirName;
321 }
Mike Stump11289f42009-09-09 15:08:12 +0000322
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000323 return &UDE;
Chris Lattner22eb9722006-06-18 05:43:12 +0000324}
325
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000326const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
327 bool CacheFailure) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000328 ++NumFileLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000329
Chris Lattner22eb9722006-06-18 05:43:12 +0000330 // See if there is already an entry in the map.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000331 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000332 SeenFileEntries.GetOrCreateValue(Filename);
Chris Lattner22eb9722006-06-18 05:43:12 +0000333
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000334 // See if there is already an entry in the map.
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000335 if (NamedFileEnt.getValue())
Ted Kremenek8d71e252008-01-11 20:42:05 +0000336 return NamedFileEnt.getValue() == NON_EXISTENT_FILE
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000337 ? 0 : NamedFileEnt.getValue();
Mike Stump11289f42009-09-09 15:08:12 +0000338
Chris Lattner22eb9722006-06-18 05:43:12 +0000339 ++NumFileCacheMisses;
340
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000341 // By default, initialize it to invalid.
Ted Kremenek8d71e252008-01-11 20:42:05 +0000342 NamedFileEnt.setValue(NON_EXISTENT_FILE);
Chris Lattner22eb9722006-06-18 05:43:12 +0000343
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000344 // Get the null-terminated file name as stored as the key of the
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000345 // SeenFileEntries map.
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000346 const char *InterndFileName = NamedFileEnt.getKeyData();
Mike Stump11289f42009-09-09 15:08:12 +0000347
Chris Lattner966b25b2010-11-23 20:30:42 +0000348 // Look up the directory for the file. When looking up something like
349 // sys/foo.h we'll discover all of the search directories that have a 'sys'
350 // subdirectory. This will let us avoid having to waste time on known-to-fail
351 // searches when we go to find sys/bar.h, because all the search directories
352 // without a 'sys' subdir will get a cached failure result.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000353 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
354 CacheFailure);
355 if (DirInfo == 0) { // Directory doesn't exist, file can't exist.
356 if (!CacheFailure)
357 SeenFileEntries.erase(Filename);
358
Douglas Gregor407e2122009-12-02 18:12:28 +0000359 return 0;
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000360 }
361
Chris Lattner22eb9722006-06-18 05:43:12 +0000362 // FIXME: Use the directory info to prune this, before doing the stat syscall.
363 // FIXME: This will reduce the # syscalls.
Mike Stump11289f42009-09-09 15:08:12 +0000364
Chris Lattner22eb9722006-06-18 05:43:12 +0000365 // Nope, there isn't. Check to see if the file exists.
Chris Lattnerdd278432010-11-23 21:17:56 +0000366 int FileDescriptor = -1;
Chris Lattner22eb9722006-06-18 05:43:12 +0000367 struct stat StatBuf;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000368 if (getStatValue(InterndFileName, StatBuf, &FileDescriptor)) {
369 // There's no real file at the given path.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000370 if (!CacheFailure)
371 SeenFileEntries.erase(Filename);
372
Chris Lattner22eb9722006-06-18 05:43:12 +0000373 return 0;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000374 }
Mike Stump11289f42009-09-09 15:08:12 +0000375
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000376 if (FileDescriptor != -1 && !openFile) {
377 close(FileDescriptor);
378 FileDescriptor = -1;
379 }
380
Ted Kremenekf4c38c92007-12-18 22:29:39 +0000381 // It exists. See if we have already opened a file with the same inode.
Chris Lattner22eb9722006-06-18 05:43:12 +0000382 // This occurs when one dir is symlinked to another, for example.
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000383 FileEntry &UFE = UniqueRealFiles.getFile(InterndFileName, StatBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000384
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000385 NamedFileEnt.setValue(&UFE);
Chris Lattnerdd278432010-11-23 21:17:56 +0000386 if (UFE.getName()) { // Already have an entry with this inode, return it.
387 // If the stat process opened the file, close it to avoid a FD leak.
388 if (FileDescriptor != -1)
389 close(FileDescriptor);
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000390
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000391 return &UFE;
Chris Lattnerdd278432010-11-23 21:17:56 +0000392 }
Chris Lattner269c2322006-06-25 06:23:00 +0000393
Chris Lattner22eb9722006-06-18 05:43:12 +0000394 // Otherwise, we don't have this directory yet, add it.
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000395 // FIXME: Change the name to be a char* that points back to the
396 // 'SeenFileEntries' key.
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000397 UFE.Name = InterndFileName;
398 UFE.Size = StatBuf.st_size;
399 UFE.ModTime = StatBuf.st_mtime;
400 UFE.Dir = DirInfo;
401 UFE.UID = NextFileUID++;
Chris Lattnerdd278432010-11-23 21:17:56 +0000402 UFE.FD = FileDescriptor;
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000403 return &UFE;
Chris Lattner22eb9722006-06-18 05:43:12 +0000404}
405
Douglas Gregor407e2122009-12-02 18:12:28 +0000406const FileEntry *
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000407FileManager::getVirtualFile(StringRef Filename, off_t Size,
Chris Lattner5159f612010-11-23 08:35:12 +0000408 time_t ModificationTime) {
Douglas Gregor407e2122009-12-02 18:12:28 +0000409 ++NumFileLookups;
410
411 // See if there is already an entry in the map.
412 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000413 SeenFileEntries.GetOrCreateValue(Filename);
Douglas Gregor407e2122009-12-02 18:12:28 +0000414
415 // See if there is already an entry in the map.
Axel Naumann63fbaed2011-01-27 10:55:51 +0000416 if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
417 return NamedFileEnt.getValue();
Douglas Gregor407e2122009-12-02 18:12:28 +0000418
419 ++NumFileCacheMisses;
420
421 // By default, initialize it to invalid.
422 NamedFileEnt.setValue(NON_EXISTENT_FILE);
423
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000424 addAncestorsAsVirtualDirs(Filename);
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000425 FileEntry *UFE = 0;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000426
427 // Now that all ancestors of Filename are in the cache, the
428 // following call is guaranteed to find the DirectoryEntry from the
429 // cache.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000430 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
431 /*CacheFailure=*/true);
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000432 assert(DirInfo &&
433 "The directory of a virtual file should already be in the cache.");
Douglas Gregor407e2122009-12-02 18:12:28 +0000434
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000435 // Check to see if the file exists. If so, drop the virtual file
436 int FileDescriptor = -1;
437 struct stat StatBuf;
438 const char *InterndFileName = NamedFileEnt.getKeyData();
439 if (getStatValue(InterndFileName, StatBuf, &FileDescriptor) == 0) {
440 // If the stat process opened the file, close it to avoid a FD leak.
441 if (FileDescriptor != -1)
442 close(FileDescriptor);
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000443
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000444 StatBuf.st_size = Size;
445 StatBuf.st_mtime = ModificationTime;
446 UFE = &UniqueRealFiles.getFile(InterndFileName, StatBuf);
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000447
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000448 NamedFileEnt.setValue(UFE);
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000449
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000450 // If we had already opened this file, close it now so we don't
451 // leak the descriptor. We're not going to use the file
452 // descriptor anyway, since this is a virtual file.
453 if (UFE->FD != -1) {
454 close(UFE->FD);
455 UFE->FD = -1;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000456 }
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000457
458 // If we already have an entry with this inode, return it.
459 if (UFE->getName())
460 return UFE;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000461 }
462
463 if (!UFE) {
464 UFE = new FileEntry();
465 VirtualFileEntries.push_back(UFE);
466 NamedFileEnt.setValue(UFE);
467 }
Douglas Gregor407e2122009-12-02 18:12:28 +0000468
Chris Lattner9624b692010-11-23 20:50:22 +0000469 UFE->Name = InterndFileName;
Douglas Gregor407e2122009-12-02 18:12:28 +0000470 UFE->Size = Size;
471 UFE->ModTime = ModificationTime;
472 UFE->Dir = DirInfo;
473 UFE->UID = NextFileUID++;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000474 UFE->FD = -1;
Douglas Gregor407e2122009-12-02 18:12:28 +0000475 return UFE;
476}
477
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000478void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
479 StringRef pathRef(path.data(), path.size());
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000480
Anders Carlsson9ba8fb12011-03-14 01:13:54 +0000481 if (FileSystemOpts.WorkingDir.empty()
482 || llvm::sys::path::is_absolute(pathRef))
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000483 return;
484
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000485 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000486 llvm::sys::path::append(NewPath, pathRef);
Chris Lattner6e640992010-11-23 04:45:28 +0000487 path = NewPath;
488}
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000489
Chris Lattner6e640992010-11-23 04:45:28 +0000490llvm::MemoryBuffer *FileManager::
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000491getBufferForFile(const FileEntry *Entry, std::string *ErrorStr,
492 bool isVolatile) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000493 OwningPtr<llvm::MemoryBuffer> Result;
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000494 llvm::error_code ec;
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44 +0000495
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000496 uint64_t FileSize = Entry->getSize();
497 // If there's a high enough chance that the file have changed since we
498 // got its size, force a stat before opening it.
499 if (isVolatile)
500 FileSize = -1;
501
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44 +0000502 const char *Filename = Entry->getName();
503 // If the file is already open, use the open file descriptor.
504 if (Entry->FD != -1) {
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000505 ec = llvm::MemoryBuffer::getOpenFile(Entry->FD, Filename, Result, FileSize);
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44 +0000506 if (ErrorStr)
507 *ErrorStr = ec.message();
508
509 close(Entry->FD);
510 Entry->FD = -1;
511 return Result.take();
512 }
513
514 // Otherwise, open the file.
515
Chris Lattner5ea7d072010-11-23 22:32:37 +0000516 if (FileSystemOpts.WorkingDir.empty()) {
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000517 ec = llvm::MemoryBuffer::getFile(Filename, Result, FileSize);
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000518 if (ec && ErrorStr)
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000519 *ErrorStr = ec.message();
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000520 return Result.take();
Chris Lattner5ea7d072010-11-23 22:32:37 +0000521 }
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000522
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000523 SmallString<128> FilePath(Entry->getName());
Anders Carlsson878b3e22011-03-07 01:28:33 +0000524 FixupRelativePath(FilePath);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000525 ec = llvm::MemoryBuffer::getFile(FilePath.str(), Result, FileSize);
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000526 if (ec && ErrorStr)
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000527 *ErrorStr = ec.message();
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000528 return Result.take();
Chris Lattner26b5c192010-11-23 09:19:42 +0000529}
530
531llvm::MemoryBuffer *FileManager::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000532getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000533 OwningPtr<llvm::MemoryBuffer> Result;
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000534 llvm::error_code ec;
535 if (FileSystemOpts.WorkingDir.empty()) {
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000536 ec = llvm::MemoryBuffer::getFile(Filename, Result);
537 if (ec && ErrorStr)
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000538 *ErrorStr = ec.message();
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000539 return Result.take();
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000540 }
541
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000542 SmallString<128> FilePath(Filename);
Anders Carlsson878b3e22011-03-07 01:28:33 +0000543 FixupRelativePath(FilePath);
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000544 ec = llvm::MemoryBuffer::getFile(FilePath.c_str(), Result);
545 if (ec && ErrorStr)
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000546 *ErrorStr = ec.message();
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000547 return Result.take();
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000548}
549
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000550/// getStatValue - Get the 'stat' information for the specified path,
551/// using the cache to accelerate it if possible. This returns true
552/// if the path points to a virtual file or does not exist, or returns
553/// false if it's an existent real file. If FileDescriptor is NULL,
554/// do directory look-up instead of file look-up.
Chris Lattner9624b692010-11-23 20:50:22 +0000555bool FileManager::getStatValue(const char *Path, struct stat &StatBuf,
Chris Lattnerdd278432010-11-23 21:17:56 +0000556 int *FileDescriptor) {
Chris Lattner226efd32010-11-23 19:19:34 +0000557 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
558 // absolute!
Chris Lattner5769c3d2010-11-23 19:56:39 +0000559 if (FileSystemOpts.WorkingDir.empty())
Chris Lattnerdd278432010-11-23 21:17:56 +0000560 return FileSystemStatCache::get(Path, StatBuf, FileDescriptor,
561 StatCache.get());
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000562
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000563 SmallString<128> FilePath(Path);
Anders Carlsson878b3e22011-03-07 01:28:33 +0000564 FixupRelativePath(FilePath);
Chris Lattner5769c3d2010-11-23 19:56:39 +0000565
Chris Lattnerdd278432010-11-23 21:17:56 +0000566 return FileSystemStatCache::get(FilePath.c_str(), StatBuf, FileDescriptor,
567 StatCache.get());
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000568}
569
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000570bool FileManager::getNoncachedStatValue(StringRef Path,
Anders Carlsson5e368402011-03-18 19:23:19 +0000571 struct stat &StatBuf) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000572 SmallString<128> FilePath(Path);
Anders Carlsson5e368402011-03-18 19:23:19 +0000573 FixupRelativePath(FilePath);
574
575 return ::stat(FilePath.c_str(), &StatBuf) != 0;
576}
577
Axel Naumannb3074002012-07-10 16:50:27 +0000578void FileManager::invalidateCache(const FileEntry *Entry) {
579 assert(Entry && "Cannot invalidate a NULL FileEntry");
Axel Naumann38179d92012-06-27 09:17:42 +0000580
581 SeenFileEntries.erase(Entry->getName());
Axel Naumannb3074002012-07-10 16:50:27 +0000582
583 // FileEntry invalidation should not block future optimizations in the file
584 // caches. Possible alternatives are cache truncation (invalidate last N) or
585 // invalidation of the whole cache.
586 UniqueRealFiles.erase(Entry);
Axel Naumann38179d92012-06-27 09:17:42 +0000587}
588
589
Douglas Gregor09b69892011-02-10 17:09:37 +0000590void FileManager::GetUniqueIDMapping(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000591 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
Douglas Gregor09b69892011-02-10 17:09:37 +0000592 UIDToFiles.clear();
593 UIDToFiles.resize(NextFileUID);
594
595 // Map file entries
596 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000597 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
Douglas Gregor09b69892011-02-10 17:09:37 +0000598 FE != FEEnd; ++FE)
599 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
600 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
601
602 // Map virtual file entries
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000603 for (SmallVector<FileEntry*, 4>::const_iterator
Douglas Gregor09b69892011-02-10 17:09:37 +0000604 VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
605 VFE != VFEEnd; ++VFE)
606 if (*VFE && *VFE != NON_EXISTENT_FILE)
607 UIDToFiles[(*VFE)->getUID()] = *VFE;
608}
Chris Lattner226efd32010-11-23 19:19:34 +0000609
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000610void FileManager::modifyFileEntry(FileEntry *File,
611 off_t Size, time_t ModificationTime) {
612 File->Size = Size;
613 File->ModTime = ModificationTime;
614}
615
Chris Lattner226efd32010-11-23 19:19:34 +0000616
Chris Lattner22eb9722006-06-18 05:43:12 +0000617void FileManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000618 llvm::errs() << "\n*** File Manager Stats:\n";
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000619 llvm::errs() << UniqueRealFiles.size() << " real files found, "
620 << UniqueRealDirs.size() << " real dirs found.\n";
621 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
622 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000623 llvm::errs() << NumDirLookups << " dir lookups, "
624 << NumDirCacheMisses << " dir cache misses.\n";
625 llvm::errs() << NumFileLookups << " file lookups, "
626 << NumFileCacheMisses << " file cache misses.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000627
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000628 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
Chris Lattner22eb9722006-06-18 05:43:12 +0000629}