blob: e4d019aedb7c2d781550edddcedce188c47af5aa [file] [log] [blame]
Chris Lattner226efd32010-11-23 19:19:341//===--- FileManager.cpp - File System Probing and Caching ----------------===//
Chris Lattner22eb9722006-06-18 05:43:122//
Chandler Carruth2946cd72019-01-19 08:50:563// 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:126//
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:3420#include "clang/Basic/FileSystemStatCache.h"
David Blaikied2725a32015-12-09 17:23:1321#include "llvm/ADT/STLExtras.h"
Volodymyr Sapsaie8752a92019-10-11 18:22:3422#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Config/llvm-config.h"
Michael J. Spencer740857f2010-12-21 16:45:5725#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidis71731d62010-11-03 22:45:2326#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:3927#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:3328#include "llvm/Support/raw_ostream.h"
Eugene Zelenko35b79c22016-08-13 01:05:3529#include <algorithm>
30#include <cassert>
31#include <climits>
32#include <cstdint>
33#include <cstdlib>
Benjamin Kramer26db6482009-09-05 09:49:3934#include <string>
Eugene Zelenko35b79c22016-08-13 01:05:3535#include <utility>
Chris Lattner278038b2010-11-23 21:53:1536
Chris Lattner22eb9722006-06-18 05:43:1237using namespace clang;
38
Volodymyr Sapsaie8752a92019-10-11 18:22:3439#define DEBUG_TYPE "file-search"
40
41ALWAYS_ENABLED_STATISTIC(NumDirLookups, "Number of directory lookups.");
42ALWAYS_ENABLED_STATISTIC(NumFileLookups, "Number of file lookups.");
43ALWAYS_ENABLED_STATISTIC(NumDirCacheMisses,
44 "Number of directory cache misses.");
45ALWAYS_ENABLED_STATISTIC(NumFileCacheMisses, "Number of file cache misses.");
46
Ted Kremenek5c04bd82009-01-28 00:27:3147//===----------------------------------------------------------------------===//
48// Common logic.
49//===----------------------------------------------------------------------===//
Ted Kremenekd87eef82008-02-24 03:15:2550
Ben Langmuirc8130a72014-02-20 21:59:2351FileManager::FileManager(const FileSystemOptions &FSO,
Jonas Devliegherefc514902018-10-10 13:27:2552 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
Benjamin Kramerf6021ec2017-03-21 21:35:0453 : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
54 SeenFileEntries(64), NextFileUID(0) {
Ben Langmuirc8130a72014-02-20 21:59:2355 // If the caller doesn't provide a virtual file system, just grab the real
56 // file system.
Benjamin Kramerf6021ec2017-03-21 21:35:0457 if (!this->FS)
Jonas Devliegherefc514902018-10-10 13:27:2558 this->FS = llvm::vfs::getRealFileSystem();
Ted Kremenekd87eef82008-02-24 03:15:2559}
60
David Blaikied2725a32015-12-09 17:23:1361FileManager::~FileManager() = default;
Ted Kremenekd87eef82008-02-24 03:15:2562
Alex Lorenzd92b1ae2018-12-21 19:33:0963void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
Douglas Gregord2eb58a2009-10-16 18:18:3064 assert(statCache && "No stat cache provided?");
Alex Lorenzd92b1ae2018-12-21 19:33:0965 StatCache = std::move(statCache);
Douglas Gregord2eb58a2009-10-16 18:18:3066}
67
Alex Lorenzd92b1ae2018-12-21 19:33:0968void FileManager::clearStatCache() { StatCache.reset(); }
Manuel Klimek3aad8552012-07-31 13:56:5469
Adrian Prantl9fc8faf2018-05-09 01:00:0170/// Retrieve the directory that the given file name resides in.
Zhanyong Wane1dd3e22011-02-11 18:44:4971/// Filename can point to either a real file or a virtual file.
Harlan Haskins461f0722019-08-01 21:31:4972static llvm::ErrorOr<const DirectoryEntry *>
73getDirectoryFromFile(FileManager &FileMgr, StringRef Filename,
74 bool CacheFailure) {
Zhanyong Wanf3c0ff72011-02-11 21:25:3575 if (Filename.empty())
Harlan Haskins461f0722019-08-01 21:31:4976 return std::errc::no_such_file_or_directory;
Zhanyong Wane1dd3e22011-02-11 18:44:4977
Zhanyong Wanf3c0ff72011-02-11 21:25:3578 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
Harlan Haskins461f0722019-08-01 21:31:4979 return std::errc::is_a_directory;
Benjamin Kramer3cf715d2010-11-21 11:32:2280
Chris Lattner0e62c1c2011-07-23 10:55:1581 StringRef DirName = llvm::sys::path::parent_path(Filename);
Chris Lattner0c0e8042010-11-21 09:50:1682 // Use the current directory if file has no path component.
Zhanyong Wanf3c0ff72011-02-11 21:25:3583 if (DirName.empty())
84 DirName = ".";
Douglas Gregor407e2122009-12-02 18:12:2885
Douglas Gregor1735f4e2011-09-13 23:15:4586 return FileMgr.getDirectory(DirName, CacheFailure);
Douglas Gregor407e2122009-12-02 18:12:2887}
88
Zhanyong Wane1dd3e22011-02-11 18:44:4989/// Add all ancestors of the given path (pointing to either a file or
90/// a directory) as virtual directories.
Chris Lattner0e62c1c2011-07-23 10:55:1591void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
92 StringRef DirName = llvm::sys::path::parent_path(Path);
Zhanyong Wanf3c0ff72011-02-11 21:25:3593 if (DirName.empty())
David Majnemer1834dc72016-04-12 16:33:5394 DirName = ".";
Zhanyong Wane1dd3e22011-02-11 18:44:4995
Harlan Haskins461f0722019-08-01 21:31:4996 auto &NamedDirEnt = *SeenDirEntries.insert(
97 {DirName, std::errc::no_such_file_or_directory}).first;
Zhanyong Wane1dd3e22011-02-11 18:44:4998
99 // When caching a virtual directory, we always cache its ancestors
100 // at the same time. Therefore, if DirName is already in the cache,
101 // we don't need to recurse as its ancestors must also already be in
Richard Smith018ab5f2019-01-30 02:23:34102 // the cache (or it's a known non-virtual directory).
103 if (NamedDirEnt.second)
Zhanyong Wane1dd3e22011-02-11 18:44:49104 return;
105
106 // Add the virtual directory to the cache.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18107 auto UDE = std::make_unique<DirectoryEntry>();
Mehdi Amini0df59d82016-10-11 07:31:29108 UDE->Name = NamedDirEnt.first();
Harlan Haskins461f0722019-08-01 21:31:49109 NamedDirEnt.second = *UDE.get();
David Blaikied2725a32015-12-09 17:23:13110 VirtualDirectoryEntries.push_back(std::move(UDE));
Zhanyong Wane1dd3e22011-02-11 18:44:49111
112 // Recursively add the other ancestors.
113 addAncestorsAsVirtualDirs(DirName);
114}
115
Alex Lorenz0377ca62019-08-31 01:26:04116llvm::Expected<DirectoryEntryRef>
117FileManager::getDirectoryRef(StringRef DirName, bool CacheFailure) {
NAKAMURA Takumi8bd8ee72012-06-16 06:04:10118 // stat doesn't like trailing separators except for root directory.
NAKAMURA Takumi32f1acf2011-11-17 06:16:05119 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
120 // (though it can strip '\\')
NAKAMURA Takumi8bd8ee72012-06-16 06:04:10121 if (DirName.size() > 1 &&
122 DirName != llvm::sys::path::root_path(DirName) &&
123 llvm::sys::path::is_separator(DirName.back()))
NAKAMURA Takumi32f1acf2011-11-17 06:16:05124 DirName = DirName.substr(0, DirName.size()-1);
Nico Weber1865df42018-04-27 19:11:14125#ifdef _WIN32
Rafael Espindolaee305462013-07-29 15:47:24126 // Fixing a problem with "clang C:test.c" on Windows.
127 // Stat("C:") does not recognize "C:" as a valid directory
128 std::string DirNameStr;
129 if (DirName.size() > 1 && DirName.back() == ':' &&
130 DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
131 DirNameStr = DirName.str() + '.';
132 DirName = DirNameStr;
133 }
134#endif
NAKAMURA Takumi32f1acf2011-11-17 06:16:05135
Chris Lattner22eb9722006-06-18 05:43:12136 ++NumDirLookups;
Mike Stump11289f42009-09-09 15:08:12137
Zhanyong Wane1dd3e22011-02-11 18:44:49138 // See if there was already an entry in the map. Note that the map
139 // contains both virtual and real directories.
Harlan Haskins461f0722019-08-01 21:31:49140 auto SeenDirInsertResult =
141 SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory});
Alex Lorenz0377ca62019-08-31 01:26:04142 if (!SeenDirInsertResult.second) {
143 if (SeenDirInsertResult.first->second)
144 return DirectoryEntryRef(&*SeenDirInsertResult.first);
145 return llvm::errorCodeToError(SeenDirInsertResult.first->second.getError());
146 }
Mike Stump11289f42009-09-09 15:08:12147
Richard Smith018ab5f2019-01-30 02:23:34148 // We've not seen this before. Fill it in.
Chris Lattner22eb9722006-06-18 05:43:12149 ++NumDirCacheMisses;
Richard Smith018ab5f2019-01-30 02:23:34150 auto &NamedDirEnt = *SeenDirInsertResult.first;
151 assert(!NamedDirEnt.second && "should be newly-created");
Mike Stump11289f42009-09-09 15:08:12152
Chris Lattner43fd42e2006-10-30 03:40:58153 // Get the null-terminated directory name as stored as the key of the
Zhanyong Wane1dd3e22011-02-11 18:44:49154 // SeenDirEntries map.
Mehdi Amini0df59d82016-10-11 07:31:29155 StringRef InterndDirName = NamedDirEnt.first();
Mike Stump11289f42009-09-09 15:08:12156
Chris Lattneraf653752006-10-30 03:06:54157 // Check to see if the directory exists.
Harlan Haskins06f64d52019-03-05 02:27:12158 llvm::vfs::Status Status;
Harlan Haskins461f0722019-08-01 21:31:49159 auto statError = getStatValue(InterndDirName, Status, false,
160 nullptr /*directory lookup*/);
161 if (statError) {
Zhanyong Wane1dd3e22011-02-11 18:44:49162 // There's no real directory at the given path.
Harlan Haskins461f0722019-08-01 21:31:49163 if (CacheFailure)
164 NamedDirEnt.second = statError;
165 else
Douglas Gregor1735f4e2011-09-13 23:15:45166 SeenDirEntries.erase(DirName);
Alex Lorenz0377ca62019-08-31 01:26:04167 return llvm::errorCodeToError(statError);
Zhanyong Wane1dd3e22011-02-11 18:44:49168 }
Ted Kremenekd87eef82008-02-24 03:15:25169
Zhanyong Wane1dd3e22011-02-11 18:44:49170 // It exists. See if we have already opened a directory with the
171 // same inode (this occurs on Unix-like systems when one dir is
172 // symlinked to another, for example) or the same path (on
173 // Windows).
Harlan Haskins06f64d52019-03-05 02:27:12174 DirectoryEntry &UDE = UniqueRealDirs[Status.getUniqueID()];
Mike Stump11289f42009-09-09 15:08:12175
Harlan Haskins461f0722019-08-01 21:31:49176 NamedDirEnt.second = UDE;
Mehdi Amini0df59d82016-10-11 07:31:29177 if (UDE.getName().empty()) {
Zhanyong Wane1dd3e22011-02-11 18:44:49178 // We don't have this directory yet, add it. We use the string
179 // key from the SeenDirEntries map as the string.
180 UDE.Name = InterndDirName;
181 }
Mike Stump11289f42009-09-09 15:08:12182
Alex Lorenz0377ca62019-08-31 01:26:04183 return DirectoryEntryRef(&NamedDirEnt);
184}
185
186llvm::ErrorOr<const DirectoryEntry *>
187FileManager::getDirectory(StringRef DirName, bool CacheFailure) {
188 auto Result = getDirectoryRef(DirName, CacheFailure);
189 if (Result)
190 return &Result->getDirEntry();
191 return llvm::errorToErrorCode(Result.takeError());
Chris Lattner22eb9722006-06-18 05:43:12192}
193
Harlan Haskins461f0722019-08-01 21:31:49194llvm::ErrorOr<const FileEntry *>
195FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) {
Alex Lorenz4dc55732019-08-22 18:15:50196 auto Result = getFileRef(Filename, openFile, CacheFailure);
197 if (Result)
198 return &Result->getFileEntry();
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51199 return llvm::errorToErrorCode(Result.takeError());
Alex Lorenz4dc55732019-08-22 18:15:50200}
201
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51202llvm::Expected<FileEntryRef>
Alex Lorenz4dc55732019-08-22 18:15:50203FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) {
Chris Lattner22eb9722006-06-18 05:43:12204 ++NumFileLookups;
Mike Stump11289f42009-09-09 15:08:12205
Chris Lattner22eb9722006-06-18 05:43:12206 // See if there is already an entry in the map.
Harlan Haskins461f0722019-08-01 21:31:49207 auto SeenFileInsertResult =
208 SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
Alex Lorenz4dc55732019-08-22 18:15:50209 if (!SeenFileInsertResult.second) {
210 if (!SeenFileInsertResult.first->second)
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51211 return llvm::errorCodeToError(
212 SeenFileInsertResult.first->second.getError());
Alex Lorenz4dc55732019-08-22 18:15:50213 // Construct and return and FileEntryRef, unless it's a redirect to another
214 // filename.
215 SeenFileEntryOrRedirect Value = *SeenFileInsertResult.first->second;
216 FileEntry *FE;
217 if (LLVM_LIKELY(FE = Value.dyn_cast<FileEntry *>()))
218 return FileEntryRef(SeenFileInsertResult.first->first(), *FE);
219 return getFileRef(*Value.get<const StringRef *>(), openFile, CacheFailure);
220 }
Chris Lattner22eb9722006-06-18 05:43:12221
Richard Smith018ab5f2019-01-30 02:23:34222 // We've not seen this before. Fill it in.
Chris Lattner22eb9722006-06-18 05:43:12223 ++NumFileCacheMisses;
Alex Suhanb3144142019-11-08 21:37:13224 auto *NamedFileEnt = &*SeenFileInsertResult.first;
225 assert(!NamedFileEnt->second && "should be newly-created");
Sam McCallfa361202019-01-24 18:55:24226
Chris Lattner2f4a89a2006-10-30 03:55:17227 // Get the null-terminated file name as stored as the key of the
Zhanyong Wane1dd3e22011-02-11 18:44:49228 // SeenFileEntries map.
Alex Suhanb3144142019-11-08 21:37:13229 StringRef InterndFileName = NamedFileEnt->first();
Mike Stump11289f42009-09-09 15:08:12230
Chris Lattner966b25b2010-11-23 20:30:42231 // Look up the directory for the file. When looking up something like
232 // sys/foo.h we'll discover all of the search directories that have a 'sys'
233 // subdirectory. This will let us avoid having to waste time on known-to-fail
234 // searches when we go to find sys/bar.h, because all the search directories
235 // without a 'sys' subdir will get a cached failure result.
Harlan Haskins461f0722019-08-01 21:31:49236 auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure);
237 if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist.
238 if (CacheFailure)
Alex Suhanb3144142019-11-08 21:37:13239 NamedFileEnt->second = DirInfoOrErr.getError();
Harlan Haskins461f0722019-08-01 21:31:49240 else
Douglas Gregor1735f4e2011-09-13 23:15:45241 SeenFileEntries.erase(Filename);
Craig Topperf1186c52014-05-08 06:41:40242
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51243 return llvm::errorCodeToError(DirInfoOrErr.getError());
Douglas Gregor1735f4e2011-09-13 23:15:45244 }
Harlan Haskins461f0722019-08-01 21:31:49245 const DirectoryEntry *DirInfo = *DirInfoOrErr;
Fangrui Song6907ce22018-07-30 19:24:48246
Chris Lattner22eb9722006-06-18 05:43:12247 // FIXME: Use the directory info to prune this, before doing the stat syscall.
248 // FIXME: This will reduce the # syscalls.
Mike Stump11289f42009-09-09 15:08:12249
Richard Smith018ab5f2019-01-30 02:23:34250 // Check to see if the file exists.
Jonas Devliegherefc514902018-10-10 13:27:25251 std::unique_ptr<llvm::vfs::File> F;
Harlan Haskins06f64d52019-03-05 02:27:12252 llvm::vfs::Status Status;
Harlan Haskins461f0722019-08-01 21:31:49253 auto statError = getStatValue(InterndFileName, Status, true,
254 openFile ? &F : nullptr);
255 if (statError) {
Zhanyong Wane1dd3e22011-02-11 18:44:49256 // There's no real file at the given path.
Harlan Haskins461f0722019-08-01 21:31:49257 if (CacheFailure)
Alex Suhanb3144142019-11-08 21:37:13258 NamedFileEnt->second = statError;
Harlan Haskins461f0722019-08-01 21:31:49259 else
Douglas Gregor1735f4e2011-09-13 23:15:45260 SeenFileEntries.erase(Filename);
Craig Topperf1186c52014-05-08 06:41:40261
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51262 return llvm::errorCodeToError(statError);
Zhanyong Wane1dd3e22011-02-11 18:44:49263 }
Mike Stump11289f42009-09-09 15:08:12264
Patrik Hagglundab01d4b2014-02-21 07:23:53265 assert((openFile || !F) && "undesired open file");
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25266
Ted Kremenekf4c38c92007-12-18 22:29:39267 // It exists. See if we have already opened a file with the same inode.
Chris Lattner22eb9722006-06-18 05:43:12268 // This occurs when one dir is symlinked to another, for example.
Harlan Haskins06f64d52019-03-05 02:27:12269 FileEntry &UFE = UniqueRealFiles[Status.getUniqueID()];
Mike Stump11289f42009-09-09 15:08:12270
Alex Suhanb3144142019-11-08 21:37:13271 NamedFileEnt->second = &UFE;
Ben Langmuirab86fbe2014-09-08 16:15:54272
273 // If the name returned by getStatValue is different than Filename, re-intern
274 // the name.
Harlan Haskins06f64d52019-03-05 02:27:12275 if (Status.getName() != Filename) {
Richard Smith98f9e942019-08-26 17:31:06276 auto &NewNamedFileEnt =
Alex Lorenz4dc55732019-08-22 18:15:50277 *SeenFileEntries.insert({Status.getName(), &UFE}).first;
Richard Smith98f9e942019-08-26 17:31:06278 assert((*NewNamedFileEnt.second).get<FileEntry *>() == &UFE &&
Richard Smith018ab5f2019-01-30 02:23:34279 "filename from getStatValue() refers to wrong file");
Richard Smith98f9e942019-08-26 17:31:06280 InterndFileName = NewNamedFileEnt.first().data();
Alex Lorenz4dc55732019-08-22 18:15:50281 // In addition to re-interning the name, construct a redirecting seen file
282 // entry, that will point to the name the filesystem actually wants to use.
283 StringRef *Redirect = new (CanonicalNameStorage) StringRef(InterndFileName);
Alex Suhanb3144142019-11-08 21:37:13284 auto SeenFileInsertResultIt = SeenFileEntries.find(Filename);
285 assert(SeenFileInsertResultIt != SeenFileEntries.end() &&
286 "unexpected SeenFileEntries cache miss");
287 SeenFileInsertResultIt->second = Redirect;
288 NamedFileEnt = &*SeenFileInsertResultIt;
Ben Langmuirab86fbe2014-09-08 16:15:54289 }
290
Ben Langmuirc8a71462014-02-27 17:23:33291 if (UFE.isValid()) { // Already have an entry with this inode, return it.
Ben Langmuir5de00f32014-05-23 18:15:47292
293 // FIXME: this hack ensures that if we look up a file by a virtual path in
294 // the VFS that the getDir() will have the virtual path, even if we found
295 // the file by a 'real' path first. This is required in order to find a
296 // module's structure when its headers/module map are mapped in the VFS.
297 // We should remove this as soon as we can properly support a file having
298 // multiple names.
Harlan Haskins06f64d52019-03-05 02:27:12299 if (DirInfo != UFE.Dir && Status.IsVFSMapped)
Ben Langmuir5de00f32014-05-23 18:15:47300 UFE.Dir = DirInfo;
301
Manuel Klimekc0ff9902014-08-13 12:34:41302 // Always update the name to use the last name by which a file was accessed.
303 // FIXME: Neither this nor always using the first name is correct; we want
304 // to switch towards a design where we return a FileName object that
305 // encapsulates both the name by which the file was accessed and the
306 // corresponding FileEntry.
Alex Lorenz4dc55732019-08-22 18:15:50307 // FIXME: The Name should be removed from FileEntry once all clients
308 // adopt FileEntryRef.
Ben Langmuirab86fbe2014-09-08 16:15:54309 UFE.Name = InterndFileName;
Manuel Klimekc0ff9902014-08-13 12:34:41310
Alex Lorenz4dc55732019-08-22 18:15:50311 return FileEntryRef(InterndFileName, UFE);
Chris Lattnerdd278432010-11-23 21:17:56312 }
Chris Lattner269c2322006-06-25 06:23:00313
Ben Langmuirc9b72342014-02-27 22:21:32314 // Otherwise, we don't have this file yet, add it.
Ben Langmuirab86fbe2014-09-08 16:15:54315 UFE.Name = InterndFileName;
Harlan Haskins06f64d52019-03-05 02:27:12316 UFE.Size = Status.getSize();
317 UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
Chris Lattner2f4a89a2006-10-30 03:55:17318 UFE.Dir = DirInfo;
319 UFE.UID = NextFileUID++;
Harlan Haskins06f64d52019-03-05 02:27:12320 UFE.UniqueID = Status.getUniqueID();
321 UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
Sam McCallfa361202019-01-24 18:55:24322 UFE.File = std::move(F);
Ben Langmuirc8a71462014-02-27 17:23:33323 UFE.IsValid = true;
Simon Marchiddbabc62018-08-06 21:48:20324
Sam McCallfa361202019-01-24 18:55:24325 if (UFE.File) {
326 if (auto PathName = UFE.File->getName())
327 fillRealPathName(&UFE, *PathName);
Jan Korouscd8607d2019-02-18 22:33:40328 } else if (!openFile) {
329 // We should still fill the path even if we aren't opening the file.
330 fillRealPathName(&UFE, InterndFileName);
Sam McCallfa361202019-01-24 18:55:24331 }
Alex Lorenz4dc55732019-08-22 18:15:50332 return FileEntryRef(InterndFileName, UFE);
Chris Lattner22eb9722006-06-18 05:43:12333}
334
Douglas Gregor407e2122009-12-02 18:12:28335const FileEntry *
Chris Lattner0e62c1c2011-07-23 10:55:15336FileManager::getVirtualFile(StringRef Filename, off_t Size,
Chris Lattner5159f612010-11-23 08:35:12337 time_t ModificationTime) {
Douglas Gregor407e2122009-12-02 18:12:28338 ++NumFileLookups;
339
Richard Smith018ab5f2019-01-30 02:23:34340 // See if there is already an entry in the map for an existing file.
Harlan Haskins461f0722019-08-01 21:31:49341 auto &NamedFileEnt = *SeenFileEntries.insert(
342 {Filename, std::errc::no_such_file_or_directory}).first;
Alex Lorenz4dc55732019-08-22 18:15:50343 if (NamedFileEnt.second) {
344 SeenFileEntryOrRedirect Value = *NamedFileEnt.second;
345 FileEntry *FE;
346 if (LLVM_LIKELY(FE = Value.dyn_cast<FileEntry *>()))
347 return FE;
348 return getVirtualFile(*Value.get<const StringRef *>(), Size,
349 ModificationTime);
350 }
Douglas Gregor407e2122009-12-02 18:12:28351
Richard Smith018ab5f2019-01-30 02:23:34352 // We've not seen this before, or the file is cached as non-existent.
Douglas Gregor407e2122009-12-02 18:12:28353 ++NumFileCacheMisses;
Zhanyong Wane1dd3e22011-02-11 18:44:49354 addAncestorsAsVirtualDirs(Filename);
Craig Topperf1186c52014-05-08 06:41:40355 FileEntry *UFE = nullptr;
Zhanyong Wane1dd3e22011-02-11 18:44:49356
357 // Now that all ancestors of Filename are in the cache, the
358 // following call is guaranteed to find the DirectoryEntry from the
359 // cache.
Harlan Haskins461f0722019-08-01 21:31:49360 auto DirInfo = getDirectoryFromFile(*this, Filename, /*CacheFailure=*/true);
Zhanyong Wane1dd3e22011-02-11 18:44:49361 assert(DirInfo &&
362 "The directory of a virtual file should already be in the cache.");
Douglas Gregor407e2122009-12-02 18:12:28363
Zhanyong Wane1dd3e22011-02-11 18:44:49364 // Check to see if the file exists. If so, drop the virtual file
Harlan Haskins06f64d52019-03-05 02:27:12365 llvm::vfs::Status Status;
David Blaikie13156b62014-11-19 03:06:06366 const char *InterndFileName = NamedFileEnt.first().data();
Harlan Haskins461f0722019-08-01 21:31:49367 if (!getStatValue(InterndFileName, Status, true, nullptr)) {
Harlan Haskins06f64d52019-03-05 02:27:12368 UFE = &UniqueRealFiles[Status.getUniqueID()];
369 Status = llvm::vfs::Status(
370 Status.getName(), Status.getUniqueID(),
371 llvm::sys::toTimePoint(ModificationTime),
372 Status.getUser(), Status.getGroup(), Size,
373 Status.getType(), Status.getPermissions());
Douglas Gregor606c4ac2011-02-05 19:42:43374
Alex Lorenz4dc55732019-08-22 18:15:50375 NamedFileEnt.second = UFE;
Douglas Gregor606c4ac2011-02-05 19:42:43376
Zhanyong Wane1dd3e22011-02-11 18:44:49377 // If we had already opened this file, close it now so we don't
378 // leak the descriptor. We're not going to use the file
379 // descriptor anyway, since this is a virtual file.
Ben Langmuirc8130a72014-02-20 21:59:23380 if (UFE->File)
381 UFE->closeFile();
Zhanyong Wane1dd3e22011-02-11 18:44:49382
383 // If we already have an entry with this inode, return it.
Ben Langmuirc8a71462014-02-27 17:23:33384 if (UFE->isValid())
Zhanyong Wane1dd3e22011-02-11 18:44:49385 return UFE;
Ben Langmuirc9b72342014-02-27 22:21:32386
Harlan Haskins06f64d52019-03-05 02:27:12387 UFE->UniqueID = Status.getUniqueID();
388 UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
389 fillRealPathName(UFE, Status.getName());
Richard Smith018ab5f2019-01-30 02:23:34390 } else {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18391 VirtualFileEntries.push_back(std::make_unique<FileEntry>());
David Blaikied2725a32015-12-09 17:23:13392 UFE = VirtualFileEntries.back().get();
Alex Lorenz4dc55732019-08-22 18:15:50393 NamedFileEnt.second = UFE;
Douglas Gregor606c4ac2011-02-05 19:42:43394 }
Douglas Gregor407e2122009-12-02 18:12:28395
Chris Lattner9624b692010-11-23 20:50:22396 UFE->Name = InterndFileName;
Douglas Gregor407e2122009-12-02 18:12:28397 UFE->Size = Size;
398 UFE->ModTime = ModificationTime;
Harlan Haskins461f0722019-08-01 21:31:49399 UFE->Dir = *DirInfo;
Douglas Gregor407e2122009-12-02 18:12:28400 UFE->UID = NextFileUID++;
Erik Verbruggendfffaf52017-03-28 09:18:05401 UFE->IsValid = true;
Ben Langmuirc8130a72014-02-20 21:59:23402 UFE->File.reset();
Douglas Gregor407e2122009-12-02 18:12:28403 return UFE;
404}
405
Duncan P. N. Exon Smithe1b7f222019-08-30 22:59:25406llvm::Optional<FileEntryRef> FileManager::getBypassFile(FileEntryRef VF) {
407 // Stat of the file and return nullptr if it doesn't exist.
408 llvm::vfs::Status Status;
409 if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr))
410 return None;
411
412 // Fill it in from the stat.
413 BypassFileEntries.push_back(std::make_unique<FileEntry>());
414 const FileEntry &VFE = VF.getFileEntry();
415 FileEntry &BFE = *BypassFileEntries.back();
416 BFE.Name = VFE.getName();
417 BFE.Size = Status.getSize();
418 BFE.Dir = VFE.Dir;
419 BFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
420 BFE.UID = NextFileUID++;
421 BFE.IsValid = true;
422 return FileEntryRef(VF.getName(), BFE);
423}
424
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32425bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
Chris Lattner0e62c1c2011-07-23 10:55:15426 StringRef pathRef(path.data(), path.size());
Anders Carlssonb5c356a2011-03-06 22:25:35427
Fangrui Song6907ce22018-07-30 19:24:48428 if (FileSystemOpts.WorkingDir.empty()
Anders Carlsson9ba8fb12011-03-14 01:13:54429 || llvm::sys::path::is_absolute(pathRef))
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32430 return false;
Michael J. Spencerf28df4c2010-12-17 21:22:22431
Dylan Noblesmith2c1dd272012-02-05 02:13:05432 SmallString<128> NewPath(FileSystemOpts.WorkingDir);
Anders Carlssonb5c356a2011-03-06 22:25:35433 llvm::sys::path::append(NewPath, pathRef);
Chris Lattner6e640992010-11-23 04:45:28434 path = NewPath;
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32435 return true;
436}
437
438bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
439 bool Changed = FixupRelativePath(Path);
440
441 if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
Ilya Biryukov47035c02017-08-02 07:25:24442 FS->makeAbsolute(Path);
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32443 Changed = true;
444 }
445
446 return Changed;
Chris Lattner6e640992010-11-23 04:45:28447}
Argyrios Kyrtzidis71731d62010-11-03 22:45:23448
Kadir Cetinkayae9870c02018-11-30 17:10:11449void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
450 llvm::SmallString<128> AbsPath(FileName);
451 // This is not the same as `VFS::getRealPath()`, which resolves symlinks
452 // but can be very expensive on real file systems.
453 // FIXME: the semantic of RealPathName is unclear, and the name might be
454 // misleading. We need to clean up the interface here.
455 makeAbsolutePath(AbsPath);
456 llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
Benjamin Krameradcd0262020-01-28 19:23:46457 UFE->RealPathName = std::string(AbsPath.str());
Kadir Cetinkayae9870c02018-11-30 17:10:11458}
459
Benjamin Kramera8857962014-10-26 22:44:13460llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Duncan P. N. Exon Smith122705b2019-08-30 16:56:26461FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile) {
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04462 uint64_t FileSize = Entry->getSize();
463 // If there's a high enough chance that the file have changed since we
464 // got its size, force a stat before opening it.
465 if (isVolatile)
466 FileSize = -1;
467
Mehdi Amini004b9c72016-10-10 22:52:47468 StringRef Filename = Entry->getName();
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44469 // If the file is already open, use the open file descriptor.
Ben Langmuirc8130a72014-02-20 21:59:23470 if (Entry->File) {
Benjamin Kramera8857962014-10-26 22:44:13471 auto Result =
472 Entry->File->getBuffer(Filename, FileSize,
473 /*RequiresNullTerminator=*/true, isVolatile);
Duncan P. N. Exon Smith122705b2019-08-30 16:56:26474 Entry->closeFile();
Rafael Espindola6406f7b2014-08-26 19:54:40475 return Result;
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44476 }
477
478 // Otherwise, open the file.
Duncan P. N. Exon Smith894b8d12019-08-25 01:18:35479 return getBufferForFileImpl(Filename, FileSize, isVolatile);
480}
Argyrios Kyrtzidis669b0b12011-03-15 00:47:44481
Duncan P. N. Exon Smith894b8d12019-08-25 01:18:35482llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
483FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
484 bool isVolatile) {
Benjamin Kramera8857962014-10-26 22:44:13485 if (FileSystemOpts.WorkingDir.empty())
486 return FS->getBufferForFile(Filename, FileSize,
487 /*RequiresNullTerminator=*/true, isVolatile);
Anders Carlssonb5c356a2011-03-06 22:25:35488
Duncan P. N. Exon Smith894b8d12019-08-25 01:18:35489 SmallString<128> FilePath(Filename);
Anders Carlsson878b3e22011-03-07 01:28:33490 FixupRelativePath(FilePath);
Yaron Keren92e1b622015-03-18 10:17:07491 return FS->getBufferForFile(FilePath, FileSize,
Benjamin Kramera8857962014-10-26 22:44:13492 /*RequiresNullTerminator=*/true, isVolatile);
Chris Lattner26b5c192010-11-23 09:19:42493}
494
Zhanyong Wane1dd3e22011-02-11 18:44:49495/// getStatValue - Get the 'stat' information for the specified path,
496/// using the cache to accelerate it if possible. This returns true
497/// if the path points to a virtual file or does not exist, or returns
498/// false if it's an existent real file. If FileDescriptor is NULL,
499/// do directory look-up instead of file look-up.
Harlan Haskins461f0722019-08-01 21:31:49500std::error_code
501FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
502 bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
Chris Lattner226efd32010-11-23 19:19:34503 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
504 // absolute!
Chris Lattner5769c3d2010-11-23 19:56:39505 if (FileSystemOpts.WorkingDir.empty())
Harlan Haskins461f0722019-08-01 21:31:49506 return FileSystemStatCache::get(Path, Status, isFile, F,
507 StatCache.get(), *FS);
Zhanyong Wane1dd3e22011-02-11 18:44:49508
Dylan Noblesmith2c1dd272012-02-05 02:13:05509 SmallString<128> FilePath(Path);
Anders Carlsson878b3e22011-03-07 01:28:33510 FixupRelativePath(FilePath);
Chris Lattner5769c3d2010-11-23 19:56:39511
Harlan Haskins461f0722019-08-01 21:31:49512 return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
513 StatCache.get(), *FS);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23514}
515
Harlan Haskins461f0722019-08-01 21:31:49516std::error_code
517FileManager::getNoncachedStatValue(StringRef Path,
518 llvm::vfs::Status &Result) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05519 SmallString<128> FilePath(Path);
Anders Carlsson5e368402011-03-18 19:23:19520 FixupRelativePath(FilePath);
521
Jonas Devliegherefc514902018-10-10 13:27:25522 llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
Ben Langmuirc8130a72014-02-20 21:59:23523 if (!S)
Harlan Haskins461f0722019-08-01 21:31:49524 return S.getError();
Ben Langmuirc8130a72014-02-20 21:59:23525 Result = *S;
Harlan Haskins461f0722019-08-01 21:31:49526 return std::error_code();
Anders Carlsson5e368402011-03-18 19:23:19527}
528
Douglas Gregor09b69892011-02-10 17:09:37529void FileManager::GetUniqueIDMapping(
Chris Lattner0e62c1c2011-07-23 10:55:15530 SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
Douglas Gregor09b69892011-02-10 17:09:37531 UIDToFiles.clear();
532 UIDToFiles.resize(NextFileUID);
Fangrui Song6907ce22018-07-30 19:24:48533
Douglas Gregor09b69892011-02-10 17:09:37534 // Map file entries
Alex Lorenz4dc55732019-08-22 18:15:50535 for (llvm::StringMap<llvm::ErrorOr<SeenFileEntryOrRedirect>,
Harlan Haskins461f0722019-08-01 21:31:49536 llvm::BumpPtrAllocator>::const_iterator
Alex Lorenz4dc55732019-08-22 18:15:50537 FE = SeenFileEntries.begin(),
538 FEEnd = SeenFileEntries.end();
Douglas Gregor09b69892011-02-10 17:09:37539 FE != FEEnd; ++FE)
Alex Lorenz4dc55732019-08-22 18:15:50540 if (llvm::ErrorOr<SeenFileEntryOrRedirect> Entry = FE->getValue()) {
541 if (const auto *FE = (*Entry).dyn_cast<FileEntry *>())
542 UIDToFiles[FE->getUID()] = FE;
Harlan Haskins461f0722019-08-01 21:31:49543 }
Fangrui Song6907ce22018-07-30 19:24:48544
Douglas Gregor09b69892011-02-10 17:09:37545 // Map virtual file entries
David Blaikied2725a32015-12-09 17:23:13546 for (const auto &VFE : VirtualFileEntries)
Richard Smith018ab5f2019-01-30 02:23:34547 UIDToFiles[VFE->getUID()] = VFE.get();
Douglas Gregor09b69892011-02-10 17:09:37548}
Chris Lattner226efd32010-11-23 19:19:34549
Douglas Gregore00c8b22013-01-26 00:55:12550StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
Karl-Johan Karlssone8efac42019-12-20 07:07:22551 llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
552 = CanonicalNames.find(Dir);
553 if (Known != CanonicalNames.end())
Douglas Gregore00c8b22013-01-26 00:55:12554 return Known->second;
555
556 StringRef CanonicalName(Dir->getName());
Richard Smith54cc3c22014-12-11 20:50:24557
Eric Liu5fb18fe2018-05-17 10:26:23558 SmallString<4096> CanonicalNameBuf;
559 if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
Benjamin Kramerda4690a2015-08-04 11:27:08560 CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
Douglas Gregore00c8b22013-01-26 00:55:12561
Karl-Johan Karlssone8efac42019-12-20 07:07:22562 CanonicalNames.insert({Dir, CanonicalName});
563 return CanonicalName;
564}
565
566StringRef FileManager::getCanonicalName(const FileEntry *File) {
567 llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
568 = CanonicalNames.find(File);
569 if (Known != CanonicalNames.end())
570 return Known->second;
571
572 StringRef CanonicalName(File->getName());
573
574 SmallString<4096> CanonicalNameBuf;
575 if (!FS->getRealPath(File->getName(), CanonicalNameBuf))
576 CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
577
578 CanonicalNames.insert({File, CanonicalName});
Douglas Gregore00c8b22013-01-26 00:55:12579 return CanonicalName;
Douglas Gregore00c8b22013-01-26 00:55:12580}
Chris Lattner226efd32010-11-23 19:19:34581
Chris Lattner22eb9722006-06-18 05:43:12582void FileManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50583 llvm::errs() << "\n*** File Manager Stats:\n";
Zhanyong Wane1dd3e22011-02-11 18:44:49584 llvm::errs() << UniqueRealFiles.size() << " real files found, "
585 << UniqueRealDirs.size() << " real dirs found.\n";
586 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
587 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50588 llvm::errs() << NumDirLookups << " dir lookups, "
589 << NumDirCacheMisses << " dir cache misses.\n";
590 llvm::errs() << NumFileLookups << " file lookups, "
591 << NumFileCacheMisses << " file cache misses.\n";
Mike Stump11289f42009-09-09 15:08:12592
Benjamin Kramer89b422c2009-08-23 12:08:50593 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
Chris Lattner22eb9722006-06-18 05:43:12594}