blob: 21cb92d51c266a9adfa437866ae883f382f1e93e [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"
David Blaikied2725a32015-12-09 17:23:13 +000024#include "llvm/ADT/STLExtras.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"
Eugene Zelenko35b79c22016-08-13 01:05:35 +000029#include <algorithm>
30#include <cassert>
31#include <climits>
32#include <cstdint>
33#include <cstdlib>
Benjamin Kramer26db6482009-09-05 09:49:39 +000034#include <string>
Eugene Zelenko35b79c22016-08-13 01:05:35 +000035#include <utility>
Chris Lattner278038b2010-11-23 21:53:15 +000036
Chris Lattner22eb9722006-06-18 05:43:12 +000037using namespace clang;
38
Ted Kremenek8d71e252008-01-11 20:42:05 +000039/// NON_EXISTENT_DIR - A special value distinct from null that is used to
Chris Lattneraf653752006-10-30 03:06:54 +000040/// represent a dir name that doesn't exist on the disk.
Ted Kremenek8d71e252008-01-11 20:42:05 +000041#define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
Chris Lattneraf653752006-10-30 03:06:54 +000042
Chris Lattner9624b692010-11-23 20:50:22 +000043/// NON_EXISTENT_FILE - A special value distinct from null that is used to
44/// represent a filename that doesn't exist on the disk.
45#define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
46
Ted Kremenek5c04bd82009-01-28 00:27:31 +000047//===----------------------------------------------------------------------===//
48// Common logic.
49//===----------------------------------------------------------------------===//
Ted Kremenekd87eef82008-02-24 03:15:25 +000050
Ben Langmuirc8130a72014-02-20 21:59:23 +000051FileManager::FileManager(const FileSystemOptions &FSO,
Jonas Devliegherefc514902018-10-10 13:27:25 +000052 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
Benjamin Kramerf6021ec2017-03-21 21:35:04 +000053 : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
54 SeenFileEntries(64), NextFileUID(0) {
Ted Kremenekd87eef82008-02-24 03:15:25 +000055 NumDirLookups = NumFileLookups = 0;
56 NumDirCacheMisses = NumFileCacheMisses = 0;
Ben Langmuirc8130a72014-02-20 21:59:23 +000057
58 // If the caller doesn't provide a virtual file system, just grab the real
59 // file system.
Benjamin Kramerf6021ec2017-03-21 21:35:04 +000060 if (!this->FS)
Jonas Devliegherefc514902018-10-10 13:27:25 +000061 this->FS = llvm::vfs::getRealFileSystem();
Ted Kremenekd87eef82008-02-24 03:15:25 +000062}
63
David Blaikied2725a32015-12-09 17:23:13 +000064FileManager::~FileManager() = default;
Ted Kremenekd87eef82008-02-24 03:15:25 +000065
David Blaikie23430cc2014-08-11 21:29:24 +000066void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache,
Chris Lattner226efd32010-11-23 19:19:34 +000067 bool AtBeginning) {
Douglas Gregord2eb58a2009-10-16 18:18:30 +000068 assert(statCache && "No stat cache provided?");
Craig Topperf1186c52014-05-08 06:41:40 +000069 if (AtBeginning || !StatCache.get()) {
David Blaikie23430cc2014-08-11 21:29:24 +000070 statCache->setNextStatCache(std::move(StatCache));
71 StatCache = std::move(statCache);
Douglas Gregord2eb58a2009-10-16 18:18:30 +000072 return;
73 }
Fangrui Song6907ce22018-07-30 19:24:48 +000074
Chris Lattner226efd32010-11-23 19:19:34 +000075 FileSystemStatCache *LastCache = StatCache.get();
Douglas Gregord2eb58a2009-10-16 18:18:30 +000076 while (LastCache->getNextStatCache())
77 LastCache = LastCache->getNextStatCache();
David Blaikie23430cc2014-08-11 21:29:24 +000078
79 LastCache->setNextStatCache(std::move(statCache));
Douglas Gregord2eb58a2009-10-16 18:18:30 +000080}
81
Chris Lattner226efd32010-11-23 19:19:34 +000082void FileManager::removeStatCache(FileSystemStatCache *statCache) {
Douglas Gregord2eb58a2009-10-16 18:18:30 +000083 if (!statCache)
84 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000085
Douglas Gregord2eb58a2009-10-16 18:18:30 +000086 if (StatCache.get() == statCache) {
87 // This is the first stat cache.
David Blaikiedd0e1e82014-08-10 16:57:11 +000088 StatCache = StatCache->takeNextStatCache();
Douglas Gregord2eb58a2009-10-16 18:18:30 +000089 return;
90 }
Fangrui Song6907ce22018-07-30 19:24:48 +000091
Douglas Gregord2eb58a2009-10-16 18:18:30 +000092 // Find the stat cache in the list.
Chris Lattner226efd32010-11-23 19:19:34 +000093 FileSystemStatCache *PrevCache = StatCache.get();
Douglas Gregord2eb58a2009-10-16 18:18:30 +000094 while (PrevCache && PrevCache->getNextStatCache() != statCache)
95 PrevCache = PrevCache->getNextStatCache();
Fangrui Song6907ce22018-07-30 19:24:48 +000096
Chris Lattner9624b692010-11-23 20:50:22 +000097 assert(PrevCache && "Stat cache not found for removal");
David Blaikie23430cc2014-08-11 21:29:24 +000098 PrevCache->setNextStatCache(statCache->takeNextStatCache());
Douglas Gregord2eb58a2009-10-16 18:18:30 +000099}
100
Manuel Klimek3aad8552012-07-31 13:56:54 +0000101void FileManager::clearStatCaches() {
David Blaikie3875a822014-07-19 01:06:45 +0000102 StatCache.reset();
Manuel Klimek3aad8552012-07-31 13:56:54 +0000103}
104
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000105/// Retrieve the directory that the given file name resides in.
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000106/// Filename can point to either a real file or a virtual file.
Douglas Gregor407e2122009-12-02 18:12:28 +0000107static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000108 StringRef Filename,
109 bool CacheFailure) {
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000110 if (Filename.empty())
Craig Topperf1186c52014-05-08 06:41:40 +0000111 return nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000112
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000113 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
Craig Topperf1186c52014-05-08 06:41:40 +0000114 return nullptr; // If Filename is a directory.
Benjamin Kramer3cf715d2010-11-21 11:32:22 +0000115
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000116 StringRef DirName = llvm::sys::path::parent_path(Filename);
Chris Lattner0c0e8042010-11-21 09:50:16 +0000117 // Use the current directory if file has no path component.
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000118 if (DirName.empty())
119 DirName = ".";
Douglas Gregor407e2122009-12-02 18:12:28 +0000120
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000121 return FileMgr.getDirectory(DirName, CacheFailure);
Douglas Gregor407e2122009-12-02 18:12:28 +0000122}
123
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000124/// Add all ancestors of the given path (pointing to either a file or
125/// a directory) as virtual directories.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000126void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
127 StringRef DirName = llvm::sys::path::parent_path(Path);
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +0000128 if (DirName.empty())
David Majnemer1834dc72016-04-12 16:33:53 +0000129 DirName = ".";
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000130
David Blaikie13156b62014-11-19 03:06:06 +0000131 auto &NamedDirEnt =
132 *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000133
134 // When caching a virtual directory, we always cache its ancestors
135 // at the same time. Therefore, if DirName is already in the cache,
136 // we don't need to recurse as its ancestors must also already be in
137 // the cache.
Richard Smitha8cfffa2015-11-26 02:04:16 +0000138 if (NamedDirEnt.second && NamedDirEnt.second != NON_EXISTENT_DIR)
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000139 return;
140
141 // Add the virtual directory to the cache.
David Blaikied2725a32015-12-09 17:23:13 +0000142 auto UDE = llvm::make_unique<DirectoryEntry>();
Mehdi Amini0df59d82016-10-11 07:31:29 +0000143 UDE->Name = NamedDirEnt.first();
David Blaikied2725a32015-12-09 17:23:13 +0000144 NamedDirEnt.second = UDE.get();
145 VirtualDirectoryEntries.push_back(std::move(UDE));
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000146
147 // Recursively add the other ancestors.
148 addAncestorsAsVirtualDirs(DirName);
149}
150
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000151const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
152 bool CacheFailure) {
NAKAMURA Takumi8bd8ee72012-06-16 06:04:10 +0000153 // stat doesn't like trailing separators except for root directory.
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000154 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
155 // (though it can strip '\\')
NAKAMURA Takumi8bd8ee72012-06-16 06:04:10 +0000156 if (DirName.size() > 1 &&
157 DirName != llvm::sys::path::root_path(DirName) &&
158 llvm::sys::path::is_separator(DirName.back()))
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000159 DirName = DirName.substr(0, DirName.size()-1);
Nico Weber1865df42018-04-27 19:11:14 +0000160#ifdef _WIN32
Rafael Espindolaee305462013-07-29 15:47:24 +0000161 // Fixing a problem with "clang C:test.c" on Windows.
162 // Stat("C:") does not recognize "C:" as a valid directory
163 std::string DirNameStr;
164 if (DirName.size() > 1 && DirName.back() == ':' &&
165 DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
166 DirNameStr = DirName.str() + '.';
167 DirName = DirNameStr;
168 }
169#endif
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000170
Chris Lattner22eb9722006-06-18 05:43:12 +0000171 ++NumDirLookups;
David Blaikie13156b62014-11-19 03:06:06 +0000172 auto &NamedDirEnt =
173 *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
Mike Stump11289f42009-09-09 15:08:12 +0000174
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000175 // See if there was already an entry in the map. Note that the map
176 // contains both virtual and real directories.
David Blaikie13156b62014-11-19 03:06:06 +0000177 if (NamedDirEnt.second)
178 return NamedDirEnt.second == NON_EXISTENT_DIR ? nullptr
179 : NamedDirEnt.second;
Mike Stump11289f42009-09-09 15:08:12 +0000180
Chris Lattner22eb9722006-06-18 05:43:12 +0000181 ++NumDirCacheMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000182
Chris Lattneraf653752006-10-30 03:06:54 +0000183 // By default, initialize it to invalid.
David Blaikie13156b62014-11-19 03:06:06 +0000184 NamedDirEnt.second = NON_EXISTENT_DIR;
Mike Stump11289f42009-09-09 15:08:12 +0000185
Chris Lattner43fd42e2006-10-30 03:40:58 +0000186 // Get the null-terminated directory name as stored as the key of the
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000187 // SeenDirEntries map.
Mehdi Amini0df59d82016-10-11 07:31:29 +0000188 StringRef InterndDirName = NamedDirEnt.first();
Mike Stump11289f42009-09-09 15:08:12 +0000189
Chris Lattneraf653752006-10-30 03:06:54 +0000190 // Check to see if the directory exists.
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000191 FileData Data;
Craig Topperf1186c52014-05-08 06:41:40 +0000192 if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000193 // There's no real directory at the given path.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000194 if (!CacheFailure)
195 SeenDirEntries.erase(DirName);
Craig Topperf1186c52014-05-08 06:41:40 +0000196 return nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000197 }
Ted Kremenekd87eef82008-02-24 03:15:25 +0000198
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000199 // It exists. See if we have already opened a directory with the
200 // same inode (this occurs on Unix-like systems when one dir is
201 // symlinked to another, for example) or the same path (on
202 // Windows).
Ben Langmuirc9b72342014-02-27 22:21:32 +0000203 DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID];
Mike Stump11289f42009-09-09 15:08:12 +0000204
David Blaikie13156b62014-11-19 03:06:06 +0000205 NamedDirEnt.second = &UDE;
Mehdi Amini0df59d82016-10-11 07:31:29 +0000206 if (UDE.getName().empty()) {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000207 // We don't have this directory yet, add it. We use the string
208 // key from the SeenDirEntries map as the string.
209 UDE.Name = InterndDirName;
210 }
Mike Stump11289f42009-09-09 15:08:12 +0000211
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000212 return &UDE;
Chris Lattner22eb9722006-06-18 05:43:12 +0000213}
214
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000215const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
216 bool CacheFailure) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000217 ++NumFileLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000218
Chris Lattner22eb9722006-06-18 05:43:12 +0000219 // See if there is already an entry in the map.
David Blaikie13156b62014-11-19 03:06:06 +0000220 auto &NamedFileEnt =
221 *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
Chris Lattner22eb9722006-06-18 05:43:12 +0000222
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000223 // See if there is already an entry in the map.
Sam McCalle84385f2018-11-19 13:37:46 +0000224 if (NamedFileEnt.second) {
225 if (NamedFileEnt.second == NON_EXISTENT_FILE)
226 return nullptr;
227 // Entry exists: return it *unless* it wasn't opened and open is requested.
228 if (!(NamedFileEnt.second->DeferredOpen && openFile))
229 return NamedFileEnt.second;
230 // We previously stat()ed the file, but didn't open it: do that below.
231 // FIXME: the below does other redundant work too (stats the dir and file).
232 } else {
233 // By default, initialize it to invalid.
234 NamedFileEnt.second = NON_EXISTENT_FILE;
235 }
Mike Stump11289f42009-09-09 15:08:12 +0000236
Chris Lattner22eb9722006-06-18 05:43:12 +0000237 ++NumFileCacheMisses;
238
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000239 // Get the null-terminated file name as stored as the key of the
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000240 // SeenFileEntries map.
Mehdi Amini0df59d82016-10-11 07:31:29 +0000241 StringRef InterndFileName = NamedFileEnt.first();
Mike Stump11289f42009-09-09 15:08:12 +0000242
Chris Lattner966b25b2010-11-23 20:30:42 +0000243 // Look up the directory for the file. When looking up something like
244 // sys/foo.h we'll discover all of the search directories that have a 'sys'
245 // subdirectory. This will let us avoid having to waste time on known-to-fail
246 // searches when we go to find sys/bar.h, because all the search directories
247 // without a 'sys' subdir will get a cached failure result.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000248 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
249 CacheFailure);
Craig Topperf1186c52014-05-08 06:41:40 +0000250 if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000251 if (!CacheFailure)
252 SeenFileEntries.erase(Filename);
Craig Topperf1186c52014-05-08 06:41:40 +0000253
254 return nullptr;
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000255 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000256
Chris Lattner22eb9722006-06-18 05:43:12 +0000257 // FIXME: Use the directory info to prune this, before doing the stat syscall.
258 // FIXME: This will reduce the # syscalls.
Mike Stump11289f42009-09-09 15:08:12 +0000259
Chris Lattner22eb9722006-06-18 05:43:12 +0000260 // Nope, there isn't. Check to see if the file exists.
Jonas Devliegherefc514902018-10-10 13:27:25 +0000261 std::unique_ptr<llvm::vfs::File> F;
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000262 FileData Data;
Craig Topperf1186c52014-05-08 06:41:40 +0000263 if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000264 // There's no real file at the given path.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000265 if (!CacheFailure)
266 SeenFileEntries.erase(Filename);
Craig Topperf1186c52014-05-08 06:41:40 +0000267
268 return nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000269 }
Mike Stump11289f42009-09-09 15:08:12 +0000270
Patrik Hagglundab01d4b2014-02-21 07:23:53 +0000271 assert((openFile || !F) && "undesired open file");
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000272
Ted Kremenekf4c38c92007-12-18 22:29:39 +0000273 // It exists. See if we have already opened a file with the same inode.
Chris Lattner22eb9722006-06-18 05:43:12 +0000274 // This occurs when one dir is symlinked to another, for example.
Ben Langmuirc9b72342014-02-27 22:21:32 +0000275 FileEntry &UFE = UniqueRealFiles[Data.UniqueID];
Sam McCalle84385f2018-11-19 13:37:46 +0000276 UFE.DeferredOpen = !openFile;
Mike Stump11289f42009-09-09 15:08:12 +0000277
David Blaikie13156b62014-11-19 03:06:06 +0000278 NamedFileEnt.second = &UFE;
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000279
280 // If the name returned by getStatValue is different than Filename, re-intern
281 // the name.
282 if (Data.Name != Filename) {
David Blaikie13156b62014-11-19 03:06:06 +0000283 auto &NamedFileEnt =
284 *SeenFileEntries.insert(std::make_pair(Data.Name, nullptr)).first;
285 if (!NamedFileEnt.second)
286 NamedFileEnt.second = &UFE;
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000287 else
David Blaikie13156b62014-11-19 03:06:06 +0000288 assert(NamedFileEnt.second == &UFE &&
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000289 "filename from getStatValue() refers to wrong file");
David Blaikie13156b62014-11-19 03:06:06 +0000290 InterndFileName = NamedFileEnt.first().data();
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000291 }
292
Sam McCalle84385f2018-11-19 13:37:46 +0000293 // If we opened the file for the first time, record the resulting info.
294 // Do this even if the cache entry was valid, maybe we didn't previously open.
295 if (F && !UFE.File) {
296 if (auto PathName = F->getName()) {
297 llvm::SmallString<128> AbsPath(*PathName);
298 // This is not the same as `VFS::getRealPath()`, which resolves symlinks
299 // but can be very expensive on real file systems.
300 // FIXME: the semantic of RealPathName is unclear, and the name might be
301 // misleading. We need to clean up the interface here.
302 makeAbsolutePath(AbsPath);
303 llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
304 UFE.RealPathName = AbsPath.str();
305 }
306 UFE.File = std::move(F);
307 assert(!UFE.DeferredOpen && "we just opened it!");
308 }
309
Ben Langmuirc8a71462014-02-27 17:23:33 +0000310 if (UFE.isValid()) { // Already have an entry with this inode, return it.
Ben Langmuir5de00f32014-05-23 18:15:47 +0000311
312 // FIXME: this hack ensures that if we look up a file by a virtual path in
313 // the VFS that the getDir() will have the virtual path, even if we found
314 // the file by a 'real' path first. This is required in order to find a
315 // module's structure when its headers/module map are mapped in the VFS.
316 // We should remove this as soon as we can properly support a file having
317 // multiple names.
318 if (DirInfo != UFE.Dir && Data.IsVFSMapped)
319 UFE.Dir = DirInfo;
320
Manuel Klimekc0ff9902014-08-13 12:34:41 +0000321 // Always update the name to use the last name by which a file was accessed.
322 // FIXME: Neither this nor always using the first name is correct; we want
323 // to switch towards a design where we return a FileName object that
324 // encapsulates both the name by which the file was accessed and the
325 // corresponding FileEntry.
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000326 UFE.Name = InterndFileName;
Manuel Klimekc0ff9902014-08-13 12:34:41 +0000327
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000328 return &UFE;
Chris Lattnerdd278432010-11-23 21:17:56 +0000329 }
Chris Lattner269c2322006-06-25 06:23:00 +0000330
Ben Langmuirc9b72342014-02-27 22:21:32 +0000331 // Otherwise, we don't have this file yet, add it.
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000332 UFE.Name = InterndFileName;
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000333 UFE.Size = Data.Size;
334 UFE.ModTime = Data.ModTime;
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000335 UFE.Dir = DirInfo;
336 UFE.UID = NextFileUID++;
Ben Langmuirc9b72342014-02-27 22:21:32 +0000337 UFE.UniqueID = Data.UniqueID;
338 UFE.IsNamedPipe = Data.IsNamedPipe;
339 UFE.InPCH = Data.InPCH;
Ben Langmuirc8a71462014-02-27 17:23:33 +0000340 UFE.IsValid = true;
Sam McCalle84385f2018-11-19 13:37:46 +0000341 // Note File and DeferredOpen were initialized above.
Simon Marchiddbabc62018-08-06 21:48:20 +0000342
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000343 return &UFE;
Chris Lattner22eb9722006-06-18 05:43:12 +0000344}
345
Douglas Gregor407e2122009-12-02 18:12:28 +0000346const FileEntry *
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000347FileManager::getVirtualFile(StringRef Filename, off_t Size,
Chris Lattner5159f612010-11-23 08:35:12 +0000348 time_t ModificationTime) {
Douglas Gregor407e2122009-12-02 18:12:28 +0000349 ++NumFileLookups;
350
351 // See if there is already an entry in the map.
David Blaikie13156b62014-11-19 03:06:06 +0000352 auto &NamedFileEnt =
353 *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
Douglas Gregor407e2122009-12-02 18:12:28 +0000354
355 // See if there is already an entry in the map.
David Blaikie13156b62014-11-19 03:06:06 +0000356 if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE)
357 return NamedFileEnt.second;
Douglas Gregor407e2122009-12-02 18:12:28 +0000358
359 ++NumFileCacheMisses;
360
361 // By default, initialize it to invalid.
David Blaikie13156b62014-11-19 03:06:06 +0000362 NamedFileEnt.second = NON_EXISTENT_FILE;
Douglas Gregor407e2122009-12-02 18:12:28 +0000363
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000364 addAncestorsAsVirtualDirs(Filename);
Craig Topperf1186c52014-05-08 06:41:40 +0000365 FileEntry *UFE = nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000366
367 // Now that all ancestors of Filename are in the cache, the
368 // following call is guaranteed to find the DirectoryEntry from the
369 // cache.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000370 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
371 /*CacheFailure=*/true);
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000372 assert(DirInfo &&
373 "The directory of a virtual file should already be in the cache.");
Douglas Gregor407e2122009-12-02 18:12:28 +0000374
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000375 // Check to see if the file exists. If so, drop the virtual file
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000376 FileData Data;
David Blaikie13156b62014-11-19 03:06:06 +0000377 const char *InterndFileName = NamedFileEnt.first().data();
Craig Topperf1186c52014-05-08 06:41:40 +0000378 if (getStatValue(InterndFileName, Data, true, nullptr) == 0) {
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000379 Data.Size = Size;
380 Data.ModTime = ModificationTime;
Ben Langmuirc9b72342014-02-27 22:21:32 +0000381 UFE = &UniqueRealFiles[Data.UniqueID];
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000382
David Blaikie13156b62014-11-19 03:06:06 +0000383 NamedFileEnt.second = UFE;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000384
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000385 // If we had already opened this file, close it now so we don't
386 // leak the descriptor. We're not going to use the file
387 // descriptor anyway, since this is a virtual file.
Ben Langmuirc8130a72014-02-20 21:59:23 +0000388 if (UFE->File)
389 UFE->closeFile();
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000390
391 // If we already have an entry with this inode, return it.
Ben Langmuirc8a71462014-02-27 17:23:33 +0000392 if (UFE->isValid())
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000393 return UFE;
Ben Langmuirc9b72342014-02-27 22:21:32 +0000394
395 UFE->UniqueID = Data.UniqueID;
396 UFE->IsNamedPipe = Data.IsNamedPipe;
397 UFE->InPCH = Data.InPCH;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000398 }
399
400 if (!UFE) {
David Blaikied2725a32015-12-09 17:23:13 +0000401 VirtualFileEntries.push_back(llvm::make_unique<FileEntry>());
402 UFE = VirtualFileEntries.back().get();
David Blaikie13156b62014-11-19 03:06:06 +0000403 NamedFileEnt.second = UFE;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000404 }
Douglas Gregor407e2122009-12-02 18:12:28 +0000405
Chris Lattner9624b692010-11-23 20:50:22 +0000406 UFE->Name = InterndFileName;
Douglas Gregor407e2122009-12-02 18:12:28 +0000407 UFE->Size = Size;
408 UFE->ModTime = ModificationTime;
409 UFE->Dir = DirInfo;
410 UFE->UID = NextFileUID++;
Erik Verbruggendfffaf52017-03-28 09:18:05 +0000411 UFE->IsValid = true;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000412 UFE->File.reset();
Sam McCalle84385f2018-11-19 13:37:46 +0000413 UFE->DeferredOpen = false;
Douglas Gregor407e2122009-12-02 18:12:28 +0000414 return UFE;
415}
416
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +0000417bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000418 StringRef pathRef(path.data(), path.size());
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000419
Fangrui Song6907ce22018-07-30 19:24:48 +0000420 if (FileSystemOpts.WorkingDir.empty()
Anders Carlsson9ba8fb12011-03-14 01:13:54 +0000421 || llvm::sys::path::is_absolute(pathRef))
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +0000422 return false;
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000423
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000424 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000425 llvm::sys::path::append(NewPath, pathRef);
Chris Lattner6e640992010-11-23 04:45:28 +0000426 path = NewPath;
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +0000427 return true;
428}
429
430bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
431 bool Changed = FixupRelativePath(Path);
432
433 if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
Ilya Biryukov47035c02017-08-02 07:25:24 +0000434 FS->makeAbsolute(Path);
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +0000435 Changed = true;
436 }
437
438 return Changed;
Chris Lattner6e640992010-11-23 04:45:28 +0000439}
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000440
Benjamin Kramera8857962014-10-26 22:44:13 +0000441llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
442FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
443 bool ShouldCloseOpenFile) {
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000444 uint64_t FileSize = Entry->getSize();
445 // If there's a high enough chance that the file have changed since we
446 // got its size, force a stat before opening it.
447 if (isVolatile)
448 FileSize = -1;
449
Mehdi Amini004b9c72016-10-10 22:52:47 +0000450 StringRef Filename = Entry->getName();
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44 +0000451 // If the file is already open, use the open file descriptor.
Ben Langmuirc8130a72014-02-20 21:59:23 +0000452 if (Entry->File) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000453 auto Result =
454 Entry->File->getBuffer(Filename, FileSize,
455 /*RequiresNullTerminator=*/true, isVolatile);
Ben Langmuir9801b252014-06-20 00:24:56 +0000456 // FIXME: we need a set of APIs that can make guarantees about whether a
457 // FileEntry is open or not.
458 if (ShouldCloseOpenFile)
459 Entry->closeFile();
Rafael Espindola6406f7b2014-08-26 19:54:40 +0000460 return Result;
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44 +0000461 }
462
463 // Otherwise, open the file.
464
Benjamin Kramera8857962014-10-26 22:44:13 +0000465 if (FileSystemOpts.WorkingDir.empty())
466 return FS->getBufferForFile(Filename, FileSize,
467 /*RequiresNullTerminator=*/true, isVolatile);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000468
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000469 SmallString<128> FilePath(Entry->getName());
Anders Carlsson878b3e22011-03-07 01:28:33 +0000470 FixupRelativePath(FilePath);
Yaron Keren92e1b622015-03-18 10:17:07 +0000471 return FS->getBufferForFile(FilePath, FileSize,
Benjamin Kramera8857962014-10-26 22:44:13 +0000472 /*RequiresNullTerminator=*/true, isVolatile);
Chris Lattner26b5c192010-11-23 09:19:42 +0000473}
474
Benjamin Kramera8857962014-10-26 22:44:13 +0000475llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +0000476FileManager::getBufferForFile(StringRef Filename, bool isVolatile) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000477 if (FileSystemOpts.WorkingDir.empty())
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +0000478 return FS->getBufferForFile(Filename, -1, true, isVolatile);
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000479
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000480 SmallString<128> FilePath(Filename);
Anders Carlsson878b3e22011-03-07 01:28:33 +0000481 FixupRelativePath(FilePath);
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +0000482 return FS->getBufferForFile(FilePath.c_str(), -1, true, isVolatile);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000483}
484
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000485/// getStatValue - Get the 'stat' information for the specified path,
486/// using the cache to accelerate it if possible. This returns true
487/// if the path points to a virtual file or does not exist, or returns
488/// false if it's an existent real file. If FileDescriptor is NULL,
489/// do directory look-up instead of file look-up.
Mehdi Amini0df59d82016-10-11 07:31:29 +0000490bool FileManager::getStatValue(StringRef Path, FileData &Data, bool isFile,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000491 std::unique_ptr<llvm::vfs::File> *F) {
Chris Lattner226efd32010-11-23 19:19:34 +0000492 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
493 // absolute!
Chris Lattner5769c3d2010-11-23 19:56:39 +0000494 if (FileSystemOpts.WorkingDir.empty())
Ben Langmuirc8130a72014-02-20 21:59:23 +0000495 return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000496
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000497 SmallString<128> FilePath(Path);
Anders Carlsson878b3e22011-03-07 01:28:33 +0000498 FixupRelativePath(FilePath);
Chris Lattner5769c3d2010-11-23 19:56:39 +0000499
Ben Langmuirc8130a72014-02-20 21:59:23 +0000500 return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
501 StatCache.get(), *FS);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000502}
503
Rafael Espindolae4777f42013-07-29 18:22:23 +0000504bool FileManager::getNoncachedStatValue(StringRef Path,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000505 llvm::vfs::Status &Result) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000506 SmallString<128> FilePath(Path);
Anders Carlsson5e368402011-03-18 19:23:19 +0000507 FixupRelativePath(FilePath);
508
Jonas Devliegherefc514902018-10-10 13:27:25 +0000509 llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000510 if (!S)
511 return true;
512 Result = *S;
513 return false;
Anders Carlsson5e368402011-03-18 19:23:19 +0000514}
515
Axel Naumannb3074002012-07-10 16:50:27 +0000516void FileManager::invalidateCache(const FileEntry *Entry) {
517 assert(Entry && "Cannot invalidate a NULL FileEntry");
Axel Naumann38179d92012-06-27 09:17:42 +0000518
519 SeenFileEntries.erase(Entry->getName());
Axel Naumannb3074002012-07-10 16:50:27 +0000520
521 // FileEntry invalidation should not block future optimizations in the file
522 // caches. Possible alternatives are cache truncation (invalidate last N) or
523 // invalidation of the whole cache.
Ben Langmuirc9b72342014-02-27 22:21:32 +0000524 UniqueRealFiles.erase(Entry->getUniqueID());
Axel Naumann38179d92012-06-27 09:17:42 +0000525}
526
Douglas Gregor09b69892011-02-10 17:09:37 +0000527void FileManager::GetUniqueIDMapping(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000528 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
Douglas Gregor09b69892011-02-10 17:09:37 +0000529 UIDToFiles.clear();
530 UIDToFiles.resize(NextFileUID);
Fangrui Song6907ce22018-07-30 19:24:48 +0000531
Douglas Gregor09b69892011-02-10 17:09:37 +0000532 // Map file entries
533 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000534 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
Douglas Gregor09b69892011-02-10 17:09:37 +0000535 FE != FEEnd; ++FE)
536 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
537 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000538
Douglas Gregor09b69892011-02-10 17:09:37 +0000539 // Map virtual file entries
David Blaikied2725a32015-12-09 17:23:13 +0000540 for (const auto &VFE : VirtualFileEntries)
541 if (VFE && VFE.get() != NON_EXISTENT_FILE)
542 UIDToFiles[VFE->getUID()] = VFE.get();
Douglas Gregor09b69892011-02-10 17:09:37 +0000543}
Chris Lattner226efd32010-11-23 19:19:34 +0000544
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000545void FileManager::modifyFileEntry(FileEntry *File,
546 off_t Size, time_t ModificationTime) {
547 File->Size = Size;
548 File->ModTime = ModificationTime;
549}
550
Douglas Gregore00c8b22013-01-26 00:55:12 +0000551StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
552 // FIXME: use llvm::sys::fs::canonical() when it gets implemented
Douglas Gregore00c8b22013-01-26 00:55:12 +0000553 llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
554 = CanonicalDirNames.find(Dir);
555 if (Known != CanonicalDirNames.end())
556 return Known->second;
557
558 StringRef CanonicalName(Dir->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +0000559
Eric Liu5fb18fe2018-05-17 10:26:23 +0000560 SmallString<4096> CanonicalNameBuf;
561 if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
Benjamin Kramerda4690a2015-08-04 11:27:08 +0000562 CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
Douglas Gregore00c8b22013-01-26 00:55:12 +0000563
564 CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
565 return CanonicalName;
Douglas Gregore00c8b22013-01-26 00:55:12 +0000566}
Chris Lattner226efd32010-11-23 19:19:34 +0000567
Chris Lattner22eb9722006-06-18 05:43:12 +0000568void FileManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000569 llvm::errs() << "\n*** File Manager Stats:\n";
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000570 llvm::errs() << UniqueRealFiles.size() << " real files found, "
571 << UniqueRealDirs.size() << " real dirs found.\n";
572 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
573 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000574 llvm::errs() << NumDirLookups << " dir lookups, "
575 << NumDirCacheMisses << " dir cache misses.\n";
576 llvm::errs() << NumFileLookups << " file lookups, "
577 << NumFileCacheMisses << " file cache misses.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000578
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000579 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
Chris Lattner22eb9722006-06-18 05:43:12 +0000580}