blob: f5a2d4894c13e59287793509a975461805cec8e7 [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
Alex Lorenzd92b1ae2018-12-21 19:33:09 +000066void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
Douglas Gregord2eb58a2009-10-16 18:18:30 +000067 assert(statCache && "No stat cache provided?");
Alex Lorenzd92b1ae2018-12-21 19:33:09 +000068 StatCache = std::move(statCache);
Douglas Gregord2eb58a2009-10-16 18:18:30 +000069}
70
Alex Lorenzd92b1ae2018-12-21 19:33:09 +000071void FileManager::clearStatCache() { StatCache.reset(); }
Manuel Klimek3aad8552012-07-31 13:56:54 +000072
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000073/// Retrieve the directory that the given file name resides in.
Zhanyong Wane1dd3e22011-02-11 18:44:49 +000074/// Filename can point to either a real file or a virtual file.
Douglas Gregor407e2122009-12-02 18:12:28 +000075static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
Douglas Gregor1735f4e2011-09-13 23:15:45 +000076 StringRef Filename,
77 bool CacheFailure) {
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +000078 if (Filename.empty())
Craig Topperf1186c52014-05-08 06:41:40 +000079 return nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +000080
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +000081 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
Craig Topperf1186c52014-05-08 06:41:40 +000082 return nullptr; // If Filename is a directory.
Benjamin Kramer3cf715d2010-11-21 11:32:22 +000083
Chris Lattner0e62c1c2011-07-23 10:55:15 +000084 StringRef DirName = llvm::sys::path::parent_path(Filename);
Chris Lattner0c0e8042010-11-21 09:50:16 +000085 // Use the current directory if file has no path component.
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +000086 if (DirName.empty())
87 DirName = ".";
Douglas Gregor407e2122009-12-02 18:12:28 +000088
Douglas Gregor1735f4e2011-09-13 23:15:45 +000089 return FileMgr.getDirectory(DirName, CacheFailure);
Douglas Gregor407e2122009-12-02 18:12:28 +000090}
91
Zhanyong Wane1dd3e22011-02-11 18:44:49 +000092/// Add all ancestors of the given path (pointing to either a file or
93/// a directory) as virtual directories.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000094void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
95 StringRef DirName = llvm::sys::path::parent_path(Path);
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +000096 if (DirName.empty())
David Majnemer1834dc72016-04-12 16:33:53 +000097 DirName = ".";
Zhanyong Wane1dd3e22011-02-11 18:44:49 +000098
David Blaikie13156b62014-11-19 03:06:06 +000099 auto &NamedDirEnt =
100 *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000101
102 // When caching a virtual directory, we always cache its ancestors
103 // at the same time. Therefore, if DirName is already in the cache,
104 // we don't need to recurse as its ancestors must also already be in
105 // the cache.
Richard Smitha8cfffa2015-11-26 02:04:16 +0000106 if (NamedDirEnt.second && NamedDirEnt.second != NON_EXISTENT_DIR)
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000107 return;
108
109 // Add the virtual directory to the cache.
David Blaikied2725a32015-12-09 17:23:13 +0000110 auto UDE = llvm::make_unique<DirectoryEntry>();
Mehdi Amini0df59d82016-10-11 07:31:29 +0000111 UDE->Name = NamedDirEnt.first();
David Blaikied2725a32015-12-09 17:23:13 +0000112 NamedDirEnt.second = UDE.get();
113 VirtualDirectoryEntries.push_back(std::move(UDE));
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000114
115 // Recursively add the other ancestors.
116 addAncestorsAsVirtualDirs(DirName);
117}
118
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000119const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
120 bool CacheFailure) {
NAKAMURA Takumi8bd8ee72012-06-16 06:04:10 +0000121 // stat doesn't like trailing separators except for root directory.
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000122 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
123 // (though it can strip '\\')
NAKAMURA Takumi8bd8ee72012-06-16 06:04:10 +0000124 if (DirName.size() > 1 &&
125 DirName != llvm::sys::path::root_path(DirName) &&
126 llvm::sys::path::is_separator(DirName.back()))
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000127 DirName = DirName.substr(0, DirName.size()-1);
Nico Weber1865df42018-04-27 19:11:14 +0000128#ifdef _WIN32
Rafael Espindolaee305462013-07-29 15:47:24 +0000129 // Fixing a problem with "clang C:test.c" on Windows.
130 // Stat("C:") does not recognize "C:" as a valid directory
131 std::string DirNameStr;
132 if (DirName.size() > 1 && DirName.back() == ':' &&
133 DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
134 DirNameStr = DirName.str() + '.';
135 DirName = DirNameStr;
136 }
137#endif
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000138
Chris Lattner22eb9722006-06-18 05:43:12 +0000139 ++NumDirLookups;
David Blaikie13156b62014-11-19 03:06:06 +0000140 auto &NamedDirEnt =
141 *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first;
Mike Stump11289f42009-09-09 15:08:12 +0000142
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000143 // See if there was already an entry in the map. Note that the map
144 // contains both virtual and real directories.
David Blaikie13156b62014-11-19 03:06:06 +0000145 if (NamedDirEnt.second)
146 return NamedDirEnt.second == NON_EXISTENT_DIR ? nullptr
147 : NamedDirEnt.second;
Mike Stump11289f42009-09-09 15:08:12 +0000148
Chris Lattner22eb9722006-06-18 05:43:12 +0000149 ++NumDirCacheMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000150
Chris Lattneraf653752006-10-30 03:06:54 +0000151 // By default, initialize it to invalid.
David Blaikie13156b62014-11-19 03:06:06 +0000152 NamedDirEnt.second = NON_EXISTENT_DIR;
Mike Stump11289f42009-09-09 15:08:12 +0000153
Chris Lattner43fd42e2006-10-30 03:40:58 +0000154 // Get the null-terminated directory name as stored as the key of the
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000155 // SeenDirEntries map.
Mehdi Amini0df59d82016-10-11 07:31:29 +0000156 StringRef InterndDirName = NamedDirEnt.first();
Mike Stump11289f42009-09-09 15:08:12 +0000157
Chris Lattneraf653752006-10-30 03:06:54 +0000158 // Check to see if the directory exists.
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000159 FileData Data;
Craig Topperf1186c52014-05-08 06:41:40 +0000160 if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000161 // There's no real directory at the given path.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000162 if (!CacheFailure)
163 SeenDirEntries.erase(DirName);
Craig Topperf1186c52014-05-08 06:41:40 +0000164 return nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000165 }
Ted Kremenekd87eef82008-02-24 03:15:25 +0000166
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000167 // It exists. See if we have already opened a directory with the
168 // same inode (this occurs on Unix-like systems when one dir is
169 // symlinked to another, for example) or the same path (on
170 // Windows).
Ben Langmuirc9b72342014-02-27 22:21:32 +0000171 DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID];
Mike Stump11289f42009-09-09 15:08:12 +0000172
David Blaikie13156b62014-11-19 03:06:06 +0000173 NamedDirEnt.second = &UDE;
Mehdi Amini0df59d82016-10-11 07:31:29 +0000174 if (UDE.getName().empty()) {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000175 // We don't have this directory yet, add it. We use the string
176 // key from the SeenDirEntries map as the string.
177 UDE.Name = InterndDirName;
178 }
Mike Stump11289f42009-09-09 15:08:12 +0000179
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000180 return &UDE;
Chris Lattner22eb9722006-06-18 05:43:12 +0000181}
182
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000183const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
184 bool CacheFailure) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000185 ++NumFileLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000186
Chris Lattner22eb9722006-06-18 05:43:12 +0000187 // See if there is already an entry in the map.
David Blaikie13156b62014-11-19 03:06:06 +0000188 auto &NamedFileEnt =
189 *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
Chris Lattner22eb9722006-06-18 05:43:12 +0000190
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000191 // See if there is already an entry in the map.
Sam McCalle84385f2018-11-19 13:37:46 +0000192 if (NamedFileEnt.second) {
193 if (NamedFileEnt.second == NON_EXISTENT_FILE)
194 return nullptr;
195 // Entry exists: return it *unless* it wasn't opened and open is requested.
196 if (!(NamedFileEnt.second->DeferredOpen && openFile))
197 return NamedFileEnt.second;
198 // We previously stat()ed the file, but didn't open it: do that below.
199 // FIXME: the below does other redundant work too (stats the dir and file).
200 } else {
201 // By default, initialize it to invalid.
202 NamedFileEnt.second = NON_EXISTENT_FILE;
203 }
Mike Stump11289f42009-09-09 15:08:12 +0000204
Chris Lattner22eb9722006-06-18 05:43:12 +0000205 ++NumFileCacheMisses;
206
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000207 // Get the null-terminated file name as stored as the key of the
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000208 // SeenFileEntries map.
Mehdi Amini0df59d82016-10-11 07:31:29 +0000209 StringRef InterndFileName = NamedFileEnt.first();
Mike Stump11289f42009-09-09 15:08:12 +0000210
Chris Lattner966b25b2010-11-23 20:30:42 +0000211 // Look up the directory for the file. When looking up something like
212 // sys/foo.h we'll discover all of the search directories that have a 'sys'
213 // subdirectory. This will let us avoid having to waste time on known-to-fail
214 // searches when we go to find sys/bar.h, because all the search directories
215 // without a 'sys' subdir will get a cached failure result.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000216 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
217 CacheFailure);
Craig Topperf1186c52014-05-08 06:41:40 +0000218 if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000219 if (!CacheFailure)
220 SeenFileEntries.erase(Filename);
Craig Topperf1186c52014-05-08 06:41:40 +0000221
222 return nullptr;
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000223 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000224
Chris Lattner22eb9722006-06-18 05:43:12 +0000225 // FIXME: Use the directory info to prune this, before doing the stat syscall.
226 // FIXME: This will reduce the # syscalls.
Mike Stump11289f42009-09-09 15:08:12 +0000227
Chris Lattner22eb9722006-06-18 05:43:12 +0000228 // Nope, there isn't. Check to see if the file exists.
Jonas Devliegherefc514902018-10-10 13:27:25 +0000229 std::unique_ptr<llvm::vfs::File> F;
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000230 FileData Data;
Craig Topperf1186c52014-05-08 06:41:40 +0000231 if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000232 // There's no real file at the given path.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000233 if (!CacheFailure)
234 SeenFileEntries.erase(Filename);
Craig Topperf1186c52014-05-08 06:41:40 +0000235
236 return nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000237 }
Mike Stump11289f42009-09-09 15:08:12 +0000238
Patrik Hagglundab01d4b2014-02-21 07:23:53 +0000239 assert((openFile || !F) && "undesired open file");
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000240
Ted Kremenekf4c38c92007-12-18 22:29:39 +0000241 // It exists. See if we have already opened a file with the same inode.
Chris Lattner22eb9722006-06-18 05:43:12 +0000242 // This occurs when one dir is symlinked to another, for example.
Ben Langmuirc9b72342014-02-27 22:21:32 +0000243 FileEntry &UFE = UniqueRealFiles[Data.UniqueID];
Sam McCalle84385f2018-11-19 13:37:46 +0000244 UFE.DeferredOpen = !openFile;
Mike Stump11289f42009-09-09 15:08:12 +0000245
David Blaikie13156b62014-11-19 03:06:06 +0000246 NamedFileEnt.second = &UFE;
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000247
248 // If the name returned by getStatValue is different than Filename, re-intern
249 // the name.
250 if (Data.Name != Filename) {
David Blaikie13156b62014-11-19 03:06:06 +0000251 auto &NamedFileEnt =
252 *SeenFileEntries.insert(std::make_pair(Data.Name, nullptr)).first;
253 if (!NamedFileEnt.second)
254 NamedFileEnt.second = &UFE;
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000255 else
David Blaikie13156b62014-11-19 03:06:06 +0000256 assert(NamedFileEnt.second == &UFE &&
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000257 "filename from getStatValue() refers to wrong file");
David Blaikie13156b62014-11-19 03:06:06 +0000258 InterndFileName = NamedFileEnt.first().data();
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000259 }
260
Sam McCalle84385f2018-11-19 13:37:46 +0000261 // If we opened the file for the first time, record the resulting info.
262 // Do this even if the cache entry was valid, maybe we didn't previously open.
263 if (F && !UFE.File) {
Kadir Cetinkayae9870c02018-11-30 17:10:11 +0000264 if (auto PathName = F->getName())
265 fillRealPathName(&UFE, *PathName);
Sam McCalle84385f2018-11-19 13:37:46 +0000266 UFE.File = std::move(F);
267 assert(!UFE.DeferredOpen && "we just opened it!");
268 }
269
Ben Langmuirc8a71462014-02-27 17:23:33 +0000270 if (UFE.isValid()) { // Already have an entry with this inode, return it.
Ben Langmuir5de00f32014-05-23 18:15:47 +0000271
272 // FIXME: this hack ensures that if we look up a file by a virtual path in
273 // the VFS that the getDir() will have the virtual path, even if we found
274 // the file by a 'real' path first. This is required in order to find a
275 // module's structure when its headers/module map are mapped in the VFS.
276 // We should remove this as soon as we can properly support a file having
277 // multiple names.
278 if (DirInfo != UFE.Dir && Data.IsVFSMapped)
279 UFE.Dir = DirInfo;
280
Manuel Klimekc0ff9902014-08-13 12:34:41 +0000281 // Always update the name to use the last name by which a file was accessed.
282 // FIXME: Neither this nor always using the first name is correct; we want
283 // to switch towards a design where we return a FileName object that
284 // encapsulates both the name by which the file was accessed and the
285 // corresponding FileEntry.
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000286 UFE.Name = InterndFileName;
Manuel Klimekc0ff9902014-08-13 12:34:41 +0000287
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000288 return &UFE;
Chris Lattnerdd278432010-11-23 21:17:56 +0000289 }
Chris Lattner269c2322006-06-25 06:23:00 +0000290
Ben Langmuirc9b72342014-02-27 22:21:32 +0000291 // Otherwise, we don't have this file yet, add it.
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000292 UFE.Name = InterndFileName;
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000293 UFE.Size = Data.Size;
294 UFE.ModTime = Data.ModTime;
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000295 UFE.Dir = DirInfo;
296 UFE.UID = NextFileUID++;
Ben Langmuirc9b72342014-02-27 22:21:32 +0000297 UFE.UniqueID = Data.UniqueID;
298 UFE.IsNamedPipe = Data.IsNamedPipe;
299 UFE.InPCH = Data.InPCH;
Ben Langmuirc8a71462014-02-27 17:23:33 +0000300 UFE.IsValid = true;
Sam McCalle84385f2018-11-19 13:37:46 +0000301 // Note File and DeferredOpen were initialized above.
Simon Marchiddbabc62018-08-06 21:48:20 +0000302
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000303 return &UFE;
Chris Lattner22eb9722006-06-18 05:43:12 +0000304}
305
Douglas Gregor407e2122009-12-02 18:12:28 +0000306const FileEntry *
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000307FileManager::getVirtualFile(StringRef Filename, off_t Size,
Chris Lattner5159f612010-11-23 08:35:12 +0000308 time_t ModificationTime) {
Douglas Gregor407e2122009-12-02 18:12:28 +0000309 ++NumFileLookups;
310
311 // See if there is already an entry in the map.
David Blaikie13156b62014-11-19 03:06:06 +0000312 auto &NamedFileEnt =
313 *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first;
Douglas Gregor407e2122009-12-02 18:12:28 +0000314
315 // See if there is already an entry in the map.
David Blaikie13156b62014-11-19 03:06:06 +0000316 if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE)
317 return NamedFileEnt.second;
Douglas Gregor407e2122009-12-02 18:12:28 +0000318
319 ++NumFileCacheMisses;
320
321 // By default, initialize it to invalid.
David Blaikie13156b62014-11-19 03:06:06 +0000322 NamedFileEnt.second = NON_EXISTENT_FILE;
Douglas Gregor407e2122009-12-02 18:12:28 +0000323
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000324 addAncestorsAsVirtualDirs(Filename);
Craig Topperf1186c52014-05-08 06:41:40 +0000325 FileEntry *UFE = nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000326
327 // Now that all ancestors of Filename are in the cache, the
328 // following call is guaranteed to find the DirectoryEntry from the
329 // cache.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000330 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
331 /*CacheFailure=*/true);
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000332 assert(DirInfo &&
333 "The directory of a virtual file should already be in the cache.");
Douglas Gregor407e2122009-12-02 18:12:28 +0000334
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000335 // Check to see if the file exists. If so, drop the virtual file
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000336 FileData Data;
David Blaikie13156b62014-11-19 03:06:06 +0000337 const char *InterndFileName = NamedFileEnt.first().data();
Craig Topperf1186c52014-05-08 06:41:40 +0000338 if (getStatValue(InterndFileName, Data, true, nullptr) == 0) {
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000339 Data.Size = Size;
340 Data.ModTime = ModificationTime;
Ben Langmuirc9b72342014-02-27 22:21:32 +0000341 UFE = &UniqueRealFiles[Data.UniqueID];
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000342
David Blaikie13156b62014-11-19 03:06:06 +0000343 NamedFileEnt.second = UFE;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000344
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000345 // If we had already opened this file, close it now so we don't
346 // leak the descriptor. We're not going to use the file
347 // descriptor anyway, since this is a virtual file.
Ben Langmuirc8130a72014-02-20 21:59:23 +0000348 if (UFE->File)
349 UFE->closeFile();
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000350
351 // If we already have an entry with this inode, return it.
Ben Langmuirc8a71462014-02-27 17:23:33 +0000352 if (UFE->isValid())
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000353 return UFE;
Ben Langmuirc9b72342014-02-27 22:21:32 +0000354
355 UFE->UniqueID = Data.UniqueID;
356 UFE->IsNamedPipe = Data.IsNamedPipe;
357 UFE->InPCH = Data.InPCH;
Kadir Cetinkayae9870c02018-11-30 17:10:11 +0000358 fillRealPathName(UFE, Data.Name);
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000359 }
360
361 if (!UFE) {
David Blaikied2725a32015-12-09 17:23:13 +0000362 VirtualFileEntries.push_back(llvm::make_unique<FileEntry>());
363 UFE = VirtualFileEntries.back().get();
David Blaikie13156b62014-11-19 03:06:06 +0000364 NamedFileEnt.second = UFE;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000365 }
Douglas Gregor407e2122009-12-02 18:12:28 +0000366
Chris Lattner9624b692010-11-23 20:50:22 +0000367 UFE->Name = InterndFileName;
Douglas Gregor407e2122009-12-02 18:12:28 +0000368 UFE->Size = Size;
369 UFE->ModTime = ModificationTime;
370 UFE->Dir = DirInfo;
371 UFE->UID = NextFileUID++;
Erik Verbruggendfffaf52017-03-28 09:18:05 +0000372 UFE->IsValid = true;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000373 UFE->File.reset();
Sam McCalle84385f2018-11-19 13:37:46 +0000374 UFE->DeferredOpen = false;
Douglas Gregor407e2122009-12-02 18:12:28 +0000375 return UFE;
376}
377
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +0000378bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000379 StringRef pathRef(path.data(), path.size());
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000380
Fangrui Song6907ce22018-07-30 19:24:48 +0000381 if (FileSystemOpts.WorkingDir.empty()
Anders Carlsson9ba8fb12011-03-14 01:13:54 +0000382 || llvm::sys::path::is_absolute(pathRef))
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +0000383 return false;
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000384
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000385 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000386 llvm::sys::path::append(NewPath, pathRef);
Chris Lattner6e640992010-11-23 04:45:28 +0000387 path = NewPath;
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +0000388 return true;
389}
390
391bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
392 bool Changed = FixupRelativePath(Path);
393
394 if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
Ilya Biryukov47035c02017-08-02 07:25:24 +0000395 FS->makeAbsolute(Path);
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +0000396 Changed = true;
397 }
398
399 return Changed;
Chris Lattner6e640992010-11-23 04:45:28 +0000400}
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000401
Kadir Cetinkayae9870c02018-11-30 17:10:11 +0000402void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
403 llvm::SmallString<128> AbsPath(FileName);
404 // This is not the same as `VFS::getRealPath()`, which resolves symlinks
405 // but can be very expensive on real file systems.
406 // FIXME: the semantic of RealPathName is unclear, and the name might be
407 // misleading. We need to clean up the interface here.
408 makeAbsolutePath(AbsPath);
409 llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
410 UFE->RealPathName = AbsPath.str();
411}
412
Benjamin Kramera8857962014-10-26 22:44:13 +0000413llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
414FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
415 bool ShouldCloseOpenFile) {
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000416 uint64_t FileSize = Entry->getSize();
417 // If there's a high enough chance that the file have changed since we
418 // got its size, force a stat before opening it.
419 if (isVolatile)
420 FileSize = -1;
421
Mehdi Amini004b9c72016-10-10 22:52:47 +0000422 StringRef Filename = Entry->getName();
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44 +0000423 // If the file is already open, use the open file descriptor.
Ben Langmuirc8130a72014-02-20 21:59:23 +0000424 if (Entry->File) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000425 auto Result =
426 Entry->File->getBuffer(Filename, FileSize,
427 /*RequiresNullTerminator=*/true, isVolatile);
Ben Langmuir9801b252014-06-20 00:24:56 +0000428 // FIXME: we need a set of APIs that can make guarantees about whether a
429 // FileEntry is open or not.
430 if (ShouldCloseOpenFile)
431 Entry->closeFile();
Rafael Espindola6406f7b2014-08-26 19:54:40 +0000432 return Result;
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44 +0000433 }
434
435 // Otherwise, open the file.
436
Benjamin Kramera8857962014-10-26 22:44:13 +0000437 if (FileSystemOpts.WorkingDir.empty())
438 return FS->getBufferForFile(Filename, FileSize,
439 /*RequiresNullTerminator=*/true, isVolatile);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000440
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000441 SmallString<128> FilePath(Entry->getName());
Anders Carlsson878b3e22011-03-07 01:28:33 +0000442 FixupRelativePath(FilePath);
Yaron Keren92e1b622015-03-18 10:17:07 +0000443 return FS->getBufferForFile(FilePath, FileSize,
Benjamin Kramera8857962014-10-26 22:44:13 +0000444 /*RequiresNullTerminator=*/true, isVolatile);
Chris Lattner26b5c192010-11-23 09:19:42 +0000445}
446
Benjamin Kramera8857962014-10-26 22:44:13 +0000447llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +0000448FileManager::getBufferForFile(StringRef Filename, bool isVolatile) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000449 if (FileSystemOpts.WorkingDir.empty())
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +0000450 return FS->getBufferForFile(Filename, -1, true, isVolatile);
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000451
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000452 SmallString<128> FilePath(Filename);
Anders Carlsson878b3e22011-03-07 01:28:33 +0000453 FixupRelativePath(FilePath);
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +0000454 return FS->getBufferForFile(FilePath.c_str(), -1, true, isVolatile);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000455}
456
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000457/// getStatValue - Get the 'stat' information for the specified path,
458/// using the cache to accelerate it if possible. This returns true
459/// if the path points to a virtual file or does not exist, or returns
460/// false if it's an existent real file. If FileDescriptor is NULL,
461/// do directory look-up instead of file look-up.
Mehdi Amini0df59d82016-10-11 07:31:29 +0000462bool FileManager::getStatValue(StringRef Path, FileData &Data, bool isFile,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000463 std::unique_ptr<llvm::vfs::File> *F) {
Chris Lattner226efd32010-11-23 19:19:34 +0000464 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
465 // absolute!
Chris Lattner5769c3d2010-11-23 19:56:39 +0000466 if (FileSystemOpts.WorkingDir.empty())
Ben Langmuirc8130a72014-02-20 21:59:23 +0000467 return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000468
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000469 SmallString<128> FilePath(Path);
Anders Carlsson878b3e22011-03-07 01:28:33 +0000470 FixupRelativePath(FilePath);
Chris Lattner5769c3d2010-11-23 19:56:39 +0000471
Ben Langmuirc8130a72014-02-20 21:59:23 +0000472 return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
473 StatCache.get(), *FS);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000474}
475
Rafael Espindolae4777f42013-07-29 18:22:23 +0000476bool FileManager::getNoncachedStatValue(StringRef Path,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000477 llvm::vfs::Status &Result) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000478 SmallString<128> FilePath(Path);
Anders Carlsson5e368402011-03-18 19:23:19 +0000479 FixupRelativePath(FilePath);
480
Jonas Devliegherefc514902018-10-10 13:27:25 +0000481 llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000482 if (!S)
483 return true;
484 Result = *S;
485 return false;
Anders Carlsson5e368402011-03-18 19:23:19 +0000486}
487
Axel Naumannb3074002012-07-10 16:50:27 +0000488void FileManager::invalidateCache(const FileEntry *Entry) {
489 assert(Entry && "Cannot invalidate a NULL FileEntry");
Axel Naumann38179d92012-06-27 09:17:42 +0000490
491 SeenFileEntries.erase(Entry->getName());
Axel Naumannb3074002012-07-10 16:50:27 +0000492
493 // FileEntry invalidation should not block future optimizations in the file
494 // caches. Possible alternatives are cache truncation (invalidate last N) or
495 // invalidation of the whole cache.
Ben Langmuirc9b72342014-02-27 22:21:32 +0000496 UniqueRealFiles.erase(Entry->getUniqueID());
Axel Naumann38179d92012-06-27 09:17:42 +0000497}
498
Douglas Gregor09b69892011-02-10 17:09:37 +0000499void FileManager::GetUniqueIDMapping(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000500 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
Douglas Gregor09b69892011-02-10 17:09:37 +0000501 UIDToFiles.clear();
502 UIDToFiles.resize(NextFileUID);
Fangrui Song6907ce22018-07-30 19:24:48 +0000503
Douglas Gregor09b69892011-02-10 17:09:37 +0000504 // Map file entries
505 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000506 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
Douglas Gregor09b69892011-02-10 17:09:37 +0000507 FE != FEEnd; ++FE)
508 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
509 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000510
Douglas Gregor09b69892011-02-10 17:09:37 +0000511 // Map virtual file entries
David Blaikied2725a32015-12-09 17:23:13 +0000512 for (const auto &VFE : VirtualFileEntries)
513 if (VFE && VFE.get() != NON_EXISTENT_FILE)
514 UIDToFiles[VFE->getUID()] = VFE.get();
Douglas Gregor09b69892011-02-10 17:09:37 +0000515}
Chris Lattner226efd32010-11-23 19:19:34 +0000516
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000517void FileManager::modifyFileEntry(FileEntry *File,
518 off_t Size, time_t ModificationTime) {
519 File->Size = Size;
520 File->ModTime = ModificationTime;
521}
522
Douglas Gregore00c8b22013-01-26 00:55:12 +0000523StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
524 // FIXME: use llvm::sys::fs::canonical() when it gets implemented
Douglas Gregore00c8b22013-01-26 00:55:12 +0000525 llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
526 = CanonicalDirNames.find(Dir);
527 if (Known != CanonicalDirNames.end())
528 return Known->second;
529
530 StringRef CanonicalName(Dir->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +0000531
Eric Liu5fb18fe2018-05-17 10:26:23 +0000532 SmallString<4096> CanonicalNameBuf;
533 if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
Benjamin Kramerda4690a2015-08-04 11:27:08 +0000534 CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
Douglas Gregore00c8b22013-01-26 00:55:12 +0000535
536 CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
537 return CanonicalName;
Douglas Gregore00c8b22013-01-26 00:55:12 +0000538}
Chris Lattner226efd32010-11-23 19:19:34 +0000539
Chris Lattner22eb9722006-06-18 05:43:12 +0000540void FileManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000541 llvm::errs() << "\n*** File Manager Stats:\n";
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000542 llvm::errs() << UniqueRealFiles.size() << " real files found, "
543 << UniqueRealDirs.size() << " real dirs found.\n";
544 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
545 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000546 llvm::errs() << NumDirLookups << " dir lookups, "
547 << NumDirCacheMisses << " dir cache misses.\n";
548 llvm::errs() << NumFileLookups << " file lookups, "
549 << NumFileCacheMisses << " file cache misses.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000550
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000551 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
Chris Lattner22eb9722006-06-18 05:43:12 +0000552}