blob: a816969b91441770c3e3d14a28667b8fdd665d9c [file] [log] [blame]
Chris Lattner10e286a2010-11-23 19:19:34 +00001//===--- FileManager.cpp - File System Probing and Caching ----------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner10e286a2010-11-23 19:19:34 +000021#include "clang/Basic/FileSystemStatCache.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "llvm/ADT/SmallString.h"
Michael J. Spencerfbfd1802010-12-21 16:45:57 +000023#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +000024#include "llvm/Support/MemoryBuffer.h"
Chris Lattnerd57a7ef2009-08-23 22:45:33 +000025#include "llvm/Support/raw_ostream.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000026#include "llvm/Support/Path.h"
Michael J. Spencer3a321e22010-12-09 17:36:38 +000027#include "llvm/Support/system_error.h"
Dylan Noblesmith1770e0d2011-12-22 22:49:47 +000028#include "llvm/Config/llvm-config.h"
Benjamin Kramer458fb102009-09-05 09:49:39 +000029#include <map>
30#include <set>
31#include <string>
Chris Lattner291fcf02010-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>
Daniel Dunbar6a1f4942012-11-06 17:08:24 +000039#ifndef S_ISFIFO
40#define S_ISFIFO(x) (0)
41#endif
Chris Lattner291fcf02010-11-23 21:53:15 +000042#endif
Reid Spencer5f016e22007-07-11 17:01:13 +000043using namespace clang;
44
45// FIXME: Enhance libsystem to support inode and other fields.
46#include <sys/stat.h>
47
Ted Kremenek3d2da3d2008-01-11 20:42:05 +000048/// NON_EXISTENT_DIR - A special value distinct from null that is used to
Reid Spencer5f016e22007-07-11 17:01:13 +000049/// represent a dir name that doesn't exist on the disk.
Ted Kremenek3d2da3d2008-01-11 20:42:05 +000050#define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
Reid Spencer5f016e22007-07-11 17:01:13 +000051
Chris Lattnerf9f77662010-11-23 20:50:22 +000052/// NON_EXISTENT_FILE - A special value distinct from null that is used to
53/// represent a filename that doesn't exist on the disk.
54#define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
55
56
57FileEntry::~FileEntry() {
58 // If this FileEntry owns an open file descriptor that never got used, close
59 // it.
60 if (FD != -1) ::close(FD);
61}
62
Daniel Dunbarce36ecd2012-11-05 22:53:33 +000063bool FileEntry::isNamedPipe() const {
Daniel Dunbar6a1f4942012-11-06 17:08:24 +000064 return S_ISFIFO(FileMode);
Daniel Dunbarce36ecd2012-11-05 22:53:33 +000065}
66
Ted Kremenekcb8d58b2009-01-28 00:27:31 +000067//===----------------------------------------------------------------------===//
68// Windows.
69//===----------------------------------------------------------------------===//
70
Ted Kremenek6bb816a2008-02-24 03:15:25 +000071#ifdef LLVM_ON_WIN32
72
Ted Kremenek6bb816a2008-02-24 03:15:25 +000073namespace {
Mike Stump1eb44332009-09-09 15:08:12 +000074 static std::string GetFullPath(const char *relPath) {
Ted Kremenek6bb816a2008-02-24 03:15:25 +000075 char *absPathStrPtr = _fullpath(NULL, relPath, 0);
76 assert(absPathStrPtr && "_fullpath() returned NULL!");
77
78 std::string absPath(absPathStrPtr);
79
80 free(absPathStrPtr);
81 return absPath;
82 }
83}
84
85class FileManager::UniqueDirContainer {
86 /// UniqueDirs - Cache from full path to existing directories/files.
87 ///
Mike Stump1eb44332009-09-09 15:08:12 +000088 llvm::StringMap<DirectoryEntry> UniqueDirs;
Ted Kremenek6bb816a2008-02-24 03:15:25 +000089
90public:
Zhanyong Wan9b555ea2011-02-11 18:44:49 +000091 /// getDirectory - Return an existing DirectoryEntry with the given
92 /// name if there is already one; otherwise create and return a
93 /// default-constructed DirectoryEntry.
94 DirectoryEntry &getDirectory(const char *Name,
95 const struct stat & /*StatBuf*/) {
Ted Kremenek6bb816a2008-02-24 03:15:25 +000096 std::string FullPath(GetFullPath(Name));
Chris Lattnerf3e8a992010-11-23 20:30:42 +000097 return UniqueDirs.GetOrCreateValue(FullPath).getValue();
Ted Kremenek6bb816a2008-02-24 03:15:25 +000098 }
Mike Stump1eb44332009-09-09 15:08:12 +000099
Chris Lattnerf3e8a992010-11-23 20:30:42 +0000100 size_t size() const { return UniqueDirs.size(); }
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000101};
102
103class FileManager::UniqueFileContainer {
104 /// UniqueFiles - Cache from full path to existing directories/files.
105 ///
Ted Kremenek75368892009-01-28 01:01:07 +0000106 llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000107
108public:
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000109 /// getFile - Return an existing FileEntry with the given name if
110 /// there is already one; otherwise create and return a
111 /// default-constructed FileEntry.
112 FileEntry &getFile(const char *Name, const struct stat & /*StatBuf*/) {
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000113 std::string FullPath(GetFullPath(Name));
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000114
Benjamin Kramer90c78922011-11-06 20:36:48 +0000115 // Lowercase string because Windows filesystem is case insensitive.
116 FullPath = StringRef(FullPath).lower();
Chris Lattnerf3e8a992010-11-23 20:30:42 +0000117 return UniqueFiles.GetOrCreateValue(FullPath).getValue();
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000118 }
119
Chris Lattnerf3e8a992010-11-23 20:30:42 +0000120 size_t size() const { return UniqueFiles.size(); }
Axel Naumann3ce42c32012-06-27 09:17:42 +0000121
Axel Naumannbe779592012-07-11 09:41:34 +0000122 void erase(const FileEntry *Entry) {
123 std::string FullPath(GetFullPath(Entry->getName()));
124
125 // Lowercase string because Windows filesystem is case insensitive.
126 FullPath = StringRef(FullPath).lower();
127 UniqueFiles.erase(FullPath);
128 }
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000129};
130
Ted Kremenekcb8d58b2009-01-28 00:27:31 +0000131//===----------------------------------------------------------------------===//
132// Unix-like Systems.
133//===----------------------------------------------------------------------===//
134
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000135#else
136
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000137class FileManager::UniqueDirContainer {
138 /// UniqueDirs - Cache from ID's to existing directories/files.
Mike Stump1eb44332009-09-09 15:08:12 +0000139 std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000140
141public:
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000142 /// getDirectory - Return an existing DirectoryEntry with the given
143 /// ID's if there is already one; otherwise create and return a
144 /// default-constructed DirectoryEntry.
145 DirectoryEntry &getDirectory(const char * /*Name*/,
146 const struct stat &StatBuf) {
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000147 return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
148 }
149
Chris Lattnerf3e8a992010-11-23 20:30:42 +0000150 size_t size() const { return UniqueDirs.size(); }
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000151};
152
153class FileManager::UniqueFileContainer {
154 /// UniqueFiles - Cache from ID's to existing directories/files.
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000155 std::set<FileEntry> UniqueFiles;
156
157public:
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000158 /// getFile - Return an existing FileEntry with the given ID's if
159 /// there is already one; otherwise create and return a
160 /// default-constructed FileEntry.
161 FileEntry &getFile(const char * /*Name*/, const struct stat &StatBuf) {
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000162 return
163 const_cast<FileEntry&>(
164 *UniqueFiles.insert(FileEntry(StatBuf.st_dev,
Ted Kremenek96438f32009-02-12 03:17:57 +0000165 StatBuf.st_ino,
166 StatBuf.st_mode)).first);
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000167 }
168
Chris Lattnerf3e8a992010-11-23 20:30:42 +0000169 size_t size() const { return UniqueFiles.size(); }
Axel Naumann3ce42c32012-06-27 09:17:42 +0000170
Axel Naumann5ba05592012-07-10 16:50:27 +0000171 void erase(const FileEntry *Entry) { UniqueFiles.erase(*Entry); }
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000172};
173
174#endif
175
Ted Kremenekcb8d58b2009-01-28 00:27:31 +0000176//===----------------------------------------------------------------------===//
177// Common logic.
178//===----------------------------------------------------------------------===//
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000179
Chris Lattner7ad97ff2010-11-23 07:51:02 +0000180FileManager::FileManager(const FileSystemOptions &FSO)
181 : FileSystemOpts(FSO),
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000182 UniqueRealDirs(*new UniqueDirContainer()),
183 UniqueRealFiles(*new UniqueFileContainer()),
184 SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000185 NumDirLookups = NumFileLookups = 0;
186 NumDirCacheMisses = NumFileCacheMisses = 0;
187}
188
189FileManager::~FileManager() {
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000190 delete &UniqueRealDirs;
191 delete &UniqueRealFiles;
Chris Lattnerf3e8a992010-11-23 20:30:42 +0000192 for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
193 delete VirtualFileEntries[i];
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000194 for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
195 delete VirtualDirectoryEntries[i];
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000196}
197
Chris Lattner10e286a2010-11-23 19:19:34 +0000198void FileManager::addStatCache(FileSystemStatCache *statCache,
199 bool AtBeginning) {
Douglas Gregor52e71082009-10-16 18:18:30 +0000200 assert(statCache && "No stat cache provided?");
201 if (AtBeginning || StatCache.get() == 0) {
202 statCache->setNextStatCache(StatCache.take());
203 StatCache.reset(statCache);
204 return;
205 }
206
Chris Lattner10e286a2010-11-23 19:19:34 +0000207 FileSystemStatCache *LastCache = StatCache.get();
Douglas Gregor52e71082009-10-16 18:18:30 +0000208 while (LastCache->getNextStatCache())
209 LastCache = LastCache->getNextStatCache();
210
211 LastCache->setNextStatCache(statCache);
212}
213
Chris Lattner10e286a2010-11-23 19:19:34 +0000214void FileManager::removeStatCache(FileSystemStatCache *statCache) {
Douglas Gregor52e71082009-10-16 18:18:30 +0000215 if (!statCache)
216 return;
217
218 if (StatCache.get() == statCache) {
219 // This is the first stat cache.
220 StatCache.reset(StatCache->takeNextStatCache());
221 return;
222 }
223
224 // Find the stat cache in the list.
Chris Lattner10e286a2010-11-23 19:19:34 +0000225 FileSystemStatCache *PrevCache = StatCache.get();
Douglas Gregor52e71082009-10-16 18:18:30 +0000226 while (PrevCache && PrevCache->getNextStatCache() != statCache)
227 PrevCache = PrevCache->getNextStatCache();
Chris Lattnerf9f77662010-11-23 20:50:22 +0000228
229 assert(PrevCache && "Stat cache not found for removal");
230 PrevCache->setNextStatCache(statCache->getNextStatCache());
Douglas Gregor52e71082009-10-16 18:18:30 +0000231}
232
Manuel Klimek98be8602012-07-31 13:56:54 +0000233void FileManager::clearStatCaches() {
234 StatCache.reset(0);
235}
236
Douglas Gregor057e5672009-12-02 18:12:28 +0000237/// \brief Retrieve the directory that the given file name resides in.
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000238/// Filename can point to either a real file or a virtual file.
Douglas Gregor057e5672009-12-02 18:12:28 +0000239static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
Douglas Gregor6e975c42011-09-13 23:15:45 +0000240 StringRef Filename,
241 bool CacheFailure) {
Zhanyong Wan21af8872011-02-11 21:25:35 +0000242 if (Filename.empty())
243 return NULL;
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000244
Zhanyong Wan21af8872011-02-11 21:25:35 +0000245 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
246 return NULL; // If Filename is a directory.
Benjamin Krameraa8b2d92010-11-21 11:32:22 +0000247
Chris Lattner5f9e2722011-07-23 10:55:15 +0000248 StringRef DirName = llvm::sys::path::parent_path(Filename);
Chris Lattnerf69a1f32010-11-21 09:50:16 +0000249 // Use the current directory if file has no path component.
Zhanyong Wan21af8872011-02-11 21:25:35 +0000250 if (DirName.empty())
251 DirName = ".";
Douglas Gregor057e5672009-12-02 18:12:28 +0000252
Douglas Gregor6e975c42011-09-13 23:15:45 +0000253 return FileMgr.getDirectory(DirName, CacheFailure);
Douglas Gregor057e5672009-12-02 18:12:28 +0000254}
255
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000256/// Add all ancestors of the given path (pointing to either a file or
257/// a directory) as virtual directories.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000258void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
259 StringRef DirName = llvm::sys::path::parent_path(Path);
Zhanyong Wan21af8872011-02-11 21:25:35 +0000260 if (DirName.empty())
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000261 return;
262
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000263 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
264 SeenDirEntries.GetOrCreateValue(DirName);
265
266 // When caching a virtual directory, we always cache its ancestors
267 // at the same time. Therefore, if DirName is already in the cache,
268 // we don't need to recurse as its ancestors must also already be in
269 // the cache.
270 if (NamedDirEnt.getValue())
271 return;
272
273 // Add the virtual directory to the cache.
274 DirectoryEntry *UDE = new DirectoryEntry;
275 UDE->Name = NamedDirEnt.getKeyData();
276 NamedDirEnt.setValue(UDE);
277 VirtualDirectoryEntries.push_back(UDE);
278
279 // Recursively add the other ancestors.
280 addAncestorsAsVirtualDirs(DirName);
281}
282
Douglas Gregor6e975c42011-09-13 23:15:45 +0000283const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
284 bool CacheFailure) {
NAKAMURA Takumi759a4b42012-06-16 06:04:10 +0000285 // stat doesn't like trailing separators except for root directory.
NAKAMURA Takumi678a3ea2011-11-17 06:16:05 +0000286 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
287 // (though it can strip '\\')
NAKAMURA Takumi759a4b42012-06-16 06:04:10 +0000288 if (DirName.size() > 1 &&
289 DirName != llvm::sys::path::root_path(DirName) &&
290 llvm::sys::path::is_separator(DirName.back()))
NAKAMURA Takumi678a3ea2011-11-17 06:16:05 +0000291 DirName = DirName.substr(0, DirName.size()-1);
292
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 ++NumDirLookups;
294 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000295 SeenDirEntries.GetOrCreateValue(DirName);
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000297 // See if there was already an entry in the map. Note that the map
298 // contains both virtual and real directories.
Reid Spencer5f016e22007-07-11 17:01:13 +0000299 if (NamedDirEnt.getValue())
Ted Kremenek3d2da3d2008-01-11 20:42:05 +0000300 return NamedDirEnt.getValue() == NON_EXISTENT_DIR
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 ? 0 : NamedDirEnt.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 ++NumDirCacheMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Reid Spencer5f016e22007-07-11 17:01:13 +0000305 // By default, initialize it to invalid.
Ted Kremenek3d2da3d2008-01-11 20:42:05 +0000306 NamedDirEnt.setValue(NON_EXISTENT_DIR);
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 // Get the null-terminated directory name as stored as the key of the
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000309 // SeenDirEntries map.
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 const char *InterndDirName = NamedDirEnt.getKeyData();
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 // Check to see if the directory exists.
313 struct stat StatBuf;
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000314 if (getStatValue(InterndDirName, StatBuf, 0/*directory lookup*/)) {
315 // There's no real directory at the given path.
Douglas Gregor6e975c42011-09-13 23:15:45 +0000316 if (!CacheFailure)
317 SeenDirEntries.erase(DirName);
Reid Spencer5f016e22007-07-11 17:01:13 +0000318 return 0;
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000319 }
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000320
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000321 // It exists. See if we have already opened a directory with the
322 // same inode (this occurs on Unix-like systems when one dir is
323 // symlinked to another, for example) or the same path (on
324 // Windows).
325 DirectoryEntry &UDE = UniqueRealDirs.getDirectory(InterndDirName, StatBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Reid Spencer5f016e22007-07-11 17:01:13 +0000327 NamedDirEnt.setValue(&UDE);
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000328 if (!UDE.getName()) {
329 // We don't have this directory yet, add it. We use the string
330 // key from the SeenDirEntries map as the string.
331 UDE.Name = InterndDirName;
332 }
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 return &UDE;
335}
336
Douglas Gregor6e975c42011-09-13 23:15:45 +0000337const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
338 bool CacheFailure) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000339 ++NumFileLookups;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
Reid Spencer5f016e22007-07-11 17:01:13 +0000341 // See if there is already an entry in the map.
342 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000343 SeenFileEntries.GetOrCreateValue(Filename);
Reid Spencer5f016e22007-07-11 17:01:13 +0000344
345 // See if there is already an entry in the map.
346 if (NamedFileEnt.getValue())
Ted Kremenek3d2da3d2008-01-11 20:42:05 +0000347 return NamedFileEnt.getValue() == NON_EXISTENT_FILE
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 ? 0 : NamedFileEnt.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 ++NumFileCacheMisses;
351
352 // By default, initialize it to invalid.
Ted Kremenek3d2da3d2008-01-11 20:42:05 +0000353 NamedFileEnt.setValue(NON_EXISTENT_FILE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000354
Reid Spencer5f016e22007-07-11 17:01:13 +0000355 // Get the null-terminated file name as stored as the key of the
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000356 // SeenFileEntries map.
Reid Spencer5f016e22007-07-11 17:01:13 +0000357 const char *InterndFileName = NamedFileEnt.getKeyData();
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Chris Lattnerf3e8a992010-11-23 20:30:42 +0000359 // Look up the directory for the file. When looking up something like
360 // sys/foo.h we'll discover all of the search directories that have a 'sys'
361 // subdirectory. This will let us avoid having to waste time on known-to-fail
362 // searches when we go to find sys/bar.h, because all the search directories
363 // without a 'sys' subdir will get a cached failure result.
Douglas Gregor6e975c42011-09-13 23:15:45 +0000364 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
365 CacheFailure);
366 if (DirInfo == 0) { // Directory doesn't exist, file can't exist.
367 if (!CacheFailure)
368 SeenFileEntries.erase(Filename);
369
Douglas Gregor057e5672009-12-02 18:12:28 +0000370 return 0;
Douglas Gregor6e975c42011-09-13 23:15:45 +0000371 }
372
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 // FIXME: Use the directory info to prune this, before doing the stat syscall.
374 // FIXME: This will reduce the # syscalls.
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Reid Spencer5f016e22007-07-11 17:01:13 +0000376 // Nope, there isn't. Check to see if the file exists.
Chris Lattner898a0612010-11-23 21:17:56 +0000377 int FileDescriptor = -1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 struct stat StatBuf;
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000379 if (getStatValue(InterndFileName, StatBuf, &FileDescriptor)) {
380 // There's no real file at the given path.
Douglas Gregor6e975c42011-09-13 23:15:45 +0000381 if (!CacheFailure)
382 SeenFileEntries.erase(Filename);
383
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 return 0;
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000385 }
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000387 if (FileDescriptor != -1 && !openFile) {
388 close(FileDescriptor);
389 FileDescriptor = -1;
390 }
391
Ted Kremenekbca6d122007-12-18 22:29:39 +0000392 // It exists. See if we have already opened a file with the same inode.
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 // This occurs when one dir is symlinked to another, for example.
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000394 FileEntry &UFE = UniqueRealFiles.getFile(InterndFileName, StatBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 NamedFileEnt.setValue(&UFE);
Chris Lattner898a0612010-11-23 21:17:56 +0000397 if (UFE.getName()) { // Already have an entry with this inode, return it.
398 // If the stat process opened the file, close it to avoid a FD leak.
399 if (FileDescriptor != -1)
400 close(FileDescriptor);
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000401
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 return &UFE;
Chris Lattner898a0612010-11-23 21:17:56 +0000403 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000404
405 // Otherwise, we don't have this directory yet, add it.
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000406 // FIXME: Change the name to be a char* that points back to the
407 // 'SeenFileEntries' key.
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 UFE.Name = InterndFileName;
409 UFE.Size = StatBuf.st_size;
410 UFE.ModTime = StatBuf.st_mtime;
411 UFE.Dir = DirInfo;
412 UFE.UID = NextFileUID++;
Chris Lattner898a0612010-11-23 21:17:56 +0000413 UFE.FD = FileDescriptor;
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 return &UFE;
415}
416
Douglas Gregor057e5672009-12-02 18:12:28 +0000417const FileEntry *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000418FileManager::getVirtualFile(StringRef Filename, off_t Size,
Chris Lattner39b49bc2010-11-23 08:35:12 +0000419 time_t ModificationTime) {
Douglas Gregor057e5672009-12-02 18:12:28 +0000420 ++NumFileLookups;
421
422 // See if there is already an entry in the map.
423 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000424 SeenFileEntries.GetOrCreateValue(Filename);
Douglas Gregor057e5672009-12-02 18:12:28 +0000425
426 // See if there is already an entry in the map.
Axel Naumann04331162011-01-27 10:55:51 +0000427 if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
428 return NamedFileEnt.getValue();
Douglas Gregor057e5672009-12-02 18:12:28 +0000429
430 ++NumFileCacheMisses;
431
432 // By default, initialize it to invalid.
433 NamedFileEnt.setValue(NON_EXISTENT_FILE);
434
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000435 addAncestorsAsVirtualDirs(Filename);
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000436 FileEntry *UFE = 0;
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000437
438 // Now that all ancestors of Filename are in the cache, the
439 // following call is guaranteed to find the DirectoryEntry from the
440 // cache.
Douglas Gregor6e975c42011-09-13 23:15:45 +0000441 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
442 /*CacheFailure=*/true);
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000443 assert(DirInfo &&
444 "The directory of a virtual file should already be in the cache.");
Douglas Gregor057e5672009-12-02 18:12:28 +0000445
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000446 // Check to see if the file exists. If so, drop the virtual file
447 int FileDescriptor = -1;
448 struct stat StatBuf;
449 const char *InterndFileName = NamedFileEnt.getKeyData();
450 if (getStatValue(InterndFileName, StatBuf, &FileDescriptor) == 0) {
451 // If the stat process opened the file, close it to avoid a FD leak.
452 if (FileDescriptor != -1)
453 close(FileDescriptor);
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000454
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000455 StatBuf.st_size = Size;
456 StatBuf.st_mtime = ModificationTime;
457 UFE = &UniqueRealFiles.getFile(InterndFileName, StatBuf);
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000458
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000459 NamedFileEnt.setValue(UFE);
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000460
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000461 // If we had already opened this file, close it now so we don't
462 // leak the descriptor. We're not going to use the file
463 // descriptor anyway, since this is a virtual file.
464 if (UFE->FD != -1) {
465 close(UFE->FD);
466 UFE->FD = -1;
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000467 }
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000468
469 // If we already have an entry with this inode, return it.
470 if (UFE->getName())
471 return UFE;
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000472 }
473
474 if (!UFE) {
475 UFE = new FileEntry();
476 VirtualFileEntries.push_back(UFE);
477 NamedFileEnt.setValue(UFE);
478 }
Douglas Gregor057e5672009-12-02 18:12:28 +0000479
Chris Lattnerf9f77662010-11-23 20:50:22 +0000480 UFE->Name = InterndFileName;
Douglas Gregor057e5672009-12-02 18:12:28 +0000481 UFE->Size = Size;
482 UFE->ModTime = ModificationTime;
483 UFE->Dir = DirInfo;
484 UFE->UID = NextFileUID++;
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000485 UFE->FD = -1;
Douglas Gregor057e5672009-12-02 18:12:28 +0000486 return UFE;
487}
488
Chris Lattner5f9e2722011-07-23 10:55:15 +0000489void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
490 StringRef pathRef(path.data(), path.size());
Anders Carlssonaf036a62011-03-06 22:25:35 +0000491
Anders Carlsson2e2468e2011-03-14 01:13:54 +0000492 if (FileSystemOpts.WorkingDir.empty()
493 || llvm::sys::path::is_absolute(pathRef))
Michael J. Spencer256053b2010-12-17 21:22:22 +0000494 return;
495
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000496 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
Anders Carlssonaf036a62011-03-06 22:25:35 +0000497 llvm::sys::path::append(NewPath, pathRef);
Chris Lattner67452f52010-11-23 04:45:28 +0000498 path = NewPath;
499}
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000500
Chris Lattner67452f52010-11-23 04:45:28 +0000501llvm::MemoryBuffer *FileManager::
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000502getBufferForFile(const FileEntry *Entry, std::string *ErrorStr,
503 bool isVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000504 OwningPtr<llvm::MemoryBuffer> Result;
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000505 llvm::error_code ec;
Argyrios Kyrtzidisa8d530e2011-03-15 00:47:44 +0000506
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000507 uint64_t FileSize = Entry->getSize();
508 // If there's a high enough chance that the file have changed since we
509 // got its size, force a stat before opening it.
510 if (isVolatile)
511 FileSize = -1;
512
Argyrios Kyrtzidisa8d530e2011-03-15 00:47:44 +0000513 const char *Filename = Entry->getName();
514 // If the file is already open, use the open file descriptor.
515 if (Entry->FD != -1) {
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000516 ec = llvm::MemoryBuffer::getOpenFile(Entry->FD, Filename, Result, FileSize);
Argyrios Kyrtzidisa8d530e2011-03-15 00:47:44 +0000517 if (ErrorStr)
518 *ErrorStr = ec.message();
519
520 close(Entry->FD);
521 Entry->FD = -1;
522 return Result.take();
523 }
524
525 // Otherwise, open the file.
526
Chris Lattner5cc1c732010-11-23 22:32:37 +0000527 if (FileSystemOpts.WorkingDir.empty()) {
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000528 ec = llvm::MemoryBuffer::getFile(Filename, Result, FileSize);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000529 if (ec && ErrorStr)
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000530 *ErrorStr = ec.message();
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000531 return Result.take();
Chris Lattner5cc1c732010-11-23 22:32:37 +0000532 }
Anders Carlssonaf036a62011-03-06 22:25:35 +0000533
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000534 SmallString<128> FilePath(Entry->getName());
Anders Carlsson03fd3622011-03-07 01:28:33 +0000535 FixupRelativePath(FilePath);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000536 ec = llvm::MemoryBuffer::getFile(FilePath.str(), Result, FileSize);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000537 if (ec && ErrorStr)
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000538 *ErrorStr = ec.message();
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000539 return Result.take();
Chris Lattner75dfb652010-11-23 09:19:42 +0000540}
541
542llvm::MemoryBuffer *FileManager::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000543getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000544 OwningPtr<llvm::MemoryBuffer> Result;
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000545 llvm::error_code ec;
546 if (FileSystemOpts.WorkingDir.empty()) {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000547 ec = llvm::MemoryBuffer::getFile(Filename, Result);
548 if (ec && ErrorStr)
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000549 *ErrorStr = ec.message();
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000550 return Result.take();
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000551 }
552
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000553 SmallString<128> FilePath(Filename);
Anders Carlsson03fd3622011-03-07 01:28:33 +0000554 FixupRelativePath(FilePath);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000555 ec = llvm::MemoryBuffer::getFile(FilePath.c_str(), Result);
556 if (ec && ErrorStr)
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000557 *ErrorStr = ec.message();
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000558 return Result.take();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000559}
560
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000561/// getStatValue - Get the 'stat' information for the specified path,
562/// using the cache to accelerate it if possible. This returns true
563/// if the path points to a virtual file or does not exist, or returns
564/// false if it's an existent real file. If FileDescriptor is NULL,
565/// do directory look-up instead of file look-up.
Chris Lattnerf9f77662010-11-23 20:50:22 +0000566bool FileManager::getStatValue(const char *Path, struct stat &StatBuf,
Chris Lattner898a0612010-11-23 21:17:56 +0000567 int *FileDescriptor) {
Chris Lattner10e286a2010-11-23 19:19:34 +0000568 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
569 // absolute!
Chris Lattner11aa4b02010-11-23 19:56:39 +0000570 if (FileSystemOpts.WorkingDir.empty())
Chris Lattner898a0612010-11-23 21:17:56 +0000571 return FileSystemStatCache::get(Path, StatBuf, FileDescriptor,
572 StatCache.get());
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000573
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000574 SmallString<128> FilePath(Path);
Anders Carlsson03fd3622011-03-07 01:28:33 +0000575 FixupRelativePath(FilePath);
Chris Lattner11aa4b02010-11-23 19:56:39 +0000576
Chris Lattner898a0612010-11-23 21:17:56 +0000577 return FileSystemStatCache::get(FilePath.c_str(), StatBuf, FileDescriptor,
578 StatCache.get());
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000579}
580
Chris Lattner5f9e2722011-07-23 10:55:15 +0000581bool FileManager::getNoncachedStatValue(StringRef Path,
Anders Carlsson7dbafb32011-03-18 19:23:19 +0000582 struct stat &StatBuf) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000583 SmallString<128> FilePath(Path);
Anders Carlsson7dbafb32011-03-18 19:23:19 +0000584 FixupRelativePath(FilePath);
585
586 return ::stat(FilePath.c_str(), &StatBuf) != 0;
587}
588
Axel Naumann5ba05592012-07-10 16:50:27 +0000589void FileManager::invalidateCache(const FileEntry *Entry) {
590 assert(Entry && "Cannot invalidate a NULL FileEntry");
Axel Naumann3ce42c32012-06-27 09:17:42 +0000591
592 SeenFileEntries.erase(Entry->getName());
Axel Naumann5ba05592012-07-10 16:50:27 +0000593
594 // FileEntry invalidation should not block future optimizations in the file
595 // caches. Possible alternatives are cache truncation (invalidate last N) or
596 // invalidation of the whole cache.
597 UniqueRealFiles.erase(Entry);
Axel Naumann3ce42c32012-06-27 09:17:42 +0000598}
599
600
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000601void FileManager::GetUniqueIDMapping(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000602 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000603 UIDToFiles.clear();
604 UIDToFiles.resize(NextFileUID);
605
606 // Map file entries
607 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000608 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000609 FE != FEEnd; ++FE)
610 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
611 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
612
613 // Map virtual file entries
Chris Lattner5f9e2722011-07-23 10:55:15 +0000614 for (SmallVector<FileEntry*, 4>::const_iterator
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000615 VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
616 VFE != VFEEnd; ++VFE)
617 if (*VFE && *VFE != NON_EXISTENT_FILE)
618 UIDToFiles[(*VFE)->getUID()] = *VFE;
619}
Chris Lattner10e286a2010-11-23 19:19:34 +0000620
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +0000621void FileManager::modifyFileEntry(FileEntry *File,
622 off_t Size, time_t ModificationTime) {
623 File->Size = Size;
624 File->ModTime = ModificationTime;
625}
626
Chris Lattner10e286a2010-11-23 19:19:34 +0000627
Reid Spencer5f016e22007-07-11 17:01:13 +0000628void FileManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000629 llvm::errs() << "\n*** File Manager Stats:\n";
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000630 llvm::errs() << UniqueRealFiles.size() << " real files found, "
631 << UniqueRealDirs.size() << " real dirs found.\n";
632 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
633 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000634 llvm::errs() << NumDirLookups << " dir lookups, "
635 << NumDirCacheMisses << " dir cache misses.\n";
636 llvm::errs() << NumFileLookups << " file lookups, "
637 << NumFileCacheMisses << " file cache misses.\n";
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000639 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
Reid Spencer5f016e22007-07-11 17:01:13 +0000640}