blob: 4c84f1b6ad28e701091f958062d6608d1b9bdad4 [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"
Adrian Prantl075bf562015-07-09 02:53:05 +000022#include "clang/Frontend/PCHContainerOperations.h"
Chris Lattner2f4a89a2006-10-30 03:55:17 +000023#include "llvm/ADT/SmallString.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "llvm/Config/llvm-config.h"
Michael J. Spencer740857f2010-12-21 16:45:57 +000025#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +000026#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000027#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "llvm/Support/raw_ostream.h"
Benjamin Kramer26db6482009-09-05 09:49:39 +000029#include <map>
30#include <set>
31#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000032#include <system_error>
Chris Lattner278038b2010-11-23 21:53:15 +000033
Chris Lattner22eb9722006-06-18 05:43:12 +000034using namespace clang;
35
Ted Kremenek8d71e252008-01-11 20:42:05 +000036/// NON_EXISTENT_DIR - A special value distinct from null that is used to
Chris Lattneraf653752006-10-30 03:06:54 +000037/// represent a dir name that doesn't exist on the disk.
Ted Kremenek8d71e252008-01-11 20:42:05 +000038#define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
Chris Lattneraf653752006-10-30 03:06:54 +000039
Chris Lattner9624b692010-11-23 20:50:22 +000040/// NON_EXISTENT_FILE - A special value distinct from null that is used to
41/// represent a filename that doesn't exist on the disk.
42#define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
43
Ted Kremenek5c04bd82009-01-28 00:27:31 +000044//===----------------------------------------------------------------------===//
45// Common logic.
46//===----------------------------------------------------------------------===//
Ted Kremenekd87eef82008-02-24 03:15:25 +000047
Ben Langmuirc8130a72014-02-20 21:59:23 +000048FileManager::FileManager(const FileSystemOptions &FSO,
49 IntrusiveRefCntPtr<vfs::FileSystem> FS)
50 : FS(FS), FileSystemOpts(FSO),
Zhanyong Wane1dd3e22011-02-11 18:44:49 +000051 SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
Ted Kremenekd87eef82008-02-24 03:15:25 +000052 NumDirLookups = NumFileLookups = 0;
53 NumDirCacheMisses = NumFileCacheMisses = 0;
Ben Langmuirc8130a72014-02-20 21:59:23 +000054
55 // If the caller doesn't provide a virtual file system, just grab the real
56 // file system.
57 if (!FS)
58 this->FS = vfs::getRealFileSystem();
Ted Kremenekd87eef82008-02-24 03:15:25 +000059}
60
61FileManager::~FileManager() {
Chris Lattner966b25b2010-11-23 20:30:42 +000062 for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
63 delete VirtualFileEntries[i];
Zhanyong Wane1dd3e22011-02-11 18:44:49 +000064 for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
65 delete VirtualDirectoryEntries[i];
Ted Kremenekd87eef82008-02-24 03:15:25 +000066}
67
David Blaikie23430cc2014-08-11 21:29:24 +000068void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache,
Chris Lattner226efd32010-11-23 19:19:34 +000069 bool AtBeginning) {
Douglas Gregord2eb58a2009-10-16 18:18:30 +000070 assert(statCache && "No stat cache provided?");
Craig Topperf1186c52014-05-08 06:41:40 +000071 if (AtBeginning || !StatCache.get()) {
David Blaikie23430cc2014-08-11 21:29:24 +000072 statCache->setNextStatCache(std::move(StatCache));
73 StatCache = std::move(statCache);
Douglas Gregord2eb58a2009-10-16 18:18:30 +000074 return;
75 }
76
Chris Lattner226efd32010-11-23 19:19:34 +000077 FileSystemStatCache *LastCache = StatCache.get();
Douglas Gregord2eb58a2009-10-16 18:18:30 +000078 while (LastCache->getNextStatCache())
79 LastCache = LastCache->getNextStatCache();
David Blaikie23430cc2014-08-11 21:29:24 +000080
81 LastCache->setNextStatCache(std::move(statCache));
Douglas Gregord2eb58a2009-10-16 18:18:30 +000082}
83
Chris Lattner226efd32010-11-23 19:19:34 +000084void FileManager::removeStatCache(FileSystemStatCache *statCache) {
Douglas Gregord2eb58a2009-10-16 18:18:30 +000085 if (!statCache)
86 return;
87
88 if (StatCache.get() == statCache) {
89 // This is the first stat cache.
David Blaikiedd0e1e82014-08-10 16:57:11 +000090 StatCache = StatCache->takeNextStatCache();
Douglas Gregord2eb58a2009-10-16 18:18:30 +000091 return;
92 }
93
94 // Find the stat cache in the list.
Chris Lattner226efd32010-11-23 19:19:34 +000095 FileSystemStatCache *PrevCache = StatCache.get();
Douglas Gregord2eb58a2009-10-16 18:18:30 +000096 while (PrevCache && PrevCache->getNextStatCache() != statCache)
97 PrevCache = PrevCache->getNextStatCache();
Chris Lattner9624b692010-11-23 20:50:22 +000098
99 assert(PrevCache && "Stat cache not found for removal");
David Blaikie23430cc2014-08-11 21:29:24 +0000100 PrevCache->setNextStatCache(statCache->takeNextStatCache());
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000101}
102
Manuel Klimek3aad8552012-07-31 13:56:54 +0000103void FileManager::clearStatCaches() {
David Blaikie3875a822014-07-19 01:06:45 +0000104 StatCache.reset();
Manuel Klimek3aad8552012-07-31 13:56:54 +0000105}
106
Douglas Gregor407e2122009-12-02 18:12:28 +0000107/// \brief Retrieve the directory that the given file name resides in.
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000108/// Filename can point to either a real file or a virtual file.
Douglas Gregor407e2122009-12-02 18:12:28 +0000109static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000110 StringRef Filename,
111 bool CacheFailure) {
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000112 if (Filename.empty())
Craig Topperf1186c52014-05-08 06:41:40 +0000113 return nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000114
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000115 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
Craig Topperf1186c52014-05-08 06:41:40 +0000116 return nullptr; // If Filename is a directory.
Benjamin Kramer3cf715d2010-11-21 11:32:22 +0000117
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000118 StringRef DirName = llvm::sys::path::parent_path(Filename);
Chris Lattner0c0e8042010-11-21 09:50:16 +0000119 // Use the current directory if file has no path component.
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000120 if (DirName.empty())
121 DirName = ".";
Douglas Gregor407e2122009-12-02 18:12:28 +0000122
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000123 return FileMgr.getDirectory(DirName, CacheFailure);
Douglas Gregor407e2122009-12-02 18:12:28 +0000124}
125
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000126/// Add all ancestors of the given path (pointing to either a file or
127/// a directory) as virtual directories.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000128void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
129 StringRef DirName = llvm::sys::path::parent_path(Path);
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000130 if (DirName.empty())
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000131 return;
132
David Blaikie13156b62014-11-19 03:06:06 +0000133 auto &NamedDirEnt =
134 *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000135
136 // When caching a virtual directory, we always cache its ancestors
137 // at the same time. Therefore, if DirName is already in the cache,
138 // we don't need to recurse as its ancestors must also already be in
139 // the cache.
David Blaikie13156b62014-11-19 03:06:06 +0000140 if (NamedDirEnt.second)
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000141 return;
142
143 // Add the virtual directory to the cache.
144 DirectoryEntry *UDE = new DirectoryEntry;
David Blaikie13156b62014-11-19 03:06:06 +0000145 UDE->Name = NamedDirEnt.first().data();
146 NamedDirEnt.second = UDE;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000147 VirtualDirectoryEntries.push_back(UDE);
148
149 // Recursively add the other ancestors.
150 addAncestorsAsVirtualDirs(DirName);
151}
152
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000153const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
154 bool CacheFailure) {
NAKAMURA Takumi8bd8ee72012-06-16 06:04:10 +0000155 // stat doesn't like trailing separators except for root directory.
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000156 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
157 // (though it can strip '\\')
NAKAMURA Takumi8bd8ee72012-06-16 06:04:10 +0000158 if (DirName.size() > 1 &&
159 DirName != llvm::sys::path::root_path(DirName) &&
160 llvm::sys::path::is_separator(DirName.back()))
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000161 DirName = DirName.substr(0, DirName.size()-1);
Rafael Espindolaee305462013-07-29 15:47:24 +0000162#ifdef LLVM_ON_WIN32
163 // Fixing a problem with "clang C:test.c" on Windows.
164 // Stat("C:") does not recognize "C:" as a valid directory
165 std::string DirNameStr;
166 if (DirName.size() > 1 && DirName.back() == ':' &&
167 DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
168 DirNameStr = DirName.str() + '.';
169 DirName = DirNameStr;
170 }
171#endif
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000172
Chris Lattner22eb9722006-06-18 05:43:12 +0000173 ++NumDirLookups;
David Blaikie13156b62014-11-19 03:06:06 +0000174 auto &NamedDirEnt =
175 *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
Mike Stump11289f42009-09-09 15:08:12 +0000176
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000177 // See if there was already an entry in the map. Note that the map
178 // contains both virtual and real directories.
David Blaikie13156b62014-11-19 03:06:06 +0000179 if (NamedDirEnt.second)
180 return NamedDirEnt.second == NON_EXISTENT_DIR ? nullptr
181 : NamedDirEnt.second;
Mike Stump11289f42009-09-09 15:08:12 +0000182
Chris Lattner22eb9722006-06-18 05:43:12 +0000183 ++NumDirCacheMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000184
Chris Lattneraf653752006-10-30 03:06:54 +0000185 // By default, initialize it to invalid.
David Blaikie13156b62014-11-19 03:06:06 +0000186 NamedDirEnt.second = NON_EXISTENT_DIR;
Mike Stump11289f42009-09-09 15:08:12 +0000187
Chris Lattner43fd42e2006-10-30 03:40:58 +0000188 // Get the null-terminated directory name as stored as the key of the
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000189 // SeenDirEntries map.
David Blaikie13156b62014-11-19 03:06:06 +0000190 const char *InterndDirName = NamedDirEnt.first().data();
Mike Stump11289f42009-09-09 15:08:12 +0000191
Chris Lattneraf653752006-10-30 03:06:54 +0000192 // Check to see if the directory exists.
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000193 FileData Data;
Craig Topperf1186c52014-05-08 06:41:40 +0000194 if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000195 // There's no real directory at the given path.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000196 if (!CacheFailure)
197 SeenDirEntries.erase(DirName);
Craig Topperf1186c52014-05-08 06:41:40 +0000198 return nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000199 }
Ted Kremenekd87eef82008-02-24 03:15:25 +0000200
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000201 // It exists. See if we have already opened a directory with the
202 // same inode (this occurs on Unix-like systems when one dir is
203 // symlinked to another, for example) or the same path (on
204 // Windows).
Ben Langmuirc9b72342014-02-27 22:21:32 +0000205 DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID];
Mike Stump11289f42009-09-09 15:08:12 +0000206
David Blaikie13156b62014-11-19 03:06:06 +0000207 NamedDirEnt.second = &UDE;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000208 if (!UDE.getName()) {
209 // We don't have this directory yet, add it. We use the string
210 // key from the SeenDirEntries map as the string.
211 UDE.Name = InterndDirName;
212 }
Mike Stump11289f42009-09-09 15:08:12 +0000213
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000214 return &UDE;
Chris Lattner22eb9722006-06-18 05:43:12 +0000215}
216
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000217const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
218 bool CacheFailure) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000219 ++NumFileLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000220
Chris Lattner22eb9722006-06-18 05:43:12 +0000221 // See if there is already an entry in the map.
David Blaikie13156b62014-11-19 03:06:06 +0000222 auto &NamedFileEnt =
223 *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
Chris Lattner22eb9722006-06-18 05:43:12 +0000224
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000225 // See if there is already an entry in the map.
David Blaikie13156b62014-11-19 03:06:06 +0000226 if (NamedFileEnt.second)
227 return NamedFileEnt.second == NON_EXISTENT_FILE ? nullptr
228 : NamedFileEnt.second;
Mike Stump11289f42009-09-09 15:08:12 +0000229
Chris Lattner22eb9722006-06-18 05:43:12 +0000230 ++NumFileCacheMisses;
231
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000232 // By default, initialize it to invalid.
David Blaikie13156b62014-11-19 03:06:06 +0000233 NamedFileEnt.second = NON_EXISTENT_FILE;
Chris Lattner22eb9722006-06-18 05:43:12 +0000234
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000235 // Get the null-terminated file name as stored as the key of the
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000236 // SeenFileEntries map.
David Blaikie13156b62014-11-19 03:06:06 +0000237 const char *InterndFileName = NamedFileEnt.first().data();
Mike Stump11289f42009-09-09 15:08:12 +0000238
Chris Lattner966b25b2010-11-23 20:30:42 +0000239 // Look up the directory for the file. When looking up something like
240 // sys/foo.h we'll discover all of the search directories that have a 'sys'
241 // subdirectory. This will let us avoid having to waste time on known-to-fail
242 // searches when we go to find sys/bar.h, because all the search directories
243 // without a 'sys' subdir will get a cached failure result.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000244 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
245 CacheFailure);
Craig Topperf1186c52014-05-08 06:41:40 +0000246 if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000247 if (!CacheFailure)
248 SeenFileEntries.erase(Filename);
Craig Topperf1186c52014-05-08 06:41:40 +0000249
250 return nullptr;
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000251 }
252
Chris Lattner22eb9722006-06-18 05:43:12 +0000253 // FIXME: Use the directory info to prune this, before doing the stat syscall.
254 // FIXME: This will reduce the # syscalls.
Mike Stump11289f42009-09-09 15:08:12 +0000255
Chris Lattner22eb9722006-06-18 05:43:12 +0000256 // Nope, there isn't. Check to see if the file exists.
David Blaikie326ffb32014-07-08 15:46:02 +0000257 std::unique_ptr<vfs::File> F;
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000258 FileData Data;
Craig Topperf1186c52014-05-08 06:41:40 +0000259 if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000260 // There's no real file at the given path.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000261 if (!CacheFailure)
262 SeenFileEntries.erase(Filename);
Craig Topperf1186c52014-05-08 06:41:40 +0000263
264 return nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000265 }
Mike Stump11289f42009-09-09 15:08:12 +0000266
Patrik Hagglundab01d4b2014-02-21 07:23:53 +0000267 assert((openFile || !F) && "undesired open file");
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000268
Ted Kremenekf4c38c92007-12-18 22:29:39 +0000269 // It exists. See if we have already opened a file with the same inode.
Chris Lattner22eb9722006-06-18 05:43:12 +0000270 // This occurs when one dir is symlinked to another, for example.
Ben Langmuirc9b72342014-02-27 22:21:32 +0000271 FileEntry &UFE = UniqueRealFiles[Data.UniqueID];
Mike Stump11289f42009-09-09 15:08:12 +0000272
David Blaikie13156b62014-11-19 03:06:06 +0000273 NamedFileEnt.second = &UFE;
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000274
275 // If the name returned by getStatValue is different than Filename, re-intern
276 // the name.
277 if (Data.Name != Filename) {
David Blaikie13156b62014-11-19 03:06:06 +0000278 auto &NamedFileEnt =
279 *SeenFileEntries.insert(std::make_pair(Data.Name, nullptr)).first;
280 if (!NamedFileEnt.second)
281 NamedFileEnt.second = &UFE;
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000282 else
David Blaikie13156b62014-11-19 03:06:06 +0000283 assert(NamedFileEnt.second == &UFE &&
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000284 "filename from getStatValue() refers to wrong file");
David Blaikie13156b62014-11-19 03:06:06 +0000285 InterndFileName = NamedFileEnt.first().data();
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000286 }
287
Ben Langmuirc8a71462014-02-27 17:23:33 +0000288 if (UFE.isValid()) { // Already have an entry with this inode, return it.
Ben Langmuir5de00f32014-05-23 18:15:47 +0000289
290 // FIXME: this hack ensures that if we look up a file by a virtual path in
291 // the VFS that the getDir() will have the virtual path, even if we found
292 // the file by a 'real' path first. This is required in order to find a
293 // module's structure when its headers/module map are mapped in the VFS.
294 // We should remove this as soon as we can properly support a file having
295 // multiple names.
296 if (DirInfo != UFE.Dir && Data.IsVFSMapped)
297 UFE.Dir = DirInfo;
298
Manuel Klimekc0ff9902014-08-13 12:34:41 +0000299 // Always update the name to use the last name by which a file was accessed.
300 // FIXME: Neither this nor always using the first name is correct; we want
301 // to switch towards a design where we return a FileName object that
302 // encapsulates both the name by which the file was accessed and the
303 // corresponding FileEntry.
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000304 UFE.Name = InterndFileName;
Manuel Klimekc0ff9902014-08-13 12:34:41 +0000305
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000306 return &UFE;
Chris Lattnerdd278432010-11-23 21:17:56 +0000307 }
Chris Lattner269c2322006-06-25 06:23:00 +0000308
Ben Langmuirc9b72342014-02-27 22:21:32 +0000309 // Otherwise, we don't have this file yet, add it.
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000310 UFE.Name = InterndFileName;
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000311 UFE.Size = Data.Size;
312 UFE.ModTime = Data.ModTime;
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000313 UFE.Dir = DirInfo;
314 UFE.UID = NextFileUID++;
Ben Langmuirc9b72342014-02-27 22:21:32 +0000315 UFE.UniqueID = Data.UniqueID;
316 UFE.IsNamedPipe = Data.IsNamedPipe;
317 UFE.InPCH = Data.InPCH;
David Blaikie326ffb32014-07-08 15:46:02 +0000318 UFE.File = std::move(F);
Ben Langmuirc8a71462014-02-27 17:23:33 +0000319 UFE.IsValid = true;
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000320 return &UFE;
Chris Lattner22eb9722006-06-18 05:43:12 +0000321}
322
Douglas Gregor407e2122009-12-02 18:12:28 +0000323const FileEntry *
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000324FileManager::getVirtualFile(StringRef Filename, off_t Size,
Chris Lattner5159f612010-11-23 08:35:12 +0000325 time_t ModificationTime) {
Douglas Gregor407e2122009-12-02 18:12:28 +0000326 ++NumFileLookups;
327
328 // See if there is already an entry in the map.
David Blaikie13156b62014-11-19 03:06:06 +0000329 auto &NamedFileEnt =
330 *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
Douglas Gregor407e2122009-12-02 18:12:28 +0000331
332 // See if there is already an entry in the map.
David Blaikie13156b62014-11-19 03:06:06 +0000333 if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE)
334 return NamedFileEnt.second;
Douglas Gregor407e2122009-12-02 18:12:28 +0000335
336 ++NumFileCacheMisses;
337
338 // By default, initialize it to invalid.
David Blaikie13156b62014-11-19 03:06:06 +0000339 NamedFileEnt.second = NON_EXISTENT_FILE;
Douglas Gregor407e2122009-12-02 18:12:28 +0000340
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000341 addAncestorsAsVirtualDirs(Filename);
Craig Topperf1186c52014-05-08 06:41:40 +0000342 FileEntry *UFE = nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000343
344 // Now that all ancestors of Filename are in the cache, the
345 // following call is guaranteed to find the DirectoryEntry from the
346 // cache.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000347 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
348 /*CacheFailure=*/true);
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000349 assert(DirInfo &&
350 "The directory of a virtual file should already be in the cache.");
Douglas Gregor407e2122009-12-02 18:12:28 +0000351
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000352 // Check to see if the file exists. If so, drop the virtual file
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000353 FileData Data;
David Blaikie13156b62014-11-19 03:06:06 +0000354 const char *InterndFileName = NamedFileEnt.first().data();
Craig Topperf1186c52014-05-08 06:41:40 +0000355 if (getStatValue(InterndFileName, Data, true, nullptr) == 0) {
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000356 Data.Size = Size;
357 Data.ModTime = ModificationTime;
Ben Langmuirc9b72342014-02-27 22:21:32 +0000358 UFE = &UniqueRealFiles[Data.UniqueID];
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000359
David Blaikie13156b62014-11-19 03:06:06 +0000360 NamedFileEnt.second = UFE;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000361
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000362 // If we had already opened this file, close it now so we don't
363 // leak the descriptor. We're not going to use the file
364 // descriptor anyway, since this is a virtual file.
Ben Langmuirc8130a72014-02-20 21:59:23 +0000365 if (UFE->File)
366 UFE->closeFile();
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000367
368 // If we already have an entry with this inode, return it.
Ben Langmuirc8a71462014-02-27 17:23:33 +0000369 if (UFE->isValid())
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000370 return UFE;
Ben Langmuirc9b72342014-02-27 22:21:32 +0000371
372 UFE->UniqueID = Data.UniqueID;
373 UFE->IsNamedPipe = Data.IsNamedPipe;
374 UFE->InPCH = Data.InPCH;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000375 }
376
377 if (!UFE) {
378 UFE = new FileEntry();
379 VirtualFileEntries.push_back(UFE);
David Blaikie13156b62014-11-19 03:06:06 +0000380 NamedFileEnt.second = UFE;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000381 }
Douglas Gregor407e2122009-12-02 18:12:28 +0000382
Chris Lattner9624b692010-11-23 20:50:22 +0000383 UFE->Name = InterndFileName;
Douglas Gregor407e2122009-12-02 18:12:28 +0000384 UFE->Size = Size;
385 UFE->ModTime = ModificationTime;
386 UFE->Dir = DirInfo;
387 UFE->UID = NextFileUID++;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000388 UFE->File.reset();
Douglas Gregor407e2122009-12-02 18:12:28 +0000389 return UFE;
390}
391
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000392void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
393 StringRef pathRef(path.data(), path.size());
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000394
Anders Carlsson9ba8fb12011-03-14 01:13:54 +0000395 if (FileSystemOpts.WorkingDir.empty()
396 || llvm::sys::path::is_absolute(pathRef))
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000397 return;
398
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000399 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000400 llvm::sys::path::append(NewPath, pathRef);
Chris Lattner6e640992010-11-23 04:45:28 +0000401 path = NewPath;
402}
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000403
Benjamin Kramera8857962014-10-26 22:44:13 +0000404llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
405FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
406 bool ShouldCloseOpenFile) {
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000407 uint64_t FileSize = Entry->getSize();
408 // If there's a high enough chance that the file have changed since we
409 // got its size, force a stat before opening it.
410 if (isVolatile)
411 FileSize = -1;
412
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44 +0000413 const char *Filename = Entry->getName();
414 // If the file is already open, use the open file descriptor.
Ben Langmuirc8130a72014-02-20 21:59:23 +0000415 if (Entry->File) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000416 auto Result =
417 Entry->File->getBuffer(Filename, FileSize,
418 /*RequiresNullTerminator=*/true, isVolatile);
Ben Langmuir9801b252014-06-20 00:24:56 +0000419 // FIXME: we need a set of APIs that can make guarantees about whether a
420 // FileEntry is open or not.
421 if (ShouldCloseOpenFile)
422 Entry->closeFile();
Rafael Espindola6406f7b2014-08-26 19:54:40 +0000423 return Result;
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44 +0000424 }
425
426 // Otherwise, open the file.
427
Benjamin Kramera8857962014-10-26 22:44:13 +0000428 if (FileSystemOpts.WorkingDir.empty())
429 return FS->getBufferForFile(Filename, FileSize,
430 /*RequiresNullTerminator=*/true, isVolatile);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000431
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000432 SmallString<128> FilePath(Entry->getName());
Anders Carlsson878b3e22011-03-07 01:28:33 +0000433 FixupRelativePath(FilePath);
Yaron Keren92e1b622015-03-18 10:17:07 +0000434 return FS->getBufferForFile(FilePath, FileSize,
Benjamin Kramera8857962014-10-26 22:44:13 +0000435 /*RequiresNullTerminator=*/true, isVolatile);
Chris Lattner26b5c192010-11-23 09:19:42 +0000436}
437
Benjamin Kramera8857962014-10-26 22:44:13 +0000438llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
439FileManager::getBufferForFile(StringRef Filename) {
440 if (FileSystemOpts.WorkingDir.empty())
441 return FS->getBufferForFile(Filename);
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000442
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000443 SmallString<128> FilePath(Filename);
Anders Carlsson878b3e22011-03-07 01:28:33 +0000444 FixupRelativePath(FilePath);
Benjamin Kramera8857962014-10-26 22:44:13 +0000445 return FS->getBufferForFile(FilePath.c_str());
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000446}
447
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000448/// getStatValue - Get the 'stat' information for the specified path,
449/// using the cache to accelerate it if possible. This returns true
450/// if the path points to a virtual file or does not exist, or returns
451/// false if it's an existent real file. If FileDescriptor is NULL,
452/// do directory look-up instead of file look-up.
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000453bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile,
David Blaikie326ffb32014-07-08 15:46:02 +0000454 std::unique_ptr<vfs::File> *F) {
Chris Lattner226efd32010-11-23 19:19:34 +0000455 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
456 // absolute!
Chris Lattner5769c3d2010-11-23 19:56:39 +0000457 if (FileSystemOpts.WorkingDir.empty())
Ben Langmuirc8130a72014-02-20 21:59:23 +0000458 return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000459
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000460 SmallString<128> FilePath(Path);
Anders Carlsson878b3e22011-03-07 01:28:33 +0000461 FixupRelativePath(FilePath);
Chris Lattner5769c3d2010-11-23 19:56:39 +0000462
Ben Langmuirc8130a72014-02-20 21:59:23 +0000463 return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
464 StatCache.get(), *FS);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000465}
466
Rafael Espindolae4777f42013-07-29 18:22:23 +0000467bool FileManager::getNoncachedStatValue(StringRef Path,
Ben Langmuirc8130a72014-02-20 21:59:23 +0000468 vfs::Status &Result) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000469 SmallString<128> FilePath(Path);
Anders Carlsson5e368402011-03-18 19:23:19 +0000470 FixupRelativePath(FilePath);
471
Ben Langmuirc8130a72014-02-20 21:59:23 +0000472 llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str());
473 if (!S)
474 return true;
475 Result = *S;
476 return false;
Anders Carlsson5e368402011-03-18 19:23:19 +0000477}
478
Axel Naumannb3074002012-07-10 16:50:27 +0000479void FileManager::invalidateCache(const FileEntry *Entry) {
480 assert(Entry && "Cannot invalidate a NULL FileEntry");
Axel Naumann38179d92012-06-27 09:17:42 +0000481
482 SeenFileEntries.erase(Entry->getName());
Axel Naumannb3074002012-07-10 16:50:27 +0000483
484 // FileEntry invalidation should not block future optimizations in the file
485 // caches. Possible alternatives are cache truncation (invalidate last N) or
486 // invalidation of the whole cache.
Ben Langmuirc9b72342014-02-27 22:21:32 +0000487 UniqueRealFiles.erase(Entry->getUniqueID());
Axel Naumann38179d92012-06-27 09:17:42 +0000488}
489
490
Douglas Gregor09b69892011-02-10 17:09:37 +0000491void FileManager::GetUniqueIDMapping(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000492 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
Douglas Gregor09b69892011-02-10 17:09:37 +0000493 UIDToFiles.clear();
494 UIDToFiles.resize(NextFileUID);
495
496 // Map file entries
497 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000498 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
Douglas Gregor09b69892011-02-10 17:09:37 +0000499 FE != FEEnd; ++FE)
500 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
501 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
502
503 // Map virtual file entries
Craig Topper2341c0d2013-07-04 03:08:24 +0000504 for (SmallVectorImpl<FileEntry *>::const_iterator
Douglas Gregor09b69892011-02-10 17:09:37 +0000505 VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
506 VFE != VFEEnd; ++VFE)
507 if (*VFE && *VFE != NON_EXISTENT_FILE)
508 UIDToFiles[(*VFE)->getUID()] = *VFE;
509}
Chris Lattner226efd32010-11-23 19:19:34 +0000510
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000511void FileManager::modifyFileEntry(FileEntry *File,
512 off_t Size, time_t ModificationTime) {
513 File->Size = Size;
514 File->ModTime = ModificationTime;
515}
516
Sean Silvab963ded2015-07-30 00:26:34 +0000517/// Remove '.' and '..' path components from the given absolute path.
Richard Smith54cc3c22014-12-11 20:50:24 +0000518/// \return \c true if any changes were made.
519// FIXME: Move this to llvm::sys::path.
Sean Silva3e36e502015-07-30 00:52:32 +0000520bool FileManager::removeDotPaths(SmallVectorImpl<char> &Path, bool RemoveDotDot) {
Richard Smith54cc3c22014-12-11 20:50:24 +0000521 using namespace llvm::sys;
522
523 SmallVector<StringRef, 16> ComponentStack;
524 StringRef P(Path.data(), Path.size());
525
526 // Skip the root path, then look for traversal in the components.
527 StringRef Rel = path::relative_path(P);
Richard Smith54cc3c22014-12-11 20:50:24 +0000528 for (StringRef C : llvm::make_range(path::begin(Rel), path::end(Rel))) {
Sean Silvab963ded2015-07-30 00:26:34 +0000529 if (C == ".")
530 continue;
Sean Silva3e36e502015-07-30 00:52:32 +0000531 if (RemoveDotDot) {
532 if (C == "..") {
533 if (!ComponentStack.empty())
534 ComponentStack.pop_back();
535 continue;
536 }
Richard Smith54cc3c22014-12-11 20:50:24 +0000537 }
538 ComponentStack.push_back(C);
539 }
540
Richard Smith54cc3c22014-12-11 20:50:24 +0000541 SmallString<256> Buffer = path::root_path(P);
542 for (StringRef C : ComponentStack)
543 path::append(Buffer, C);
544
Sean Silvab963ded2015-07-30 00:26:34 +0000545 bool Changed = (Path != Buffer);
Richard Smith54cc3c22014-12-11 20:50:24 +0000546 Path.swap(Buffer);
Sean Silvab963ded2015-07-30 00:26:34 +0000547 return Changed;
Richard Smith54cc3c22014-12-11 20:50:24 +0000548}
549
Douglas Gregore00c8b22013-01-26 00:55:12 +0000550StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
551 // FIXME: use llvm::sys::fs::canonical() when it gets implemented
Douglas Gregore00c8b22013-01-26 00:55:12 +0000552 llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
553 = CanonicalDirNames.find(Dir);
554 if (Known != CanonicalDirNames.end())
555 return Known->second;
556
557 StringRef CanonicalName(Dir->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +0000558
559#ifdef LLVM_ON_UNIX
Douglas Gregore00c8b22013-01-26 00:55:12 +0000560 char CanonicalNameBuf[PATH_MAX];
561 if (realpath(Dir->getName(), CanonicalNameBuf)) {
562 unsigned Len = strlen(CanonicalNameBuf);
563 char *Mem = static_cast<char *>(CanonicalNameStorage.Allocate(Len, 1));
564 memcpy(Mem, CanonicalNameBuf, Len);
565 CanonicalName = StringRef(Mem, Len);
566 }
Richard Smith54cc3c22014-12-11 20:50:24 +0000567#else
568 SmallString<256> CanonicalNameBuf(CanonicalName);
569 llvm::sys::fs::make_absolute(CanonicalNameBuf);
570 llvm::sys::path::native(CanonicalNameBuf);
Sean Silvade381662015-07-30 07:30:24 +0000571 // We've run into needing to remove '..' here in the wild though, so
572 // remove it.
573 // On Windows, symlinks are significantly less prevalent, so removing
574 // '..' is pretty safe.
575 // Ideally we'd have an equivalent of `realpath` and could implement
576 // sys::fs::canonical across all the platforms.
577 removeDotPaths(CanonicalNameBuf, /*RemoveDotDot*/true);
Sean Silvab963ded2015-07-30 00:26:34 +0000578 char *Mem = CanonicalNameStorage.Allocate<char>(CanonicalNameBuf.size());
579 memcpy(Mem, CanonicalNameBuf.data(), CanonicalNameBuf.size());
580 CanonicalName = StringRef(Mem, CanonicalNameBuf.size());
Richard Smith54cc3c22014-12-11 20:50:24 +0000581#endif
Douglas Gregore00c8b22013-01-26 00:55:12 +0000582
583 CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
584 return CanonicalName;
Douglas Gregore00c8b22013-01-26 00:55:12 +0000585}
Chris Lattner226efd32010-11-23 19:19:34 +0000586
Chris Lattner22eb9722006-06-18 05:43:12 +0000587void FileManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000588 llvm::errs() << "\n*** File Manager Stats:\n";
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000589 llvm::errs() << UniqueRealFiles.size() << " real files found, "
590 << UniqueRealDirs.size() << " real dirs found.\n";
591 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
592 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000593 llvm::errs() << NumDirLookups << " dir lookups, "
594 << NumDirCacheMisses << " dir cache misses.\n";
595 llvm::errs() << NumFileLookups << " file lookups, "
596 << NumFileCacheMisses << " file cache misses.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000597
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000598 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
Chris Lattner22eb9722006-06-18 05:43:12 +0000599}
Adrian Prantl075bf562015-07-09 02:53:05 +0000600
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000601// Virtual destructors for abstract base classes that need live in Basic.
602PCHContainerWriter::~PCHContainerWriter() {}
603PCHContainerReader::~PCHContainerReader() {}