blob: c46e2c7db380823190a7f38b0006c6ae9a274396 [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"
Benjamin Kramer26db6482009-09-05 09:49:39 +000028#include <map>
29#include <set>
30#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000031#include <system_error>
Chris Lattner278038b2010-11-23 21:53:15 +000032
Chris Lattner22eb9722006-06-18 05:43:12 +000033using namespace clang;
34
Ted Kremenek8d71e252008-01-11 20:42:05 +000035/// NON_EXISTENT_DIR - A special value distinct from null that is used to
Chris Lattneraf653752006-10-30 03:06:54 +000036/// represent a dir name that doesn't exist on the disk.
Ted Kremenek8d71e252008-01-11 20:42:05 +000037#define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
Chris Lattneraf653752006-10-30 03:06:54 +000038
Chris Lattner9624b692010-11-23 20:50:22 +000039/// NON_EXISTENT_FILE - A special value distinct from null that is used to
40/// represent a filename that doesn't exist on the disk.
41#define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
42
Ted Kremenek5c04bd82009-01-28 00:27:31 +000043//===----------------------------------------------------------------------===//
44// Common logic.
45//===----------------------------------------------------------------------===//
Ted Kremenekd87eef82008-02-24 03:15:25 +000046
Ben Langmuirc8130a72014-02-20 21:59:23 +000047FileManager::FileManager(const FileSystemOptions &FSO,
48 IntrusiveRefCntPtr<vfs::FileSystem> FS)
49 : FS(FS), FileSystemOpts(FSO),
Zhanyong Wane1dd3e22011-02-11 18:44:49 +000050 SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
Ted Kremenekd87eef82008-02-24 03:15:25 +000051 NumDirLookups = NumFileLookups = 0;
52 NumDirCacheMisses = NumFileCacheMisses = 0;
Ben Langmuirc8130a72014-02-20 21:59:23 +000053
54 // If the caller doesn't provide a virtual file system, just grab the real
55 // file system.
56 if (!FS)
57 this->FS = vfs::getRealFileSystem();
Ted Kremenekd87eef82008-02-24 03:15:25 +000058}
59
60FileManager::~FileManager() {
Chris Lattner966b25b2010-11-23 20:30:42 +000061 for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
62 delete VirtualFileEntries[i];
Zhanyong Wane1dd3e22011-02-11 18:44:49 +000063 for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
64 delete VirtualDirectoryEntries[i];
Ted Kremenekd87eef82008-02-24 03:15:25 +000065}
66
David Blaikie23430cc2014-08-11 21:29:24 +000067void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache,
Chris Lattner226efd32010-11-23 19:19:34 +000068 bool AtBeginning) {
Douglas Gregord2eb58a2009-10-16 18:18:30 +000069 assert(statCache && "No stat cache provided?");
Craig Topperf1186c52014-05-08 06:41:40 +000070 if (AtBeginning || !StatCache.get()) {
David Blaikie23430cc2014-08-11 21:29:24 +000071 statCache->setNextStatCache(std::move(StatCache));
72 StatCache = std::move(statCache);
Douglas Gregord2eb58a2009-10-16 18:18:30 +000073 return;
74 }
75
Chris Lattner226efd32010-11-23 19:19:34 +000076 FileSystemStatCache *LastCache = StatCache.get();
Douglas Gregord2eb58a2009-10-16 18:18:30 +000077 while (LastCache->getNextStatCache())
78 LastCache = LastCache->getNextStatCache();
David Blaikie23430cc2014-08-11 21:29:24 +000079
80 LastCache->setNextStatCache(std::move(statCache));
Douglas Gregord2eb58a2009-10-16 18:18:30 +000081}
82
Chris Lattner226efd32010-11-23 19:19:34 +000083void FileManager::removeStatCache(FileSystemStatCache *statCache) {
Douglas Gregord2eb58a2009-10-16 18:18:30 +000084 if (!statCache)
85 return;
86
87 if (StatCache.get() == statCache) {
88 // This is the first stat cache.
David Blaikiedd0e1e82014-08-10 16:57:11 +000089 StatCache = StatCache->takeNextStatCache();
Douglas Gregord2eb58a2009-10-16 18:18:30 +000090 return;
91 }
92
93 // Find the stat cache in the list.
Chris Lattner226efd32010-11-23 19:19:34 +000094 FileSystemStatCache *PrevCache = StatCache.get();
Douglas Gregord2eb58a2009-10-16 18:18:30 +000095 while (PrevCache && PrevCache->getNextStatCache() != statCache)
96 PrevCache = PrevCache->getNextStatCache();
Chris Lattner9624b692010-11-23 20:50:22 +000097
98 assert(PrevCache && "Stat cache not found for removal");
David Blaikie23430cc2014-08-11 21:29:24 +000099 PrevCache->setNextStatCache(statCache->takeNextStatCache());
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000100}
101
Manuel Klimek3aad8552012-07-31 13:56:54 +0000102void FileManager::clearStatCaches() {
David Blaikie3875a822014-07-19 01:06:45 +0000103 StatCache.reset();
Manuel Klimek3aad8552012-07-31 13:56:54 +0000104}
105
Douglas Gregor407e2122009-12-02 18:12:28 +0000106/// \brief Retrieve the directory that the given file name resides in.
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000107/// Filename can point to either a real file or a virtual file.
Douglas Gregor407e2122009-12-02 18:12:28 +0000108static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000109 StringRef Filename,
110 bool CacheFailure) {
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000111 if (Filename.empty())
Craig Topperf1186c52014-05-08 06:41:40 +0000112 return nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000113
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000114 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
Craig Topperf1186c52014-05-08 06:41:40 +0000115 return nullptr; // If Filename is a directory.
Benjamin Kramer3cf715d2010-11-21 11:32:22 +0000116
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000117 StringRef DirName = llvm::sys::path::parent_path(Filename);
Chris Lattner0c0e8042010-11-21 09:50:16 +0000118 // Use the current directory if file has no path component.
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000119 if (DirName.empty())
120 DirName = ".";
Douglas Gregor407e2122009-12-02 18:12:28 +0000121
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000122 return FileMgr.getDirectory(DirName, CacheFailure);
Douglas Gregor407e2122009-12-02 18:12:28 +0000123}
124
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000125/// Add all ancestors of the given path (pointing to either a file or
126/// a directory) as virtual directories.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000127void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
128 StringRef DirName = llvm::sys::path::parent_path(Path);
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000129 if (DirName.empty())
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000130 return;
131
David Blaikie13156b62014-11-19 03:06:06 +0000132 auto &NamedDirEnt =
133 *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000134
135 // When caching a virtual directory, we always cache its ancestors
136 // at the same time. Therefore, if DirName is already in the cache,
137 // we don't need to recurse as its ancestors must also already be in
138 // the cache.
David Blaikie13156b62014-11-19 03:06:06 +0000139 if (NamedDirEnt.second)
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000140 return;
141
142 // Add the virtual directory to the cache.
143 DirectoryEntry *UDE = new DirectoryEntry;
David Blaikie13156b62014-11-19 03:06:06 +0000144 UDE->Name = NamedDirEnt.first().data();
145 NamedDirEnt.second = UDE;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000146 VirtualDirectoryEntries.push_back(UDE);
147
148 // Recursively add the other ancestors.
149 addAncestorsAsVirtualDirs(DirName);
150}
151
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000152const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
153 bool CacheFailure) {
NAKAMURA Takumi8bd8ee72012-06-16 06:04:10 +0000154 // stat doesn't like trailing separators except for root directory.
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000155 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
156 // (though it can strip '\\')
NAKAMURA Takumi8bd8ee72012-06-16 06:04:10 +0000157 if (DirName.size() > 1 &&
158 DirName != llvm::sys::path::root_path(DirName) &&
159 llvm::sys::path::is_separator(DirName.back()))
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000160 DirName = DirName.substr(0, DirName.size()-1);
Rafael Espindolaee305462013-07-29 15:47:24 +0000161#ifdef LLVM_ON_WIN32
162 // Fixing a problem with "clang C:test.c" on Windows.
163 // Stat("C:") does not recognize "C:" as a valid directory
164 std::string DirNameStr;
165 if (DirName.size() > 1 && DirName.back() == ':' &&
166 DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
167 DirNameStr = DirName.str() + '.';
168 DirName = DirNameStr;
169 }
170#endif
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000171
Chris Lattner22eb9722006-06-18 05:43:12 +0000172 ++NumDirLookups;
David Blaikie13156b62014-11-19 03:06:06 +0000173 auto &NamedDirEnt =
174 *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
Mike Stump11289f42009-09-09 15:08:12 +0000175
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000176 // See if there was already an entry in the map. Note that the map
177 // contains both virtual and real directories.
David Blaikie13156b62014-11-19 03:06:06 +0000178 if (NamedDirEnt.second)
179 return NamedDirEnt.second == NON_EXISTENT_DIR ? nullptr
180 : NamedDirEnt.second;
Mike Stump11289f42009-09-09 15:08:12 +0000181
Chris Lattner22eb9722006-06-18 05:43:12 +0000182 ++NumDirCacheMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000183
Chris Lattneraf653752006-10-30 03:06:54 +0000184 // By default, initialize it to invalid.
David Blaikie13156b62014-11-19 03:06:06 +0000185 NamedDirEnt.second = NON_EXISTENT_DIR;
Mike Stump11289f42009-09-09 15:08:12 +0000186
Chris Lattner43fd42e2006-10-30 03:40:58 +0000187 // Get the null-terminated directory name as stored as the key of the
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000188 // SeenDirEntries map.
David Blaikie13156b62014-11-19 03:06:06 +0000189 const char *InterndDirName = NamedDirEnt.first().data();
Mike Stump11289f42009-09-09 15:08:12 +0000190
Chris Lattneraf653752006-10-30 03:06:54 +0000191 // Check to see if the directory exists.
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000192 FileData Data;
Craig Topperf1186c52014-05-08 06:41:40 +0000193 if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000194 // There's no real directory at the given path.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000195 if (!CacheFailure)
196 SeenDirEntries.erase(DirName);
Craig Topperf1186c52014-05-08 06:41:40 +0000197 return nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000198 }
Ted Kremenekd87eef82008-02-24 03:15:25 +0000199
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000200 // It exists. See if we have already opened a directory with the
201 // same inode (this occurs on Unix-like systems when one dir is
202 // symlinked to another, for example) or the same path (on
203 // Windows).
Ben Langmuirc9b72342014-02-27 22:21:32 +0000204 DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID];
Mike Stump11289f42009-09-09 15:08:12 +0000205
David Blaikie13156b62014-11-19 03:06:06 +0000206 NamedDirEnt.second = &UDE;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000207 if (!UDE.getName()) {
208 // We don't have this directory yet, add it. We use the string
209 // key from the SeenDirEntries map as the string.
210 UDE.Name = InterndDirName;
211 }
Mike Stump11289f42009-09-09 15:08:12 +0000212
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000213 return &UDE;
Chris Lattner22eb9722006-06-18 05:43:12 +0000214}
215
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000216const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
217 bool CacheFailure) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000218 ++NumFileLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000219
Chris Lattner22eb9722006-06-18 05:43:12 +0000220 // See if there is already an entry in the map.
David Blaikie13156b62014-11-19 03:06:06 +0000221 auto &NamedFileEnt =
222 *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
Chris Lattner22eb9722006-06-18 05:43:12 +0000223
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000224 // See if there is already an entry in the map.
David Blaikie13156b62014-11-19 03:06:06 +0000225 if (NamedFileEnt.second)
226 return NamedFileEnt.second == NON_EXISTENT_FILE ? nullptr
227 : NamedFileEnt.second;
Mike Stump11289f42009-09-09 15:08:12 +0000228
Chris Lattner22eb9722006-06-18 05:43:12 +0000229 ++NumFileCacheMisses;
230
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000231 // By default, initialize it to invalid.
David Blaikie13156b62014-11-19 03:06:06 +0000232 NamedFileEnt.second = NON_EXISTENT_FILE;
Chris Lattner22eb9722006-06-18 05:43:12 +0000233
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000234 // Get the null-terminated file name as stored as the key of the
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000235 // SeenFileEntries map.
David Blaikie13156b62014-11-19 03:06:06 +0000236 const char *InterndFileName = NamedFileEnt.first().data();
Mike Stump11289f42009-09-09 15:08:12 +0000237
Chris Lattner966b25b2010-11-23 20:30:42 +0000238 // Look up the directory for the file. When looking up something like
239 // sys/foo.h we'll discover all of the search directories that have a 'sys'
240 // subdirectory. This will let us avoid having to waste time on known-to-fail
241 // searches when we go to find sys/bar.h, because all the search directories
242 // without a 'sys' subdir will get a cached failure result.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000243 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
244 CacheFailure);
Craig Topperf1186c52014-05-08 06:41:40 +0000245 if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000246 if (!CacheFailure)
247 SeenFileEntries.erase(Filename);
Craig Topperf1186c52014-05-08 06:41:40 +0000248
249 return nullptr;
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000250 }
251
Chris Lattner22eb9722006-06-18 05:43:12 +0000252 // FIXME: Use the directory info to prune this, before doing the stat syscall.
253 // FIXME: This will reduce the # syscalls.
Mike Stump11289f42009-09-09 15:08:12 +0000254
Chris Lattner22eb9722006-06-18 05:43:12 +0000255 // Nope, there isn't. Check to see if the file exists.
David Blaikie326ffb32014-07-08 15:46:02 +0000256 std::unique_ptr<vfs::File> F;
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000257 FileData Data;
Craig Topperf1186c52014-05-08 06:41:40 +0000258 if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000259 // There's no real file at the given path.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000260 if (!CacheFailure)
261 SeenFileEntries.erase(Filename);
Craig Topperf1186c52014-05-08 06:41:40 +0000262
263 return nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000264 }
Mike Stump11289f42009-09-09 15:08:12 +0000265
Patrik Hagglundab01d4b2014-02-21 07:23:53 +0000266 assert((openFile || !F) && "undesired open file");
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000267
Ted Kremenekf4c38c92007-12-18 22:29:39 +0000268 // It exists. See if we have already opened a file with the same inode.
Chris Lattner22eb9722006-06-18 05:43:12 +0000269 // This occurs when one dir is symlinked to another, for example.
Ben Langmuirc9b72342014-02-27 22:21:32 +0000270 FileEntry &UFE = UniqueRealFiles[Data.UniqueID];
Mike Stump11289f42009-09-09 15:08:12 +0000271
David Blaikie13156b62014-11-19 03:06:06 +0000272 NamedFileEnt.second = &UFE;
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000273
274 // If the name returned by getStatValue is different than Filename, re-intern
275 // the name.
276 if (Data.Name != Filename) {
David Blaikie13156b62014-11-19 03:06:06 +0000277 auto &NamedFileEnt =
278 *SeenFileEntries.insert(std::make_pair(Data.Name, nullptr)).first;
279 if (!NamedFileEnt.second)
280 NamedFileEnt.second = &UFE;
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000281 else
David Blaikie13156b62014-11-19 03:06:06 +0000282 assert(NamedFileEnt.second == &UFE &&
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000283 "filename from getStatValue() refers to wrong file");
David Blaikie13156b62014-11-19 03:06:06 +0000284 InterndFileName = NamedFileEnt.first().data();
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000285 }
286
Ben Langmuirc8a71462014-02-27 17:23:33 +0000287 if (UFE.isValid()) { // Already have an entry with this inode, return it.
Ben Langmuir5de00f32014-05-23 18:15:47 +0000288
289 // FIXME: this hack ensures that if we look up a file by a virtual path in
290 // the VFS that the getDir() will have the virtual path, even if we found
291 // the file by a 'real' path first. This is required in order to find a
292 // module's structure when its headers/module map are mapped in the VFS.
293 // We should remove this as soon as we can properly support a file having
294 // multiple names.
295 if (DirInfo != UFE.Dir && Data.IsVFSMapped)
296 UFE.Dir = DirInfo;
297
Manuel Klimekc0ff9902014-08-13 12:34:41 +0000298 // Always update the name to use the last name by which a file was accessed.
299 // FIXME: Neither this nor always using the first name is correct; we want
300 // to switch towards a design where we return a FileName object that
301 // encapsulates both the name by which the file was accessed and the
302 // corresponding FileEntry.
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000303 UFE.Name = InterndFileName;
Manuel Klimekc0ff9902014-08-13 12:34:41 +0000304
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000305 return &UFE;
Chris Lattnerdd278432010-11-23 21:17:56 +0000306 }
Chris Lattner269c2322006-06-25 06:23:00 +0000307
Ben Langmuirc9b72342014-02-27 22:21:32 +0000308 // Otherwise, we don't have this file yet, add it.
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000309 UFE.Name = InterndFileName;
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000310 UFE.Size = Data.Size;
311 UFE.ModTime = Data.ModTime;
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000312 UFE.Dir = DirInfo;
313 UFE.UID = NextFileUID++;
Ben Langmuirc9b72342014-02-27 22:21:32 +0000314 UFE.UniqueID = Data.UniqueID;
315 UFE.IsNamedPipe = Data.IsNamedPipe;
316 UFE.InPCH = Data.InPCH;
David Blaikie326ffb32014-07-08 15:46:02 +0000317 UFE.File = std::move(F);
Ben Langmuirc8a71462014-02-27 17:23:33 +0000318 UFE.IsValid = true;
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000319 return &UFE;
Chris Lattner22eb9722006-06-18 05:43:12 +0000320}
321
Douglas Gregor407e2122009-12-02 18:12:28 +0000322const FileEntry *
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000323FileManager::getVirtualFile(StringRef Filename, off_t Size,
Chris Lattner5159f612010-11-23 08:35:12 +0000324 time_t ModificationTime) {
Douglas Gregor407e2122009-12-02 18:12:28 +0000325 ++NumFileLookups;
326
327 // See if there is already an entry in the map.
David Blaikie13156b62014-11-19 03:06:06 +0000328 auto &NamedFileEnt =
329 *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
Douglas Gregor407e2122009-12-02 18:12:28 +0000330
331 // See if there is already an entry in the map.
David Blaikie13156b62014-11-19 03:06:06 +0000332 if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE)
333 return NamedFileEnt.second;
Douglas Gregor407e2122009-12-02 18:12:28 +0000334
335 ++NumFileCacheMisses;
336
337 // By default, initialize it to invalid.
David Blaikie13156b62014-11-19 03:06:06 +0000338 NamedFileEnt.second = NON_EXISTENT_FILE;
Douglas Gregor407e2122009-12-02 18:12:28 +0000339
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000340 addAncestorsAsVirtualDirs(Filename);
Craig Topperf1186c52014-05-08 06:41:40 +0000341 FileEntry *UFE = nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000342
343 // Now that all ancestors of Filename are in the cache, the
344 // following call is guaranteed to find the DirectoryEntry from the
345 // cache.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000346 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
347 /*CacheFailure=*/true);
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000348 assert(DirInfo &&
349 "The directory of a virtual file should already be in the cache.");
Douglas Gregor407e2122009-12-02 18:12:28 +0000350
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000351 // Check to see if the file exists. If so, drop the virtual file
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000352 FileData Data;
David Blaikie13156b62014-11-19 03:06:06 +0000353 const char *InterndFileName = NamedFileEnt.first().data();
Craig Topperf1186c52014-05-08 06:41:40 +0000354 if (getStatValue(InterndFileName, Data, true, nullptr) == 0) {
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000355 Data.Size = Size;
356 Data.ModTime = ModificationTime;
Ben Langmuirc9b72342014-02-27 22:21:32 +0000357 UFE = &UniqueRealFiles[Data.UniqueID];
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000358
David Blaikie13156b62014-11-19 03:06:06 +0000359 NamedFileEnt.second = UFE;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000360
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000361 // If we had already opened this file, close it now so we don't
362 // leak the descriptor. We're not going to use the file
363 // descriptor anyway, since this is a virtual file.
Ben Langmuirc8130a72014-02-20 21:59:23 +0000364 if (UFE->File)
365 UFE->closeFile();
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000366
367 // If we already have an entry with this inode, return it.
Ben Langmuirc8a71462014-02-27 17:23:33 +0000368 if (UFE->isValid())
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000369 return UFE;
Ben Langmuirc9b72342014-02-27 22:21:32 +0000370
371 UFE->UniqueID = Data.UniqueID;
372 UFE->IsNamedPipe = Data.IsNamedPipe;
373 UFE->InPCH = Data.InPCH;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000374 }
375
376 if (!UFE) {
377 UFE = new FileEntry();
378 VirtualFileEntries.push_back(UFE);
David Blaikie13156b62014-11-19 03:06:06 +0000379 NamedFileEnt.second = UFE;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000380 }
Douglas Gregor407e2122009-12-02 18:12:28 +0000381
Chris Lattner9624b692010-11-23 20:50:22 +0000382 UFE->Name = InterndFileName;
Douglas Gregor407e2122009-12-02 18:12:28 +0000383 UFE->Size = Size;
384 UFE->ModTime = ModificationTime;
385 UFE->Dir = DirInfo;
386 UFE->UID = NextFileUID++;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000387 UFE->File.reset();
Douglas Gregor407e2122009-12-02 18:12:28 +0000388 return UFE;
389}
390
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000391void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
392 StringRef pathRef(path.data(), path.size());
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000393
Anders Carlsson9ba8fb12011-03-14 01:13:54 +0000394 if (FileSystemOpts.WorkingDir.empty()
395 || llvm::sys::path::is_absolute(pathRef))
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000396 return;
397
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000398 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000399 llvm::sys::path::append(NewPath, pathRef);
Chris Lattner6e640992010-11-23 04:45:28 +0000400 path = NewPath;
401}
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000402
Benjamin Kramera8857962014-10-26 22:44:13 +0000403llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
404FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
405 bool ShouldCloseOpenFile) {
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000406 uint64_t FileSize = Entry->getSize();
407 // If there's a high enough chance that the file have changed since we
408 // got its size, force a stat before opening it.
409 if (isVolatile)
410 FileSize = -1;
411
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44 +0000412 const char *Filename = Entry->getName();
413 // If the file is already open, use the open file descriptor.
Ben Langmuirc8130a72014-02-20 21:59:23 +0000414 if (Entry->File) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000415 auto Result =
416 Entry->File->getBuffer(Filename, FileSize,
417 /*RequiresNullTerminator=*/true, isVolatile);
Ben Langmuir9801b252014-06-20 00:24:56 +0000418 // FIXME: we need a set of APIs that can make guarantees about whether a
419 // FileEntry is open or not.
420 if (ShouldCloseOpenFile)
421 Entry->closeFile();
Rafael Espindola6406f7b2014-08-26 19:54:40 +0000422 return Result;
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44 +0000423 }
424
425 // Otherwise, open the file.
426
Benjamin Kramera8857962014-10-26 22:44:13 +0000427 if (FileSystemOpts.WorkingDir.empty())
428 return FS->getBufferForFile(Filename, FileSize,
429 /*RequiresNullTerminator=*/true, isVolatile);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000430
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000431 SmallString<128> FilePath(Entry->getName());
Anders Carlsson878b3e22011-03-07 01:28:33 +0000432 FixupRelativePath(FilePath);
Yaron Keren92e1b622015-03-18 10:17:07 +0000433 return FS->getBufferForFile(FilePath, FileSize,
Benjamin Kramera8857962014-10-26 22:44:13 +0000434 /*RequiresNullTerminator=*/true, isVolatile);
Chris Lattner26b5c192010-11-23 09:19:42 +0000435}
436
Benjamin Kramera8857962014-10-26 22:44:13 +0000437llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
438FileManager::getBufferForFile(StringRef Filename) {
439 if (FileSystemOpts.WorkingDir.empty())
440 return FS->getBufferForFile(Filename);
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000441
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000442 SmallString<128> FilePath(Filename);
Anders Carlsson878b3e22011-03-07 01:28:33 +0000443 FixupRelativePath(FilePath);
Benjamin Kramera8857962014-10-26 22:44:13 +0000444 return FS->getBufferForFile(FilePath.c_str());
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000445}
446
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000447/// getStatValue - Get the 'stat' information for the specified path,
448/// using the cache to accelerate it if possible. This returns true
449/// if the path points to a virtual file or does not exist, or returns
450/// false if it's an existent real file. If FileDescriptor is NULL,
451/// do directory look-up instead of file look-up.
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000452bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile,
David Blaikie326ffb32014-07-08 15:46:02 +0000453 std::unique_ptr<vfs::File> *F) {
Chris Lattner226efd32010-11-23 19:19:34 +0000454 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
455 // absolute!
Chris Lattner5769c3d2010-11-23 19:56:39 +0000456 if (FileSystemOpts.WorkingDir.empty())
Ben Langmuirc8130a72014-02-20 21:59:23 +0000457 return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000458
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000459 SmallString<128> FilePath(Path);
Anders Carlsson878b3e22011-03-07 01:28:33 +0000460 FixupRelativePath(FilePath);
Chris Lattner5769c3d2010-11-23 19:56:39 +0000461
Ben Langmuirc8130a72014-02-20 21:59:23 +0000462 return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
463 StatCache.get(), *FS);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000464}
465
Rafael Espindolae4777f42013-07-29 18:22:23 +0000466bool FileManager::getNoncachedStatValue(StringRef Path,
Ben Langmuirc8130a72014-02-20 21:59:23 +0000467 vfs::Status &Result) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000468 SmallString<128> FilePath(Path);
Anders Carlsson5e368402011-03-18 19:23:19 +0000469 FixupRelativePath(FilePath);
470
Ben Langmuirc8130a72014-02-20 21:59:23 +0000471 llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str());
472 if (!S)
473 return true;
474 Result = *S;
475 return false;
Anders Carlsson5e368402011-03-18 19:23:19 +0000476}
477
Axel Naumannb3074002012-07-10 16:50:27 +0000478void FileManager::invalidateCache(const FileEntry *Entry) {
479 assert(Entry && "Cannot invalidate a NULL FileEntry");
Axel Naumann38179d92012-06-27 09:17:42 +0000480
481 SeenFileEntries.erase(Entry->getName());
Axel Naumannb3074002012-07-10 16:50:27 +0000482
483 // FileEntry invalidation should not block future optimizations in the file
484 // caches. Possible alternatives are cache truncation (invalidate last N) or
485 // invalidation of the whole cache.
Ben Langmuirc9b72342014-02-27 22:21:32 +0000486 UniqueRealFiles.erase(Entry->getUniqueID());
Axel Naumann38179d92012-06-27 09:17:42 +0000487}
488
489
Douglas Gregor09b69892011-02-10 17:09:37 +0000490void FileManager::GetUniqueIDMapping(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000491 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
Douglas Gregor09b69892011-02-10 17:09:37 +0000492 UIDToFiles.clear();
493 UIDToFiles.resize(NextFileUID);
494
495 // Map file entries
496 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000497 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
Douglas Gregor09b69892011-02-10 17:09:37 +0000498 FE != FEEnd; ++FE)
499 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
500 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
501
502 // Map virtual file entries
Craig Topper2341c0d2013-07-04 03:08:24 +0000503 for (SmallVectorImpl<FileEntry *>::const_iterator
Douglas Gregor09b69892011-02-10 17:09:37 +0000504 VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
505 VFE != VFEEnd; ++VFE)
506 if (*VFE && *VFE != NON_EXISTENT_FILE)
507 UIDToFiles[(*VFE)->getUID()] = *VFE;
508}
Chris Lattner226efd32010-11-23 19:19:34 +0000509
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000510void FileManager::modifyFileEntry(FileEntry *File,
511 off_t Size, time_t ModificationTime) {
512 File->Size = Size;
513 File->ModTime = ModificationTime;
514}
515
Richard Smith54cc3c22014-12-11 20:50:24 +0000516/// Remove '.' path components from the given absolute path.
517/// \return \c true if any changes were made.
518// FIXME: Move this to llvm::sys::path.
519bool FileManager::removeDotPaths(SmallVectorImpl<char> &Path) {
520 using namespace llvm::sys;
521
522 SmallVector<StringRef, 16> ComponentStack;
523 StringRef P(Path.data(), Path.size());
524
525 // Skip the root path, then look for traversal in the components.
526 StringRef Rel = path::relative_path(P);
527 bool AnyDots = false;
528 for (StringRef C : llvm::make_range(path::begin(Rel), path::end(Rel))) {
529 if (C == ".") {
530 AnyDots = true;
531 continue;
532 }
533 ComponentStack.push_back(C);
534 }
535
536 if (!AnyDots)
537 return false;
538
539 SmallString<256> Buffer = path::root_path(P);
540 for (StringRef C : ComponentStack)
541 path::append(Buffer, C);
542
543 Path.swap(Buffer);
544 return true;
545}
546
Douglas Gregore00c8b22013-01-26 00:55:12 +0000547StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
548 // FIXME: use llvm::sys::fs::canonical() when it gets implemented
Douglas Gregore00c8b22013-01-26 00:55:12 +0000549 llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
550 = CanonicalDirNames.find(Dir);
551 if (Known != CanonicalDirNames.end())
552 return Known->second;
553
554 StringRef CanonicalName(Dir->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +0000555
556#ifdef LLVM_ON_UNIX
Douglas Gregore00c8b22013-01-26 00:55:12 +0000557 char CanonicalNameBuf[PATH_MAX];
558 if (realpath(Dir->getName(), CanonicalNameBuf)) {
559 unsigned Len = strlen(CanonicalNameBuf);
560 char *Mem = static_cast<char *>(CanonicalNameStorage.Allocate(Len, 1));
561 memcpy(Mem, CanonicalNameBuf, Len);
562 CanonicalName = StringRef(Mem, Len);
563 }
Richard Smith54cc3c22014-12-11 20:50:24 +0000564#else
565 SmallString<256> CanonicalNameBuf(CanonicalName);
566 llvm::sys::fs::make_absolute(CanonicalNameBuf);
567 llvm::sys::path::native(CanonicalNameBuf);
568 removeDotPaths(CanonicalNameBuf);
569#endif
Douglas Gregore00c8b22013-01-26 00:55:12 +0000570
571 CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
572 return CanonicalName;
Douglas Gregore00c8b22013-01-26 00:55:12 +0000573}
Chris Lattner226efd32010-11-23 19:19:34 +0000574
Chris Lattner22eb9722006-06-18 05:43:12 +0000575void FileManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000576 llvm::errs() << "\n*** File Manager Stats:\n";
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000577 llvm::errs() << UniqueRealFiles.size() << " real files found, "
578 << UniqueRealDirs.size() << " real dirs found.\n";
579 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
580 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000581 llvm::errs() << NumDirLookups << " dir lookups, "
582 << NumDirCacheMisses << " dir cache misses.\n";
583 llvm::errs() << NumFileLookups << " file lookups, "
584 << NumFileCacheMisses << " file cache misses.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000585
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000586 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
Chris Lattner22eb9722006-06-18 05:43:12 +0000587}