blob: d8deac72c4672c795c2b04b574905ceb8e16899c [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "llvm/Config/llvm-config.h"
Michael J. Spencer740857f2010-12-21 16:45:57 +000024#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +000025#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000026#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "llvm/Support/raw_ostream.h"
Michael J. Spencerf25faaa2010-12-09 17:36:38 +000028#include "llvm/Support/system_error.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>
Daniel Dunbar65706d82012-11-06 17:08:24 +000039#ifndef S_ISFIFO
40#define S_ISFIFO(x) (0)
41#endif
Chris Lattner278038b2010-11-23 21:53:15 +000042#endif
Douglas Gregore00c8b22013-01-26 00:55:12 +000043#if defined(LLVM_ON_UNIX)
Dmitri Gribenkoeadae012013-01-26 16:29:36 +000044#include <limits.h>
Douglas Gregore00c8b22013-01-26 00:55:12 +000045#endif
Chris Lattner22eb9722006-06-18 05:43:12 +000046using namespace clang;
47
48// FIXME: Enhance libsystem to support inode and other fields.
49#include <sys/stat.h>
50
Ted Kremenek8d71e252008-01-11 20:42:05 +000051/// NON_EXISTENT_DIR - A special value distinct from null that is used to
Chris Lattneraf653752006-10-30 03:06:54 +000052/// represent a dir name that doesn't exist on the disk.
Ted Kremenek8d71e252008-01-11 20:42:05 +000053#define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
Chris Lattneraf653752006-10-30 03:06:54 +000054
Chris Lattner9624b692010-11-23 20:50:22 +000055/// NON_EXISTENT_FILE - A special value distinct from null that is used to
56/// represent a filename that doesn't exist on the disk.
57#define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
58
59
60FileEntry::~FileEntry() {
61 // If this FileEntry owns an open file descriptor that never got used, close
62 // it.
63 if (FD != -1) ::close(FD);
64}
65
Daniel Dunbare2951f42012-11-05 22:53:33 +000066bool FileEntry::isNamedPipe() const {
Daniel Dunbar65706d82012-11-06 17:08:24 +000067 return S_ISFIFO(FileMode);
Daniel Dunbare2951f42012-11-05 22:53:33 +000068}
69
Ted Kremenek5c04bd82009-01-28 00:27:31 +000070//===----------------------------------------------------------------------===//
71// Windows.
72//===----------------------------------------------------------------------===//
73
Ted Kremenekd87eef82008-02-24 03:15:25 +000074#ifdef LLVM_ON_WIN32
75
Ted Kremenekd87eef82008-02-24 03:15:25 +000076namespace {
Mike Stump11289f42009-09-09 15:08:12 +000077 static std::string GetFullPath(const char *relPath) {
Ted Kremenekd87eef82008-02-24 03:15:25 +000078 char *absPathStrPtr = _fullpath(NULL, relPath, 0);
79 assert(absPathStrPtr && "_fullpath() returned NULL!");
80
81 std::string absPath(absPathStrPtr);
82
83 free(absPathStrPtr);
84 return absPath;
85 }
86}
87
88class FileManager::UniqueDirContainer {
89 /// UniqueDirs - Cache from full path to existing directories/files.
90 ///
Mike Stump11289f42009-09-09 15:08:12 +000091 llvm::StringMap<DirectoryEntry> UniqueDirs;
Ted Kremenekd87eef82008-02-24 03:15:25 +000092
93public:
Zhanyong Wane1dd3e22011-02-11 18:44:49 +000094 /// getDirectory - Return an existing DirectoryEntry with the given
95 /// name if there is already one; otherwise create and return a
96 /// default-constructed DirectoryEntry.
97 DirectoryEntry &getDirectory(const char *Name,
98 const struct stat & /*StatBuf*/) {
Ted Kremenekd87eef82008-02-24 03:15:25 +000099 std::string FullPath(GetFullPath(Name));
Chris Lattner966b25b2010-11-23 20:30:42 +0000100 return UniqueDirs.GetOrCreateValue(FullPath).getValue();
Ted Kremenekd87eef82008-02-24 03:15:25 +0000101 }
Mike Stump11289f42009-09-09 15:08:12 +0000102
Chris Lattner966b25b2010-11-23 20:30:42 +0000103 size_t size() const { return UniqueDirs.size(); }
Ted Kremenekd87eef82008-02-24 03:15:25 +0000104};
105
106class FileManager::UniqueFileContainer {
107 /// UniqueFiles - Cache from full path to existing directories/files.
108 ///
Ted Kremenek1502b7e2009-01-28 01:01:07 +0000109 llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;
Ted Kremenekd87eef82008-02-24 03:15:25 +0000110
111public:
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000112 /// getFile - Return an existing FileEntry with the given name if
113 /// there is already one; otherwise create and return a
114 /// default-constructed FileEntry.
115 FileEntry &getFile(const char *Name, const struct stat & /*StatBuf*/) {
Ted Kremenekd87eef82008-02-24 03:15:25 +0000116 std::string FullPath(GetFullPath(Name));
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000117
Benjamin Kramer44f91da2011-11-06 20:36:48 +0000118 // Lowercase string because Windows filesystem is case insensitive.
119 FullPath = StringRef(FullPath).lower();
Chris Lattner966b25b2010-11-23 20:30:42 +0000120 return UniqueFiles.GetOrCreateValue(FullPath).getValue();
Ted Kremenekd87eef82008-02-24 03:15:25 +0000121 }
122
Chris Lattner966b25b2010-11-23 20:30:42 +0000123 size_t size() const { return UniqueFiles.size(); }
Axel Naumann38179d92012-06-27 09:17:42 +0000124
Axel Naumann23c1676d2012-07-11 09:41:34 +0000125 void erase(const FileEntry *Entry) {
126 std::string FullPath(GetFullPath(Entry->getName()));
127
128 // Lowercase string because Windows filesystem is case insensitive.
129 FullPath = StringRef(FullPath).lower();
130 UniqueFiles.erase(FullPath);
131 }
Ted Kremenekd87eef82008-02-24 03:15:25 +0000132};
133
Ted Kremenek5c04bd82009-01-28 00:27:31 +0000134//===----------------------------------------------------------------------===//
135// Unix-like Systems.
136//===----------------------------------------------------------------------===//
137
Ted Kremenekd87eef82008-02-24 03:15:25 +0000138#else
139
Ted Kremenekd87eef82008-02-24 03:15:25 +0000140class FileManager::UniqueDirContainer {
141 /// UniqueDirs - Cache from ID's to existing directories/files.
Mike Stump11289f42009-09-09 15:08:12 +0000142 std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;
Ted Kremenekd87eef82008-02-24 03:15:25 +0000143
144public:
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000145 /// getDirectory - Return an existing DirectoryEntry with the given
146 /// ID's if there is already one; otherwise create and return a
147 /// default-constructed DirectoryEntry.
148 DirectoryEntry &getDirectory(const char * /*Name*/,
149 const struct stat &StatBuf) {
Ted Kremenekd87eef82008-02-24 03:15:25 +0000150 return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
151 }
152
Chris Lattner966b25b2010-11-23 20:30:42 +0000153 size_t size() const { return UniqueDirs.size(); }
Ted Kremenekd87eef82008-02-24 03:15:25 +0000154};
155
156class FileManager::UniqueFileContainer {
157 /// UniqueFiles - Cache from ID's to existing directories/files.
Ted Kremenekd87eef82008-02-24 03:15:25 +0000158 std::set<FileEntry> UniqueFiles;
159
160public:
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000161 /// getFile - Return an existing FileEntry with the given ID's if
162 /// there is already one; otherwise create and return a
163 /// default-constructed FileEntry.
164 FileEntry &getFile(const char * /*Name*/, const struct stat &StatBuf) {
Ted Kremenekd87eef82008-02-24 03:15:25 +0000165 return
166 const_cast<FileEntry&>(
167 *UniqueFiles.insert(FileEntry(StatBuf.st_dev,
Ted Kremenek5d7e2e12009-02-12 03:17:57 +0000168 StatBuf.st_ino,
169 StatBuf.st_mode)).first);
Ted Kremenekd87eef82008-02-24 03:15:25 +0000170 }
171
Chris Lattner966b25b2010-11-23 20:30:42 +0000172 size_t size() const { return UniqueFiles.size(); }
Axel Naumann38179d92012-06-27 09:17:42 +0000173
Axel Naumannb3074002012-07-10 16:50:27 +0000174 void erase(const FileEntry *Entry) { UniqueFiles.erase(*Entry); }
Ted Kremenekd87eef82008-02-24 03:15:25 +0000175};
176
177#endif
178
Ted Kremenek5c04bd82009-01-28 00:27:31 +0000179//===----------------------------------------------------------------------===//
180// Common logic.
181//===----------------------------------------------------------------------===//
Ted Kremenekd87eef82008-02-24 03:15:25 +0000182
Chris Lattner3f5a9ef2010-11-23 07:51:02 +0000183FileManager::FileManager(const FileSystemOptions &FSO)
184 : FileSystemOpts(FSO),
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000185 UniqueRealDirs(*new UniqueDirContainer()),
186 UniqueRealFiles(*new UniqueFileContainer()),
187 SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
Ted Kremenekd87eef82008-02-24 03:15:25 +0000188 NumDirLookups = NumFileLookups = 0;
189 NumDirCacheMisses = NumFileCacheMisses = 0;
190}
191
192FileManager::~FileManager() {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000193 delete &UniqueRealDirs;
194 delete &UniqueRealFiles;
Chris Lattner966b25b2010-11-23 20:30:42 +0000195 for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
196 delete VirtualFileEntries[i];
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000197 for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
198 delete VirtualDirectoryEntries[i];
Ted Kremenekd87eef82008-02-24 03:15:25 +0000199}
200
Chris Lattner226efd32010-11-23 19:19:34 +0000201void FileManager::addStatCache(FileSystemStatCache *statCache,
202 bool AtBeginning) {
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000203 assert(statCache && "No stat cache provided?");
204 if (AtBeginning || StatCache.get() == 0) {
205 statCache->setNextStatCache(StatCache.take());
206 StatCache.reset(statCache);
207 return;
208 }
209
Chris Lattner226efd32010-11-23 19:19:34 +0000210 FileSystemStatCache *LastCache = StatCache.get();
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000211 while (LastCache->getNextStatCache())
212 LastCache = LastCache->getNextStatCache();
213
214 LastCache->setNextStatCache(statCache);
215}
216
Chris Lattner226efd32010-11-23 19:19:34 +0000217void FileManager::removeStatCache(FileSystemStatCache *statCache) {
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000218 if (!statCache)
219 return;
220
221 if (StatCache.get() == statCache) {
222 // This is the first stat cache.
223 StatCache.reset(StatCache->takeNextStatCache());
224 return;
225 }
226
227 // Find the stat cache in the list.
Chris Lattner226efd32010-11-23 19:19:34 +0000228 FileSystemStatCache *PrevCache = StatCache.get();
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000229 while (PrevCache && PrevCache->getNextStatCache() != statCache)
230 PrevCache = PrevCache->getNextStatCache();
Chris Lattner9624b692010-11-23 20:50:22 +0000231
232 assert(PrevCache && "Stat cache not found for removal");
233 PrevCache->setNextStatCache(statCache->getNextStatCache());
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000234}
235
Manuel Klimek3aad8552012-07-31 13:56:54 +0000236void FileManager::clearStatCaches() {
237 StatCache.reset(0);
238}
239
Douglas Gregor407e2122009-12-02 18:12:28 +0000240/// \brief Retrieve the directory that the given file name resides in.
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000241/// Filename can point to either a real file or a virtual file.
Douglas Gregor407e2122009-12-02 18:12:28 +0000242static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000243 StringRef Filename,
244 bool CacheFailure) {
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000245 if (Filename.empty())
246 return NULL;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000247
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000248 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
249 return NULL; // If Filename is a directory.
Benjamin Kramer3cf715d2010-11-21 11:32:22 +0000250
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000251 StringRef DirName = llvm::sys::path::parent_path(Filename);
Chris Lattner0c0e8042010-11-21 09:50:16 +0000252 // Use the current directory if file has no path component.
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000253 if (DirName.empty())
254 DirName = ".";
Douglas Gregor407e2122009-12-02 18:12:28 +0000255
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000256 return FileMgr.getDirectory(DirName, CacheFailure);
Douglas Gregor407e2122009-12-02 18:12:28 +0000257}
258
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000259/// Add all ancestors of the given path (pointing to either a file or
260/// a directory) as virtual directories.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000261void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
262 StringRef DirName = llvm::sys::path::parent_path(Path);
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000263 if (DirName.empty())
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000264 return;
265
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000266 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
267 SeenDirEntries.GetOrCreateValue(DirName);
268
269 // When caching a virtual directory, we always cache its ancestors
270 // at the same time. Therefore, if DirName is already in the cache,
271 // we don't need to recurse as its ancestors must also already be in
272 // the cache.
273 if (NamedDirEnt.getValue())
274 return;
275
276 // Add the virtual directory to the cache.
277 DirectoryEntry *UDE = new DirectoryEntry;
278 UDE->Name = NamedDirEnt.getKeyData();
279 NamedDirEnt.setValue(UDE);
280 VirtualDirectoryEntries.push_back(UDE);
281
282 // Recursively add the other ancestors.
283 addAncestorsAsVirtualDirs(DirName);
284}
285
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000286const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
287 bool CacheFailure) {
NAKAMURA Takumi8bd8ee72012-06-16 06:04:10 +0000288 // stat doesn't like trailing separators except for root directory.
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000289 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
290 // (though it can strip '\\')
NAKAMURA Takumi8bd8ee72012-06-16 06:04:10 +0000291 if (DirName.size() > 1 &&
292 DirName != llvm::sys::path::root_path(DirName) &&
293 llvm::sys::path::is_separator(DirName.back()))
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000294 DirName = DirName.substr(0, DirName.size()-1);
295
Chris Lattner22eb9722006-06-18 05:43:12 +0000296 ++NumDirLookups;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000297 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000298 SeenDirEntries.GetOrCreateValue(DirName);
Mike Stump11289f42009-09-09 15:08:12 +0000299
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000300 // See if there was already an entry in the map. Note that the map
301 // contains both virtual and real directories.
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000302 if (NamedDirEnt.getValue())
Ted Kremenek8d71e252008-01-11 20:42:05 +0000303 return NamedDirEnt.getValue() == NON_EXISTENT_DIR
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000304 ? 0 : NamedDirEnt.getValue();
Mike Stump11289f42009-09-09 15:08:12 +0000305
Chris Lattner22eb9722006-06-18 05:43:12 +0000306 ++NumDirCacheMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000307
Chris Lattneraf653752006-10-30 03:06:54 +0000308 // By default, initialize it to invalid.
Ted Kremenek8d71e252008-01-11 20:42:05 +0000309 NamedDirEnt.setValue(NON_EXISTENT_DIR);
Mike Stump11289f42009-09-09 15:08:12 +0000310
Chris Lattner43fd42e2006-10-30 03:40:58 +0000311 // Get the null-terminated directory name as stored as the key of the
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000312 // SeenDirEntries map.
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000313 const char *InterndDirName = NamedDirEnt.getKeyData();
Mike Stump11289f42009-09-09 15:08:12 +0000314
Chris Lattneraf653752006-10-30 03:06:54 +0000315 // Check to see if the directory exists.
Chris Lattner22eb9722006-06-18 05:43:12 +0000316 struct stat StatBuf;
Argyrios Kyrtzidis3b779372012-12-11 07:48:23 +0000317 if (getStatValue(InterndDirName, StatBuf, false, 0/*directory lookup*/)) {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000318 // There's no real directory at the given path.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000319 if (!CacheFailure)
320 SeenDirEntries.erase(DirName);
Chris Lattner22eb9722006-06-18 05:43:12 +0000321 return 0;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000322 }
Ted Kremenekd87eef82008-02-24 03:15:25 +0000323
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000324 // It exists. See if we have already opened a directory with the
325 // same inode (this occurs on Unix-like systems when one dir is
326 // symlinked to another, for example) or the same path (on
327 // Windows).
328 DirectoryEntry &UDE = UniqueRealDirs.getDirectory(InterndDirName, StatBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000329
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000330 NamedDirEnt.setValue(&UDE);
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000331 if (!UDE.getName()) {
332 // We don't have this directory yet, add it. We use the string
333 // key from the SeenDirEntries map as the string.
334 UDE.Name = InterndDirName;
335 }
Mike Stump11289f42009-09-09 15:08:12 +0000336
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000337 return &UDE;
Chris Lattner22eb9722006-06-18 05:43:12 +0000338}
339
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000340const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
341 bool CacheFailure) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000342 ++NumFileLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000343
Chris Lattner22eb9722006-06-18 05:43:12 +0000344 // See if there is already an entry in the map.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000345 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000346 SeenFileEntries.GetOrCreateValue(Filename);
Chris Lattner22eb9722006-06-18 05:43:12 +0000347
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000348 // See if there is already an entry in the map.
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000349 if (NamedFileEnt.getValue())
Ted Kremenek8d71e252008-01-11 20:42:05 +0000350 return NamedFileEnt.getValue() == NON_EXISTENT_FILE
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000351 ? 0 : NamedFileEnt.getValue();
Mike Stump11289f42009-09-09 15:08:12 +0000352
Chris Lattner22eb9722006-06-18 05:43:12 +0000353 ++NumFileCacheMisses;
354
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000355 // By default, initialize it to invalid.
Ted Kremenek8d71e252008-01-11 20:42:05 +0000356 NamedFileEnt.setValue(NON_EXISTENT_FILE);
Chris Lattner22eb9722006-06-18 05:43:12 +0000357
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000358 // Get the null-terminated file name as stored as the key of the
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000359 // SeenFileEntries map.
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000360 const char *InterndFileName = NamedFileEnt.getKeyData();
Mike Stump11289f42009-09-09 15:08:12 +0000361
Chris Lattner966b25b2010-11-23 20:30:42 +0000362 // Look up the directory for the file. When looking up something like
363 // sys/foo.h we'll discover all of the search directories that have a 'sys'
364 // subdirectory. This will let us avoid having to waste time on known-to-fail
365 // searches when we go to find sys/bar.h, because all the search directories
366 // without a 'sys' subdir will get a cached failure result.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000367 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
368 CacheFailure);
369 if (DirInfo == 0) { // Directory doesn't exist, file can't exist.
370 if (!CacheFailure)
371 SeenFileEntries.erase(Filename);
372
Douglas Gregor407e2122009-12-02 18:12:28 +0000373 return 0;
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000374 }
375
Chris Lattner22eb9722006-06-18 05:43:12 +0000376 // FIXME: Use the directory info to prune this, before doing the stat syscall.
377 // FIXME: This will reduce the # syscalls.
Mike Stump11289f42009-09-09 15:08:12 +0000378
Chris Lattner22eb9722006-06-18 05:43:12 +0000379 // Nope, there isn't. Check to see if the file exists.
Chris Lattnerdd278432010-11-23 21:17:56 +0000380 int FileDescriptor = -1;
Chris Lattner22eb9722006-06-18 05:43:12 +0000381 struct stat StatBuf;
Argyrios Kyrtzidis3b779372012-12-11 07:48:23 +0000382 if (getStatValue(InterndFileName, StatBuf, true,
383 openFile ? &FileDescriptor : 0)) {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000384 // There's no real file at the given path.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000385 if (!CacheFailure)
386 SeenFileEntries.erase(Filename);
387
Chris Lattner22eb9722006-06-18 05:43:12 +0000388 return 0;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000389 }
Mike Stump11289f42009-09-09 15:08:12 +0000390
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000391 if (FileDescriptor != -1 && !openFile) {
392 close(FileDescriptor);
393 FileDescriptor = -1;
394 }
395
Ted Kremenekf4c38c92007-12-18 22:29:39 +0000396 // It exists. See if we have already opened a file with the same inode.
Chris Lattner22eb9722006-06-18 05:43:12 +0000397 // This occurs when one dir is symlinked to another, for example.
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000398 FileEntry &UFE = UniqueRealFiles.getFile(InterndFileName, StatBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000399
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000400 NamedFileEnt.setValue(&UFE);
Chris Lattnerdd278432010-11-23 21:17:56 +0000401 if (UFE.getName()) { // Already have an entry with this inode, return it.
402 // If the stat process opened the file, close it to avoid a FD leak.
403 if (FileDescriptor != -1)
404 close(FileDescriptor);
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000405
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000406 return &UFE;
Chris Lattnerdd278432010-11-23 21:17:56 +0000407 }
Chris Lattner269c2322006-06-25 06:23:00 +0000408
Chris Lattner22eb9722006-06-18 05:43:12 +0000409 // Otherwise, we don't have this directory yet, add it.
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000410 // FIXME: Change the name to be a char* that points back to the
411 // 'SeenFileEntries' key.
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000412 UFE.Name = InterndFileName;
413 UFE.Size = StatBuf.st_size;
414 UFE.ModTime = StatBuf.st_mtime;
415 UFE.Dir = DirInfo;
416 UFE.UID = NextFileUID++;
Chris Lattnerdd278432010-11-23 21:17:56 +0000417 UFE.FD = FileDescriptor;
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000418 return &UFE;
Chris Lattner22eb9722006-06-18 05:43:12 +0000419}
420
Douglas Gregor407e2122009-12-02 18:12:28 +0000421const FileEntry *
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000422FileManager::getVirtualFile(StringRef Filename, off_t Size,
Chris Lattner5159f612010-11-23 08:35:12 +0000423 time_t ModificationTime) {
Douglas Gregor407e2122009-12-02 18:12:28 +0000424 ++NumFileLookups;
425
426 // See if there is already an entry in the map.
427 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000428 SeenFileEntries.GetOrCreateValue(Filename);
Douglas Gregor407e2122009-12-02 18:12:28 +0000429
430 // See if there is already an entry in the map.
Axel Naumann63fbaed2011-01-27 10:55:51 +0000431 if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
432 return NamedFileEnt.getValue();
Douglas Gregor407e2122009-12-02 18:12:28 +0000433
434 ++NumFileCacheMisses;
435
436 // By default, initialize it to invalid.
437 NamedFileEnt.setValue(NON_EXISTENT_FILE);
438
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000439 addAncestorsAsVirtualDirs(Filename);
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000440 FileEntry *UFE = 0;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000441
442 // Now that all ancestors of Filename are in the cache, the
443 // following call is guaranteed to find the DirectoryEntry from the
444 // cache.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000445 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
446 /*CacheFailure=*/true);
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000447 assert(DirInfo &&
448 "The directory of a virtual file should already be in the cache.");
Douglas Gregor407e2122009-12-02 18:12:28 +0000449
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000450 // Check to see if the file exists. If so, drop the virtual file
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000451 struct stat StatBuf;
452 const char *InterndFileName = NamedFileEnt.getKeyData();
Argyrios Kyrtzidis3b779372012-12-11 07:48:23 +0000453 if (getStatValue(InterndFileName, StatBuf, true, 0) == 0) {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000454 StatBuf.st_size = Size;
455 StatBuf.st_mtime = ModificationTime;
456 UFE = &UniqueRealFiles.getFile(InterndFileName, StatBuf);
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000457
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000458 NamedFileEnt.setValue(UFE);
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000459
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000460 // If we had already opened this file, close it now so we don't
461 // leak the descriptor. We're not going to use the file
462 // descriptor anyway, since this is a virtual file.
463 if (UFE->FD != -1) {
464 close(UFE->FD);
465 UFE->FD = -1;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000466 }
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000467
468 // If we already have an entry with this inode, return it.
469 if (UFE->getName())
470 return UFE;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000471 }
472
473 if (!UFE) {
474 UFE = new FileEntry();
475 VirtualFileEntries.push_back(UFE);
476 NamedFileEnt.setValue(UFE);
477 }
Douglas Gregor407e2122009-12-02 18:12:28 +0000478
Chris Lattner9624b692010-11-23 20:50:22 +0000479 UFE->Name = InterndFileName;
Douglas Gregor407e2122009-12-02 18:12:28 +0000480 UFE->Size = Size;
481 UFE->ModTime = ModificationTime;
482 UFE->Dir = DirInfo;
483 UFE->UID = NextFileUID++;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000484 UFE->FD = -1;
Douglas Gregor407e2122009-12-02 18:12:28 +0000485 return UFE;
486}
487
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000488void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
489 StringRef pathRef(path.data(), path.size());
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000490
Anders Carlsson9ba8fb12011-03-14 01:13:54 +0000491 if (FileSystemOpts.WorkingDir.empty()
492 || llvm::sys::path::is_absolute(pathRef))
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000493 return;
494
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000495 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000496 llvm::sys::path::append(NewPath, pathRef);
Chris Lattner6e640992010-11-23 04:45:28 +0000497 path = NewPath;
498}
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000499
Chris Lattner6e640992010-11-23 04:45:28 +0000500llvm::MemoryBuffer *FileManager::
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000501getBufferForFile(const FileEntry *Entry, std::string *ErrorStr,
502 bool isVolatile) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000503 OwningPtr<llvm::MemoryBuffer> Result;
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000504 llvm::error_code ec;
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44 +0000505
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000506 uint64_t FileSize = Entry->getSize();
507 // If there's a high enough chance that the file have changed since we
508 // got its size, force a stat before opening it.
509 if (isVolatile)
510 FileSize = -1;
511
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44 +0000512 const char *Filename = Entry->getName();
513 // If the file is already open, use the open file descriptor.
514 if (Entry->FD != -1) {
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000515 ec = llvm::MemoryBuffer::getOpenFile(Entry->FD, Filename, Result, FileSize);
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44 +0000516 if (ErrorStr)
517 *ErrorStr = ec.message();
518
519 close(Entry->FD);
520 Entry->FD = -1;
521 return Result.take();
522 }
523
524 // Otherwise, open the file.
525
Chris Lattner5ea7d072010-11-23 22:32:37 +0000526 if (FileSystemOpts.WorkingDir.empty()) {
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000527 ec = llvm::MemoryBuffer::getFile(Filename, Result, FileSize);
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000528 if (ec && ErrorStr)
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000529 *ErrorStr = ec.message();
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000530 return Result.take();
Chris Lattner5ea7d072010-11-23 22:32:37 +0000531 }
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000532
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000533 SmallString<128> FilePath(Entry->getName());
Anders Carlsson878b3e22011-03-07 01:28:33 +0000534 FixupRelativePath(FilePath);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000535 ec = llvm::MemoryBuffer::getFile(FilePath.str(), Result, FileSize);
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000536 if (ec && ErrorStr)
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000537 *ErrorStr = ec.message();
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000538 return Result.take();
Chris Lattner26b5c192010-11-23 09:19:42 +0000539}
540
541llvm::MemoryBuffer *FileManager::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000542getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000543 OwningPtr<llvm::MemoryBuffer> Result;
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000544 llvm::error_code ec;
545 if (FileSystemOpts.WorkingDir.empty()) {
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000546 ec = llvm::MemoryBuffer::getFile(Filename, Result);
547 if (ec && ErrorStr)
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000548 *ErrorStr = ec.message();
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000549 return Result.take();
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000550 }
551
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000552 SmallString<128> FilePath(Filename);
Anders Carlsson878b3e22011-03-07 01:28:33 +0000553 FixupRelativePath(FilePath);
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000554 ec = llvm::MemoryBuffer::getFile(FilePath.c_str(), Result);
555 if (ec && ErrorStr)
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000556 *ErrorStr = ec.message();
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000557 return Result.take();
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000558}
559
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000560/// getStatValue - Get the 'stat' information for the specified path,
561/// using the cache to accelerate it if possible. This returns true
562/// if the path points to a virtual file or does not exist, or returns
563/// false if it's an existent real file. If FileDescriptor is NULL,
564/// do directory look-up instead of file look-up.
Chris Lattner9624b692010-11-23 20:50:22 +0000565bool FileManager::getStatValue(const char *Path, struct stat &StatBuf,
Argyrios Kyrtzidis3b779372012-12-11 07:48:23 +0000566 bool isFile, int *FileDescriptor) {
Chris Lattner226efd32010-11-23 19:19:34 +0000567 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
568 // absolute!
Chris Lattner5769c3d2010-11-23 19:56:39 +0000569 if (FileSystemOpts.WorkingDir.empty())
Argyrios Kyrtzidis3b779372012-12-11 07:48:23 +0000570 return FileSystemStatCache::get(Path, StatBuf, isFile, FileDescriptor,
Chris Lattnerdd278432010-11-23 21:17:56 +0000571 StatCache.get());
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000572
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000573 SmallString<128> FilePath(Path);
Anders Carlsson878b3e22011-03-07 01:28:33 +0000574 FixupRelativePath(FilePath);
Chris Lattner5769c3d2010-11-23 19:56:39 +0000575
Argyrios Kyrtzidis3b779372012-12-11 07:48:23 +0000576 return FileSystemStatCache::get(FilePath.c_str(), StatBuf,
577 isFile, FileDescriptor, StatCache.get());
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000578}
579
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000580bool FileManager::getNoncachedStatValue(StringRef Path,
Anders Carlsson5e368402011-03-18 19:23:19 +0000581 struct stat &StatBuf) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000582 SmallString<128> FilePath(Path);
Anders Carlsson5e368402011-03-18 19:23:19 +0000583 FixupRelativePath(FilePath);
584
585 return ::stat(FilePath.c_str(), &StatBuf) != 0;
586}
587
Axel Naumannb3074002012-07-10 16:50:27 +0000588void FileManager::invalidateCache(const FileEntry *Entry) {
589 assert(Entry && "Cannot invalidate a NULL FileEntry");
Axel Naumann38179d92012-06-27 09:17:42 +0000590
591 SeenFileEntries.erase(Entry->getName());
Axel Naumannb3074002012-07-10 16:50:27 +0000592
593 // FileEntry invalidation should not block future optimizations in the file
594 // caches. Possible alternatives are cache truncation (invalidate last N) or
595 // invalidation of the whole cache.
596 UniqueRealFiles.erase(Entry);
Axel Naumann38179d92012-06-27 09:17:42 +0000597}
598
599
Douglas Gregor09b69892011-02-10 17:09:37 +0000600void FileManager::GetUniqueIDMapping(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000601 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
Douglas Gregor09b69892011-02-10 17:09:37 +0000602 UIDToFiles.clear();
603 UIDToFiles.resize(NextFileUID);
604
605 // Map file entries
606 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000607 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
Douglas Gregor09b69892011-02-10 17:09:37 +0000608 FE != FEEnd; ++FE)
609 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
610 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
611
612 // Map virtual file entries
Craig Topper2341c0d2013-07-04 03:08:24 +0000613 for (SmallVectorImpl<FileEntry *>::const_iterator
Douglas Gregor09b69892011-02-10 17:09:37 +0000614 VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
615 VFE != VFEEnd; ++VFE)
616 if (*VFE && *VFE != NON_EXISTENT_FILE)
617 UIDToFiles[(*VFE)->getUID()] = *VFE;
618}
Chris Lattner226efd32010-11-23 19:19:34 +0000619
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000620void FileManager::modifyFileEntry(FileEntry *File,
621 off_t Size, time_t ModificationTime) {
622 File->Size = Size;
623 File->ModTime = ModificationTime;
624}
625
Douglas Gregore00c8b22013-01-26 00:55:12 +0000626StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
627 // FIXME: use llvm::sys::fs::canonical() when it gets implemented
628#ifdef LLVM_ON_UNIX
629 llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
630 = CanonicalDirNames.find(Dir);
631 if (Known != CanonicalDirNames.end())
632 return Known->second;
633
634 StringRef CanonicalName(Dir->getName());
635 char CanonicalNameBuf[PATH_MAX];
636 if (realpath(Dir->getName(), CanonicalNameBuf)) {
637 unsigned Len = strlen(CanonicalNameBuf);
638 char *Mem = static_cast<char *>(CanonicalNameStorage.Allocate(Len, 1));
639 memcpy(Mem, CanonicalNameBuf, Len);
640 CanonicalName = StringRef(Mem, Len);
641 }
642
643 CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
644 return CanonicalName;
645#else
646 return StringRef(Dir->getName());
647#endif
648}
Chris Lattner226efd32010-11-23 19:19:34 +0000649
Chris Lattner22eb9722006-06-18 05:43:12 +0000650void FileManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000651 llvm::errs() << "\n*** File Manager Stats:\n";
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000652 llvm::errs() << UniqueRealFiles.size() << " real files found, "
653 << UniqueRealDirs.size() << " real dirs found.\n";
654 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
655 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000656 llvm::errs() << NumDirLookups << " dir lookups, "
657 << NumDirCacheMisses << " dir cache misses.\n";
658 llvm::errs() << NumFileLookups << " file lookups, "
659 << NumFileCacheMisses << " file cache misses.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000660
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000661 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
Chris Lattner22eb9722006-06-18 05:43:12 +0000662}