blob: 0926376cf1035ec32e9f75c580b97040cbe7e339 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner22eb9722006-06-18 05:43:12 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the FileManager interface.
10//
11//===----------------------------------------------------------------------===//
12//
13// TODO: This should index all interesting directories with dirent calls.
14// getdirentries ?
15// opendir/readdir_r/closedir ?
16//
17//===----------------------------------------------------------------------===//
18
19#include "clang/Basic/FileManager.h"
Chris Lattner226efd32010-11-23 19:19:34 +000020#include "clang/Basic/FileSystemStatCache.h"
Chris Lattner2f4a89a2006-10-30 03:55:17 +000021#include "llvm/ADT/SmallString.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "llvm/Config/llvm-config.h"
David Blaikied2725a32015-12-09 17:23:13 +000023#include "llvm/ADT/STLExtras.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"
Eugene Zelenko35b79c22016-08-13 01:05:35 +000028#include <algorithm>
29#include <cassert>
30#include <climits>
31#include <cstdint>
32#include <cstdlib>
Benjamin Kramer26db6482009-09-05 09:49:39 +000033#include <string>
Eugene Zelenko35b79c22016-08-13 01:05:35 +000034#include <utility>
Chris Lattner278038b2010-11-23 21:53:15 +000035
Chris Lattner22eb9722006-06-18 05:43:12 +000036using namespace clang;
37
Ted Kremenek5c04bd82009-01-28 00:27:31 +000038//===----------------------------------------------------------------------===//
39// Common logic.
40//===----------------------------------------------------------------------===//
Ted Kremenekd87eef82008-02-24 03:15:25 +000041
Ben Langmuirc8130a72014-02-20 21:59:23 +000042FileManager::FileManager(const FileSystemOptions &FSO,
Jonas Devliegherefc514902018-10-10 13:27:25 +000043 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
Benjamin Kramerf6021ec2017-03-21 21:35:04 +000044 : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
45 SeenFileEntries(64), NextFileUID(0) {
Ted Kremenekd87eef82008-02-24 03:15:25 +000046 NumDirLookups = NumFileLookups = 0;
47 NumDirCacheMisses = NumFileCacheMisses = 0;
Ben Langmuirc8130a72014-02-20 21:59:23 +000048
49 // If the caller doesn't provide a virtual file system, just grab the real
50 // file system.
Benjamin Kramerf6021ec2017-03-21 21:35:04 +000051 if (!this->FS)
Jonas Devliegherefc514902018-10-10 13:27:25 +000052 this->FS = llvm::vfs::getRealFileSystem();
Ted Kremenekd87eef82008-02-24 03:15:25 +000053}
54
David Blaikied2725a32015-12-09 17:23:13 +000055FileManager::~FileManager() = default;
Ted Kremenekd87eef82008-02-24 03:15:25 +000056
Alex Lorenzd92b1ae2018-12-21 19:33:09 +000057void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
Douglas Gregord2eb58a2009-10-16 18:18:30 +000058 assert(statCache && "No stat cache provided?");
Alex Lorenzd92b1ae2018-12-21 19:33:09 +000059 StatCache = std::move(statCache);
Douglas Gregord2eb58a2009-10-16 18:18:30 +000060}
61
Alex Lorenzd92b1ae2018-12-21 19:33:09 +000062void FileManager::clearStatCache() { StatCache.reset(); }
Manuel Klimek3aad8552012-07-31 13:56:54 +000063
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000064/// Retrieve the directory that the given file name resides in.
Zhanyong Wane1dd3e22011-02-11 18:44:49 +000065/// Filename can point to either a real file or a virtual file.
Douglas Gregor407e2122009-12-02 18:12:28 +000066static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
Douglas Gregor1735f4e2011-09-13 23:15:45 +000067 StringRef Filename,
68 bool CacheFailure) {
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +000069 if (Filename.empty())
Craig Topperf1186c52014-05-08 06:41:40 +000070 return nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +000071
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +000072 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
Craig Topperf1186c52014-05-08 06:41:40 +000073 return nullptr; // If Filename is a directory.
Benjamin Kramer3cf715d2010-11-21 11:32:22 +000074
Chris Lattner0e62c1c2011-07-23 10:55:15 +000075 StringRef DirName = llvm::sys::path::parent_path(Filename);
Chris Lattner0c0e8042010-11-21 09:50:16 +000076 // Use the current directory if file has no path component.
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +000077 if (DirName.empty())
78 DirName = ".";
Douglas Gregor407e2122009-12-02 18:12:28 +000079
Douglas Gregor1735f4e2011-09-13 23:15:45 +000080 return FileMgr.getDirectory(DirName, CacheFailure);
Douglas Gregor407e2122009-12-02 18:12:28 +000081}
82
Zhanyong Wane1dd3e22011-02-11 18:44:49 +000083/// Add all ancestors of the given path (pointing to either a file or
84/// a directory) as virtual directories.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000085void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
86 StringRef DirName = llvm::sys::path::parent_path(Path);
Zhanyong Wanf3c0ff72011-02-11 21:25:35 +000087 if (DirName.empty())
David Majnemer1834dc72016-04-12 16:33:53 +000088 DirName = ".";
Zhanyong Wane1dd3e22011-02-11 18:44:49 +000089
Richard Smith018ab5f2019-01-30 02:23:34 +000090 auto &NamedDirEnt = *SeenDirEntries.insert({DirName, nullptr}).first;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +000091
92 // When caching a virtual directory, we always cache its ancestors
93 // at the same time. Therefore, if DirName is already in the cache,
94 // we don't need to recurse as its ancestors must also already be in
Richard Smith018ab5f2019-01-30 02:23:34 +000095 // the cache (or it's a known non-virtual directory).
96 if (NamedDirEnt.second)
Zhanyong Wane1dd3e22011-02-11 18:44:49 +000097 return;
98
99 // Add the virtual directory to the cache.
David Blaikied2725a32015-12-09 17:23:13 +0000100 auto UDE = llvm::make_unique<DirectoryEntry>();
Mehdi Amini0df59d82016-10-11 07:31:29 +0000101 UDE->Name = NamedDirEnt.first();
David Blaikied2725a32015-12-09 17:23:13 +0000102 NamedDirEnt.second = UDE.get();
103 VirtualDirectoryEntries.push_back(std::move(UDE));
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000104
105 // Recursively add the other ancestors.
106 addAncestorsAsVirtualDirs(DirName);
107}
108
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000109const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
110 bool CacheFailure) {
NAKAMURA Takumi8bd8ee72012-06-16 06:04:10 +0000111 // stat doesn't like trailing separators except for root directory.
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000112 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
113 // (though it can strip '\\')
NAKAMURA Takumi8bd8ee72012-06-16 06:04:10 +0000114 if (DirName.size() > 1 &&
115 DirName != llvm::sys::path::root_path(DirName) &&
116 llvm::sys::path::is_separator(DirName.back()))
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000117 DirName = DirName.substr(0, DirName.size()-1);
Nico Weber1865df42018-04-27 19:11:14 +0000118#ifdef _WIN32
Rafael Espindolaee305462013-07-29 15:47:24 +0000119 // Fixing a problem with "clang C:test.c" on Windows.
120 // Stat("C:") does not recognize "C:" as a valid directory
121 std::string DirNameStr;
122 if (DirName.size() > 1 && DirName.back() == ':' &&
123 DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
124 DirNameStr = DirName.str() + '.';
125 DirName = DirNameStr;
126 }
127#endif
NAKAMURA Takumi32f1acf2011-11-17 06:16:05 +0000128
Chris Lattner22eb9722006-06-18 05:43:12 +0000129 ++NumDirLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000130
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000131 // See if there was already an entry in the map. Note that the map
132 // contains both virtual and real directories.
Richard Smith018ab5f2019-01-30 02:23:34 +0000133 auto SeenDirInsertResult = SeenDirEntries.insert({DirName, nullptr});
134 if (!SeenDirInsertResult.second)
135 return SeenDirInsertResult.first->second;
Mike Stump11289f42009-09-09 15:08:12 +0000136
Richard Smith018ab5f2019-01-30 02:23:34 +0000137 // We've not seen this before. Fill it in.
Chris Lattner22eb9722006-06-18 05:43:12 +0000138 ++NumDirCacheMisses;
Richard Smith018ab5f2019-01-30 02:23:34 +0000139 auto &NamedDirEnt = *SeenDirInsertResult.first;
140 assert(!NamedDirEnt.second && "should be newly-created");
Mike Stump11289f42009-09-09 15:08:12 +0000141
Chris Lattner43fd42e2006-10-30 03:40:58 +0000142 // Get the null-terminated directory name as stored as the key of the
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000143 // SeenDirEntries map.
Mehdi Amini0df59d82016-10-11 07:31:29 +0000144 StringRef InterndDirName = NamedDirEnt.first();
Mike Stump11289f42009-09-09 15:08:12 +0000145
Chris Lattneraf653752006-10-30 03:06:54 +0000146 // Check to see if the directory exists.
Harlan Haskins06f64d52019-03-05 02:27:12 +0000147 llvm::vfs::Status Status;
148 if (getStatValue(InterndDirName, Status, false, nullptr /*directory lookup*/)) {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000149 // There's no real directory at the given path.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000150 if (!CacheFailure)
151 SeenDirEntries.erase(DirName);
Craig Topperf1186c52014-05-08 06:41:40 +0000152 return nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000153 }
Ted Kremenekd87eef82008-02-24 03:15:25 +0000154
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000155 // It exists. See if we have already opened a directory with the
156 // same inode (this occurs on Unix-like systems when one dir is
157 // symlinked to another, for example) or the same path (on
158 // Windows).
Harlan Haskins06f64d52019-03-05 02:27:12 +0000159 DirectoryEntry &UDE = UniqueRealDirs[Status.getUniqueID()];
Mike Stump11289f42009-09-09 15:08:12 +0000160
David Blaikie13156b62014-11-19 03:06:06 +0000161 NamedDirEnt.second = &UDE;
Mehdi Amini0df59d82016-10-11 07:31:29 +0000162 if (UDE.getName().empty()) {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000163 // We don't have this directory yet, add it. We use the string
164 // key from the SeenDirEntries map as the string.
165 UDE.Name = InterndDirName;
166 }
Mike Stump11289f42009-09-09 15:08:12 +0000167
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000168 return &UDE;
Chris Lattner22eb9722006-06-18 05:43:12 +0000169}
170
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000171const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
172 bool CacheFailure) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000173 ++NumFileLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000174
Chris Lattner22eb9722006-06-18 05:43:12 +0000175 // See if there is already an entry in the map.
Richard Smith018ab5f2019-01-30 02:23:34 +0000176 auto SeenFileInsertResult = SeenFileEntries.insert({Filename, nullptr});
177 if (!SeenFileInsertResult.second)
178 return SeenFileInsertResult.first->second;
Chris Lattner22eb9722006-06-18 05:43:12 +0000179
Richard Smith018ab5f2019-01-30 02:23:34 +0000180 // We've not seen this before. Fill it in.
Chris Lattner22eb9722006-06-18 05:43:12 +0000181 ++NumFileCacheMisses;
Richard Smith018ab5f2019-01-30 02:23:34 +0000182 auto &NamedFileEnt = *SeenFileInsertResult.first;
183 assert(!NamedFileEnt.second && "should be newly-created");
Sam McCallfa361202019-01-24 18:55:24 +0000184
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000185 // Get the null-terminated file name as stored as the key of the
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000186 // SeenFileEntries map.
Mehdi Amini0df59d82016-10-11 07:31:29 +0000187 StringRef InterndFileName = NamedFileEnt.first();
Mike Stump11289f42009-09-09 15:08:12 +0000188
Chris Lattner966b25b2010-11-23 20:30:42 +0000189 // Look up the directory for the file. When looking up something like
190 // sys/foo.h we'll discover all of the search directories that have a 'sys'
191 // subdirectory. This will let us avoid having to waste time on known-to-fail
192 // searches when we go to find sys/bar.h, because all the search directories
193 // without a 'sys' subdir will get a cached failure result.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000194 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
195 CacheFailure);
Craig Topperf1186c52014-05-08 06:41:40 +0000196 if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000197 if (!CacheFailure)
198 SeenFileEntries.erase(Filename);
Craig Topperf1186c52014-05-08 06:41:40 +0000199
200 return nullptr;
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000201 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000202
Chris Lattner22eb9722006-06-18 05:43:12 +0000203 // FIXME: Use the directory info to prune this, before doing the stat syscall.
204 // FIXME: This will reduce the # syscalls.
Mike Stump11289f42009-09-09 15:08:12 +0000205
Richard Smith018ab5f2019-01-30 02:23:34 +0000206 // Check to see if the file exists.
Jonas Devliegherefc514902018-10-10 13:27:25 +0000207 std::unique_ptr<llvm::vfs::File> F;
Harlan Haskins06f64d52019-03-05 02:27:12 +0000208 llvm::vfs::Status Status;
209 if (getStatValue(InterndFileName, Status, true, openFile ? &F : nullptr)) {
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000210 // There's no real file at the given path.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000211 if (!CacheFailure)
212 SeenFileEntries.erase(Filename);
Craig Topperf1186c52014-05-08 06:41:40 +0000213
214 return nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000215 }
Mike Stump11289f42009-09-09 15:08:12 +0000216
Patrik Hagglundab01d4b2014-02-21 07:23:53 +0000217 assert((openFile || !F) && "undesired open file");
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000218
Ted Kremenekf4c38c92007-12-18 22:29:39 +0000219 // It exists. See if we have already opened a file with the same inode.
Chris Lattner22eb9722006-06-18 05:43:12 +0000220 // This occurs when one dir is symlinked to another, for example.
Harlan Haskins06f64d52019-03-05 02:27:12 +0000221 FileEntry &UFE = UniqueRealFiles[Status.getUniqueID()];
Mike Stump11289f42009-09-09 15:08:12 +0000222
David Blaikie13156b62014-11-19 03:06:06 +0000223 NamedFileEnt.second = &UFE;
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000224
225 // If the name returned by getStatValue is different than Filename, re-intern
226 // the name.
Harlan Haskins06f64d52019-03-05 02:27:12 +0000227 if (Status.getName() != Filename) {
228 auto &NamedFileEnt =
229 *SeenFileEntries.insert({Status.getName(), &UFE}).first;
Richard Smith018ab5f2019-01-30 02:23:34 +0000230 assert(NamedFileEnt.second == &UFE &&
231 "filename from getStatValue() refers to wrong file");
David Blaikie13156b62014-11-19 03:06:06 +0000232 InterndFileName = NamedFileEnt.first().data();
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000233 }
234
Ben Langmuirc8a71462014-02-27 17:23:33 +0000235 if (UFE.isValid()) { // Already have an entry with this inode, return it.
Ben Langmuir5de00f32014-05-23 18:15:47 +0000236
237 // FIXME: this hack ensures that if we look up a file by a virtual path in
238 // the VFS that the getDir() will have the virtual path, even if we found
239 // the file by a 'real' path first. This is required in order to find a
240 // module's structure when its headers/module map are mapped in the VFS.
241 // We should remove this as soon as we can properly support a file having
242 // multiple names.
Harlan Haskins06f64d52019-03-05 02:27:12 +0000243 if (DirInfo != UFE.Dir && Status.IsVFSMapped)
Ben Langmuir5de00f32014-05-23 18:15:47 +0000244 UFE.Dir = DirInfo;
245
Manuel Klimekc0ff9902014-08-13 12:34:41 +0000246 // Always update the name to use the last name by which a file was accessed.
247 // FIXME: Neither this nor always using the first name is correct; we want
248 // to switch towards a design where we return a FileName object that
249 // encapsulates both the name by which the file was accessed and the
250 // corresponding FileEntry.
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000251 UFE.Name = InterndFileName;
Manuel Klimekc0ff9902014-08-13 12:34:41 +0000252
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000253 return &UFE;
Chris Lattnerdd278432010-11-23 21:17:56 +0000254 }
Chris Lattner269c2322006-06-25 06:23:00 +0000255
Ben Langmuirc9b72342014-02-27 22:21:32 +0000256 // Otherwise, we don't have this file yet, add it.
Ben Langmuirab86fbe2014-09-08 16:15:54 +0000257 UFE.Name = InterndFileName;
Harlan Haskins06f64d52019-03-05 02:27:12 +0000258 UFE.Size = Status.getSize();
259 UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
Chris Lattner2f4a89a2006-10-30 03:55:17 +0000260 UFE.Dir = DirInfo;
261 UFE.UID = NextFileUID++;
Harlan Haskins06f64d52019-03-05 02:27:12 +0000262 UFE.UniqueID = Status.getUniqueID();
263 UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
Sam McCallfa361202019-01-24 18:55:24 +0000264 UFE.File = std::move(F);
Ben Langmuirc8a71462014-02-27 17:23:33 +0000265 UFE.IsValid = true;
Simon Marchiddbabc62018-08-06 21:48:20 +0000266
Sam McCallfa361202019-01-24 18:55:24 +0000267 if (UFE.File) {
268 if (auto PathName = UFE.File->getName())
269 fillRealPathName(&UFE, *PathName);
Jan Korouscd8607d2019-02-18 22:33:40 +0000270 } else if (!openFile) {
271 // We should still fill the path even if we aren't opening the file.
272 fillRealPathName(&UFE, InterndFileName);
Sam McCallfa361202019-01-24 18:55:24 +0000273 }
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000274 return &UFE;
Chris Lattner22eb9722006-06-18 05:43:12 +0000275}
276
Douglas Gregor407e2122009-12-02 18:12:28 +0000277const FileEntry *
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000278FileManager::getVirtualFile(StringRef Filename, off_t Size,
Chris Lattner5159f612010-11-23 08:35:12 +0000279 time_t ModificationTime) {
Douglas Gregor407e2122009-12-02 18:12:28 +0000280 ++NumFileLookups;
281
Richard Smith018ab5f2019-01-30 02:23:34 +0000282 // See if there is already an entry in the map for an existing file.
283 auto &NamedFileEnt = *SeenFileEntries.insert({Filename, nullptr}).first;
284 if (NamedFileEnt.second)
David Blaikie13156b62014-11-19 03:06:06 +0000285 return NamedFileEnt.second;
Douglas Gregor407e2122009-12-02 18:12:28 +0000286
Richard Smith018ab5f2019-01-30 02:23:34 +0000287 // We've not seen this before, or the file is cached as non-existent.
Douglas Gregor407e2122009-12-02 18:12:28 +0000288 ++NumFileCacheMisses;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000289 addAncestorsAsVirtualDirs(Filename);
Craig Topperf1186c52014-05-08 06:41:40 +0000290 FileEntry *UFE = nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000291
292 // Now that all ancestors of Filename are in the cache, the
293 // following call is guaranteed to find the DirectoryEntry from the
294 // cache.
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000295 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
296 /*CacheFailure=*/true);
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000297 assert(DirInfo &&
298 "The directory of a virtual file should already be in the cache.");
Douglas Gregor407e2122009-12-02 18:12:28 +0000299
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000300 // Check to see if the file exists. If so, drop the virtual file
Harlan Haskins06f64d52019-03-05 02:27:12 +0000301 llvm::vfs::Status Status;
David Blaikie13156b62014-11-19 03:06:06 +0000302 const char *InterndFileName = NamedFileEnt.first().data();
Harlan Haskins06f64d52019-03-05 02:27:12 +0000303 if (getStatValue(InterndFileName, Status, true, nullptr) == 0) {
304 UFE = &UniqueRealFiles[Status.getUniqueID()];
305 Status = llvm::vfs::Status(
306 Status.getName(), Status.getUniqueID(),
307 llvm::sys::toTimePoint(ModificationTime),
308 Status.getUser(), Status.getGroup(), Size,
309 Status.getType(), Status.getPermissions());
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000310
David Blaikie13156b62014-11-19 03:06:06 +0000311 NamedFileEnt.second = UFE;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000312
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000313 // If we had already opened this file, close it now so we don't
314 // leak the descriptor. We're not going to use the file
315 // descriptor anyway, since this is a virtual file.
Ben Langmuirc8130a72014-02-20 21:59:23 +0000316 if (UFE->File)
317 UFE->closeFile();
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000318
319 // If we already have an entry with this inode, return it.
Ben Langmuirc8a71462014-02-27 17:23:33 +0000320 if (UFE->isValid())
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000321 return UFE;
Ben Langmuirc9b72342014-02-27 22:21:32 +0000322
Harlan Haskins06f64d52019-03-05 02:27:12 +0000323 UFE->UniqueID = Status.getUniqueID();
324 UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
325 fillRealPathName(UFE, Status.getName());
Richard Smith018ab5f2019-01-30 02:23:34 +0000326 } else {
David Blaikied2725a32015-12-09 17:23:13 +0000327 VirtualFileEntries.push_back(llvm::make_unique<FileEntry>());
328 UFE = VirtualFileEntries.back().get();
David Blaikie13156b62014-11-19 03:06:06 +0000329 NamedFileEnt.second = UFE;
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000330 }
Douglas Gregor407e2122009-12-02 18:12:28 +0000331
Chris Lattner9624b692010-11-23 20:50:22 +0000332 UFE->Name = InterndFileName;
Douglas Gregor407e2122009-12-02 18:12:28 +0000333 UFE->Size = Size;
334 UFE->ModTime = ModificationTime;
335 UFE->Dir = DirInfo;
336 UFE->UID = NextFileUID++;
Erik Verbruggendfffaf52017-03-28 09:18:05 +0000337 UFE->IsValid = true;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000338 UFE->File.reset();
Douglas Gregor407e2122009-12-02 18:12:28 +0000339 return UFE;
340}
341
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +0000342bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000343 StringRef pathRef(path.data(), path.size());
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000344
Fangrui Song6907ce22018-07-30 19:24:48 +0000345 if (FileSystemOpts.WorkingDir.empty()
Anders Carlsson9ba8fb12011-03-14 01:13:54 +0000346 || llvm::sys::path::is_absolute(pathRef))
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +0000347 return false;
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000348
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000349 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000350 llvm::sys::path::append(NewPath, pathRef);
Chris Lattner6e640992010-11-23 04:45:28 +0000351 path = NewPath;
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +0000352 return true;
353}
354
355bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
356 bool Changed = FixupRelativePath(Path);
357
358 if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
Ilya Biryukov47035c02017-08-02 07:25:24 +0000359 FS->makeAbsolute(Path);
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +0000360 Changed = true;
361 }
362
363 return Changed;
Chris Lattner6e640992010-11-23 04:45:28 +0000364}
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000365
Kadir Cetinkayae9870c02018-11-30 17:10:11 +0000366void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
367 llvm::SmallString<128> AbsPath(FileName);
368 // This is not the same as `VFS::getRealPath()`, which resolves symlinks
369 // but can be very expensive on real file systems.
370 // FIXME: the semantic of RealPathName is unclear, and the name might be
371 // misleading. We need to clean up the interface here.
372 makeAbsolutePath(AbsPath);
373 llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
374 UFE->RealPathName = AbsPath.str();
375}
376
Benjamin Kramera8857962014-10-26 22:44:13 +0000377llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
378FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
379 bool ShouldCloseOpenFile) {
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000380 uint64_t FileSize = Entry->getSize();
381 // If there's a high enough chance that the file have changed since we
382 // got its size, force a stat before opening it.
383 if (isVolatile)
384 FileSize = -1;
385
Mehdi Amini004b9c72016-10-10 22:52:47 +0000386 StringRef Filename = Entry->getName();
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44 +0000387 // If the file is already open, use the open file descriptor.
Ben Langmuirc8130a72014-02-20 21:59:23 +0000388 if (Entry->File) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000389 auto Result =
390 Entry->File->getBuffer(Filename, FileSize,
391 /*RequiresNullTerminator=*/true, isVolatile);
Ben Langmuir9801b252014-06-20 00:24:56 +0000392 // FIXME: we need a set of APIs that can make guarantees about whether a
393 // FileEntry is open or not.
394 if (ShouldCloseOpenFile)
395 Entry->closeFile();
Rafael Espindola6406f7b2014-08-26 19:54:40 +0000396 return Result;
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44 +0000397 }
398
399 // Otherwise, open the file.
400
Benjamin Kramera8857962014-10-26 22:44:13 +0000401 if (FileSystemOpts.WorkingDir.empty())
402 return FS->getBufferForFile(Filename, FileSize,
403 /*RequiresNullTerminator=*/true, isVolatile);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000404
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000405 SmallString<128> FilePath(Entry->getName());
Anders Carlsson878b3e22011-03-07 01:28:33 +0000406 FixupRelativePath(FilePath);
Yaron Keren92e1b622015-03-18 10:17:07 +0000407 return FS->getBufferForFile(FilePath, FileSize,
Benjamin Kramera8857962014-10-26 22:44:13 +0000408 /*RequiresNullTerminator=*/true, isVolatile);
Chris Lattner26b5c192010-11-23 09:19:42 +0000409}
410
Benjamin Kramera8857962014-10-26 22:44:13 +0000411llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +0000412FileManager::getBufferForFile(StringRef Filename, bool isVolatile) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000413 if (FileSystemOpts.WorkingDir.empty())
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +0000414 return FS->getBufferForFile(Filename, -1, true, isVolatile);
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000415
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000416 SmallString<128> FilePath(Filename);
Anders Carlsson878b3e22011-03-07 01:28:33 +0000417 FixupRelativePath(FilePath);
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +0000418 return FS->getBufferForFile(FilePath.c_str(), -1, true, isVolatile);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000419}
420
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000421/// getStatValue - Get the 'stat' information for the specified path,
422/// using the cache to accelerate it if possible. This returns true
423/// if the path points to a virtual file or does not exist, or returns
424/// false if it's an existent real file. If FileDescriptor is NULL,
425/// do directory look-up instead of file look-up.
Harlan Haskins06f64d52019-03-05 02:27:12 +0000426bool FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
427 bool isFile,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000428 std::unique_ptr<llvm::vfs::File> *F) {
Chris Lattner226efd32010-11-23 19:19:34 +0000429 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
430 // absolute!
Chris Lattner5769c3d2010-11-23 19:56:39 +0000431 if (FileSystemOpts.WorkingDir.empty())
Harlan Haskins06f64d52019-03-05 02:27:12 +0000432 return FileSystemStatCache::get(Path, Status, isFile, F,StatCache.get(), *FS);
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000433
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000434 SmallString<128> FilePath(Path);
Anders Carlsson878b3e22011-03-07 01:28:33 +0000435 FixupRelativePath(FilePath);
Chris Lattner5769c3d2010-11-23 19:56:39 +0000436
Harlan Haskins06f64d52019-03-05 02:27:12 +0000437 return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
Ben Langmuirc8130a72014-02-20 21:59:23 +0000438 StatCache.get(), *FS);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000439}
440
Rafael Espindolae4777f42013-07-29 18:22:23 +0000441bool FileManager::getNoncachedStatValue(StringRef Path,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000442 llvm::vfs::Status &Result) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000443 SmallString<128> FilePath(Path);
Anders Carlsson5e368402011-03-18 19:23:19 +0000444 FixupRelativePath(FilePath);
445
Jonas Devliegherefc514902018-10-10 13:27:25 +0000446 llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000447 if (!S)
448 return true;
449 Result = *S;
450 return false;
Anders Carlsson5e368402011-03-18 19:23:19 +0000451}
452
Axel Naumannb3074002012-07-10 16:50:27 +0000453void FileManager::invalidateCache(const FileEntry *Entry) {
454 assert(Entry && "Cannot invalidate a NULL FileEntry");
Axel Naumann38179d92012-06-27 09:17:42 +0000455
456 SeenFileEntries.erase(Entry->getName());
Axel Naumannb3074002012-07-10 16:50:27 +0000457
458 // FileEntry invalidation should not block future optimizations in the file
459 // caches. Possible alternatives are cache truncation (invalidate last N) or
460 // invalidation of the whole cache.
Richard Smith018ab5f2019-01-30 02:23:34 +0000461 //
462 // FIXME: This is broken. We sometimes have the same FileEntry* shared
463 // betweeen multiple SeenFileEntries, so this can leave dangling pointers.
Ben Langmuirc9b72342014-02-27 22:21:32 +0000464 UniqueRealFiles.erase(Entry->getUniqueID());
Axel Naumann38179d92012-06-27 09:17:42 +0000465}
466
Douglas Gregor09b69892011-02-10 17:09:37 +0000467void FileManager::GetUniqueIDMapping(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000468 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
Douglas Gregor09b69892011-02-10 17:09:37 +0000469 UIDToFiles.clear();
470 UIDToFiles.resize(NextFileUID);
Fangrui Song6907ce22018-07-30 19:24:48 +0000471
Douglas Gregor09b69892011-02-10 17:09:37 +0000472 // Map file entries
473 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000474 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
Douglas Gregor09b69892011-02-10 17:09:37 +0000475 FE != FEEnd; ++FE)
Richard Smith018ab5f2019-01-30 02:23:34 +0000476 if (FE->getValue())
Douglas Gregor09b69892011-02-10 17:09:37 +0000477 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000478
Douglas Gregor09b69892011-02-10 17:09:37 +0000479 // Map virtual file entries
David Blaikied2725a32015-12-09 17:23:13 +0000480 for (const auto &VFE : VirtualFileEntries)
Richard Smith018ab5f2019-01-30 02:23:34 +0000481 UIDToFiles[VFE->getUID()] = VFE.get();
Douglas Gregor09b69892011-02-10 17:09:37 +0000482}
Chris Lattner226efd32010-11-23 19:19:34 +0000483
Argyrios Kyrtzidis6eec06d2012-05-03 21:50:39 +0000484void FileManager::modifyFileEntry(FileEntry *File,
485 off_t Size, time_t ModificationTime) {
486 File->Size = Size;
487 File->ModTime = ModificationTime;
488}
489
Douglas Gregore00c8b22013-01-26 00:55:12 +0000490StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
491 // FIXME: use llvm::sys::fs::canonical() when it gets implemented
Douglas Gregore00c8b22013-01-26 00:55:12 +0000492 llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
493 = CanonicalDirNames.find(Dir);
494 if (Known != CanonicalDirNames.end())
495 return Known->second;
496
497 StringRef CanonicalName(Dir->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +0000498
Eric Liu5fb18fe2018-05-17 10:26:23 +0000499 SmallString<4096> CanonicalNameBuf;
500 if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
Benjamin Kramerda4690a2015-08-04 11:27:08 +0000501 CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
Douglas Gregore00c8b22013-01-26 00:55:12 +0000502
Richard Smith018ab5f2019-01-30 02:23:34 +0000503 CanonicalDirNames.insert({Dir, CanonicalName});
Douglas Gregore00c8b22013-01-26 00:55:12 +0000504 return CanonicalName;
Douglas Gregore00c8b22013-01-26 00:55:12 +0000505}
Chris Lattner226efd32010-11-23 19:19:34 +0000506
Chris Lattner22eb9722006-06-18 05:43:12 +0000507void FileManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000508 llvm::errs() << "\n*** File Manager Stats:\n";
Zhanyong Wane1dd3e22011-02-11 18:44:49 +0000509 llvm::errs() << UniqueRealFiles.size() << " real files found, "
510 << UniqueRealDirs.size() << " real dirs found.\n";
511 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
512 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000513 llvm::errs() << NumDirLookups << " dir lookups, "
514 << NumDirCacheMisses << " dir cache misses.\n";
515 llvm::errs() << NumFileLookups << " file lookups, "
516 << NumFileCacheMisses << " file cache misses.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000517
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000518 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
Chris Lattner22eb9722006-06-18 05:43:12 +0000519}