blob: 29730272055e69d9983c33b8395ee05debff5cc3 [file] [log] [blame]
Eugene Zelenko5a520112018-03-28 22:09:09 +00001//===- VirtualFileSystem.cpp - Virtual File System Layer ------------------===//
Ben Langmuirc8130a72014-02-20 21:59:23 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Eugene Zelenko5a520112018-03-28 22:09:09 +00009//
Ben Langmuirc8130a72014-02-20 21:59:23 +000010// This file implements the VirtualFileSystem interface.
Eugene Zelenko5a520112018-03-28 22:09:09 +000011//
Ben Langmuirc8130a72014-02-20 21:59:23 +000012//===----------------------------------------------------------------------===//
13
Jonas Devliegherefc514902018-10-10 13:27:25 +000014#include "llvm/Support/VirtualFileSystem.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000015#include "llvm/ADT/ArrayRef.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000016#include "llvm/ADT/DenseMap.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000017#include "llvm/ADT/IntrusiveRefCntPtr.h"
Ilya Biryukovd5554c512018-09-04 14:15:53 +000018#include "llvm/ADT/None.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000019#include "llvm/ADT/Optional.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000020#include "llvm/ADT/STLExtras.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000021#include "llvm/ADT/SmallString.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringRef.h"
Ben Langmuir740812b2014-06-24 19:37:16 +000024#include "llvm/ADT/StringSet.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000025#include "llvm/ADT/Twine.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000026#include "llvm/ADT/iterator_range.h"
Benjamin Kramercfeacf52016-05-27 14:27:13 +000027#include "llvm/Config/llvm-config.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000028#include "llvm/Support/Casting.h"
29#include "llvm/Support/Chrono.h"
Ilya Biryukovd5554c512018-09-04 14:15:53 +000030#include "llvm/Support/Compiler.h"
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +000031#include "llvm/Support/Debug.h"
Rafael Espindola71de0b62014-06-13 17:20:50 +000032#include "llvm/Support/Errc.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000033#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/ErrorOr.h"
35#include "llvm/Support/FileSystem.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000036#include "llvm/Support/MemoryBuffer.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000037#include "llvm/Support/Path.h"
David Majnemer6a6206d2016-03-04 05:26:14 +000038#include "llvm/Support/Process.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000039#include "llvm/Support/SMLoc.h"
40#include "llvm/Support/SourceMgr.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000041#include "llvm/Support/YAMLParser.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000042#include "llvm/Support/raw_ostream.h"
43#include <algorithm>
Benjamin Kramer4527fb22014-03-02 17:08:31 +000044#include <atomic>
Eugene Zelenko5a520112018-03-28 22:09:09 +000045#include <cassert>
46#include <cstdint>
47#include <iterator>
48#include <limits>
49#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000050#include <memory>
Eric Liucea78e32018-09-05 09:45:27 +000051#include <mutex>
Eugene Zelenko5a520112018-03-28 22:09:09 +000052#include <string>
53#include <system_error>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000054#include <utility>
Eugene Zelenko5a520112018-03-28 22:09:09 +000055#include <vector>
Ben Langmuirc8130a72014-02-20 21:59:23 +000056
Ben Langmuirc8130a72014-02-20 21:59:23 +000057using namespace llvm;
Jonas Devliegherefc514902018-10-10 13:27:25 +000058using namespace llvm::vfs;
Eugene Zelenko5a520112018-03-28 22:09:09 +000059
Ben Langmuirc8130a72014-02-20 21:59:23 +000060using llvm::sys::fs::file_status;
61using llvm::sys::fs::file_type;
62using llvm::sys::fs::perms;
63using llvm::sys::fs::UniqueID;
64
65Status::Status(const file_status &Status)
66 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
67 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
Jonas Devliegherefc514902018-10-10 13:27:25 +000068 Type(Status.type()), Perms(Status.permissions()) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000069
Pavel Labathac71c8e2016-11-09 10:52:22 +000070Status::Status(StringRef Name, UniqueID UID, sys::TimePoint<> MTime,
Benjamin Kramer268b51a2015-10-05 13:15:33 +000071 uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
72 perms Perms)
Ben Langmuirb59cf672014-02-27 00:25:12 +000073 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
Eugene Zelenko5a520112018-03-28 22:09:09 +000074 Type(Type), Perms(Perms) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000075
Jordan Rupprechta8fb7292018-07-24 20:28:07 +000076Status Status::copyWithNewName(const Status &In, StringRef NewName) {
77 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
78 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
79 In.getPermissions());
80}
Benjamin Kramer268b51a2015-10-05 13:15:33 +000081
Jordan Rupprechta8fb7292018-07-24 20:28:07 +000082Status Status::copyWithNewName(const file_status &In, StringRef NewName) {
83 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
84 In.getUser(), In.getGroup(), In.getSize(), In.type(),
85 In.permissions());
Benjamin Kramer268b51a2015-10-05 13:15:33 +000086}
87
Ben Langmuirc8130a72014-02-20 21:59:23 +000088bool Status::equivalent(const Status &Other) const {
Benjamin Kramerd5152912017-07-20 11:57:02 +000089 assert(isStatusKnown() && Other.isStatusKnown());
Ben Langmuirc8130a72014-02-20 21:59:23 +000090 return getUniqueID() == Other.getUniqueID();
91}
Eugene Zelenko5a520112018-03-28 22:09:09 +000092
Jonas Devliegherefc514902018-10-10 13:27:25 +000093bool Status::isDirectory() const { return Type == file_type::directory_file; }
Eugene Zelenko5a520112018-03-28 22:09:09 +000094
Jonas Devliegherefc514902018-10-10 13:27:25 +000095bool Status::isRegularFile() const { return Type == file_type::regular_file; }
Eugene Zelenko5a520112018-03-28 22:09:09 +000096
Ben Langmuirc8130a72014-02-20 21:59:23 +000097bool Status::isOther() const {
98 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
99}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000100
Jonas Devliegherefc514902018-10-10 13:27:25 +0000101bool Status::isSymlink() const { return Type == file_type::symlink_file; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000102
Jonas Devliegherefc514902018-10-10 13:27:25 +0000103bool Status::isStatusKnown() const { return Type != file_type::status_error; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000104
Ben Langmuirc8130a72014-02-20 21:59:23 +0000105bool Status::exists() const {
106 return isStatusKnown() && Type != file_type::file_not_found;
107}
108
Eugene Zelenko5a520112018-03-28 22:09:09 +0000109File::~File() = default;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000110
Eugene Zelenko5a520112018-03-28 22:09:09 +0000111FileSystem::~FileSystem() = default;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000112
Benjamin Kramera8857962014-10-26 22:44:13 +0000113ErrorOr<std::unique_ptr<MemoryBuffer>>
114FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
115 bool RequiresNullTerminator, bool IsVolatile) {
116 auto F = openFileForRead(Name);
117 if (!F)
118 return F.getError();
Ben Langmuirc8130a72014-02-20 21:59:23 +0000119
Benjamin Kramera8857962014-10-26 22:44:13 +0000120 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000121}
122
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000123std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
Bob Wilsonf43354f2016-03-26 18:55:13 +0000124 if (llvm::sys::path::is_absolute(Path))
Eugene Zelenko5a520112018-03-28 22:09:09 +0000125 return {};
Bob Wilsonf43354f2016-03-26 18:55:13 +0000126
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000127 auto WorkingDir = getCurrentWorkingDirectory();
128 if (!WorkingDir)
129 return WorkingDir.getError();
130
131 return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
132}
133
Eric Liu5fb18fe2018-05-17 10:26:23 +0000134std::error_code FileSystem::getRealPath(const Twine &Path,
Sam McCall99538e82018-11-09 15:11:34 +0000135 SmallVectorImpl<char> &Output) const {
Eric Liu5fb18fe2018-05-17 10:26:23 +0000136 return errc::operation_not_permitted;
137}
138
Jonas Devliegherecbb5c862018-11-08 00:01:32 +0000139std::error_code FileSystem::isLocal(const Twine &Path, bool &Result) {
140 return errc::operation_not_permitted;
141}
142
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000143bool FileSystem::exists(const Twine &Path) {
144 auto Status = status(Path);
145 return Status && Status->exists();
146}
147
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000148#ifndef NDEBUG
149static bool isTraversalComponent(StringRef Component) {
150 return Component.equals("..") || Component.equals(".");
151}
152
153static bool pathHasTraversal(StringRef Path) {
154 using namespace llvm::sys;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000155
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000156 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
157 if (isTraversalComponent(Comp))
158 return true;
159 return false;
160}
161#endif
162
Ben Langmuirc8130a72014-02-20 21:59:23 +0000163//===-----------------------------------------------------------------------===/
164// RealFileSystem implementation
165//===-----------------------------------------------------------------------===/
166
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000167namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000168
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000169/// Wrapper around a raw file descriptor.
Ben Langmuirc8130a72014-02-20 21:59:23 +0000170class RealFile : public File {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000171 friend class RealFileSystem;
172
Ben Langmuirc8130a72014-02-20 21:59:23 +0000173 int FD;
Ben Langmuird066d4c2014-02-28 21:16:07 +0000174 Status S;
Taewook Ohf42103c2016-06-13 20:40:21 +0000175 std::string RealName;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000176
Taewook Ohf42103c2016-06-13 20:40:21 +0000177 RealFile(int FD, StringRef NewName, StringRef NewRealPathName)
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000178 : FD(FD), S(NewName, {}, {}, {}, {}, {},
Taewook Ohf42103c2016-06-13 20:40:21 +0000179 llvm::sys::fs::file_type::status_error, {}),
180 RealName(NewRealPathName.str()) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000181 assert(FD >= 0 && "Invalid or inactive file descriptor");
182 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000183
Ben Langmuirc8130a72014-02-20 21:59:23 +0000184public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000185 ~RealFile() override;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000186
Craig Toppera798a9d2014-03-02 09:32:10 +0000187 ErrorOr<Status> status() override;
Jordan Rupprechta8fb7292018-07-24 20:28:07 +0000188 ErrorOr<std::string> getName() override;
Benjamin Kramer737501c2015-10-05 21:20:19 +0000189 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
190 int64_t FileSize,
191 bool RequiresNullTerminator,
192 bool IsVolatile) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000193 std::error_code close() override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000194};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000195
196} // namespace
197
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000198RealFile::~RealFile() { close(); }
Ben Langmuirc8130a72014-02-20 21:59:23 +0000199
200ErrorOr<Status> RealFile::status() {
201 assert(FD != -1 && "cannot stat closed file");
Ben Langmuird066d4c2014-02-28 21:16:07 +0000202 if (!S.isStatusKnown()) {
203 file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000204 if (std::error_code EC = sys::fs::status(FD, RealStatus))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000205 return EC;
Jordan Rupprechta8fb7292018-07-24 20:28:07 +0000206 S = Status::copyWithNewName(RealStatus, S.getName());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000207 }
208 return S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000209}
210
Jordan Rupprechta8fb7292018-07-24 20:28:07 +0000211ErrorOr<std::string> RealFile::getName() {
212 return RealName.empty() ? S.getName().str() : RealName;
Taewook Ohf42103c2016-06-13 20:40:21 +0000213}
214
Benjamin Kramera8857962014-10-26 22:44:13 +0000215ErrorOr<std::unique_ptr<MemoryBuffer>>
216RealFile::getBuffer(const Twine &Name, int64_t FileSize,
217 bool RequiresNullTerminator, bool IsVolatile) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000218 assert(FD != -1 && "cannot get buffer for closed file");
Benjamin Kramera8857962014-10-26 22:44:13 +0000219 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
220 IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000221}
222
Rafael Espindola8e650d72014-06-12 20:37:59 +0000223std::error_code RealFile::close() {
David Majnemer6a6206d2016-03-04 05:26:14 +0000224 std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000225 FD = -1;
David Majnemer6a6206d2016-03-04 05:26:14 +0000226 return EC;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000227}
228
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000229namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000230
Amara Emersone07cdb12019-01-14 18:32:09 +0000231/// The file system according to your operating system.
Ben Langmuirc8130a72014-02-20 21:59:23 +0000232class RealFileSystem : public FileSystem {
233public:
Craig Toppera798a9d2014-03-02 09:32:10 +0000234 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000235 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000236 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000237
238 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
239 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
Jonas Devliegherecbb5c862018-11-08 00:01:32 +0000240 std::error_code isLocal(const Twine &Path, bool &Result) override;
Sam McCall99538e82018-11-09 15:11:34 +0000241 std::error_code getRealPath(const Twine &Path,
242 SmallVectorImpl<char> &Output) const override;
Jonas Devliegherefc514902018-10-10 13:27:25 +0000243
Eric Liucea78e32018-09-05 09:45:27 +0000244private:
Amara Emersone07cdb12019-01-14 18:32:09 +0000245 mutable std::mutex CWDMutex;
246 mutable std::string CWDCache;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000247};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000248
249} // namespace
Ben Langmuirc8130a72014-02-20 21:59:23 +0000250
251ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
252 sys::fs::file_status RealStatus;
Amara Emersone07cdb12019-01-14 18:32:09 +0000253 if (std::error_code EC = sys::fs::status(Path, RealStatus))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000254 return EC;
Jordan Rupprechta8fb7292018-07-24 20:28:07 +0000255 return Status::copyWithNewName(RealStatus, Path.str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000256}
257
Benjamin Kramera8857962014-10-26 22:44:13 +0000258ErrorOr<std::unique_ptr<File>>
259RealFileSystem::openFileForRead(const Twine &Name) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000260 int FD;
Amara Emersone07cdb12019-01-14 18:32:09 +0000261 SmallString<256> RealName;
262 if (std::error_code EC =
263 sys::fs::openFileForRead(Name, FD, sys::fs::OF_None, &RealName))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000264 return EC;
Taewook Ohf42103c2016-06-13 20:40:21 +0000265 return std::unique_ptr<File>(new RealFile(FD, Name.str(), RealName.str()));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000266}
267
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000268llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
Amara Emersone07cdb12019-01-14 18:32:09 +0000269 std::lock_guard<std::mutex> Lock(CWDMutex);
270 if (!CWDCache.empty())
271 return CWDCache;
272 SmallString<256> Dir;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000273 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
274 return EC;
Amara Emersone07cdb12019-01-14 18:32:09 +0000275 CWDCache = Dir.str();
276 return CWDCache;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000277}
278
279std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
Amara Emersone07cdb12019-01-14 18:32:09 +0000280 // FIXME: chdir is thread hostile; on the other hand, creating the same
281 // behavior as chdir is complex: chdir resolves the path once, thus
282 // guaranteeing that all subsequent relative path operations work
283 // on the same path the original chdir resulted in. This makes a
284 // difference for example on network filesystems, where symlinks might be
285 // switched during runtime of the tool. Fixing this depends on having a
286 // file system abstraction that allows openat() style interactions.
287 if (auto EC = llvm::sys::fs::set_current_path(Path))
288 return EC;
Eric Liucea78e32018-09-05 09:45:27 +0000289
Amara Emersone07cdb12019-01-14 18:32:09 +0000290 // Invalidate cache.
291 std::lock_guard<std::mutex> Lock(CWDMutex);
292 CWDCache.clear();
Eric Liucea78e32018-09-05 09:45:27 +0000293 return std::error_code();
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000294}
295
Jonas Devliegherecbb5c862018-11-08 00:01:32 +0000296std::error_code RealFileSystem::isLocal(const Twine &Path, bool &Result) {
Amara Emersone07cdb12019-01-14 18:32:09 +0000297 return llvm::sys::fs::is_local(Path, Result);
Jonas Devliegherecbb5c862018-11-08 00:01:32 +0000298}
299
Sam McCall99538e82018-11-09 15:11:34 +0000300std::error_code
301RealFileSystem::getRealPath(const Twine &Path,
302 SmallVectorImpl<char> &Output) const {
Amara Emersone07cdb12019-01-14 18:32:09 +0000303 return llvm::sys::fs::real_path(Path, Output);
Eric Liu5fb18fe2018-05-17 10:26:23 +0000304}
305
Ben Langmuirc8130a72014-02-20 21:59:23 +0000306IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
Amara Emersone07cdb12019-01-14 18:32:09 +0000307 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
Ben Langmuirc8130a72014-02-20 21:59:23 +0000308 return FS;
309}
310
Ben Langmuir740812b2014-06-24 19:37:16 +0000311namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000312
Jonas Devliegherefc514902018-10-10 13:27:25 +0000313class RealFSDirIter : public llvm::vfs::detail::DirIterImpl {
Ben Langmuir740812b2014-06-24 19:37:16 +0000314 llvm::sys::fs::directory_iterator Iter;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000315
Ben Langmuir740812b2014-06-24 19:37:16 +0000316public:
Juergen Ributzka4a259562017-03-10 21:23:29 +0000317 RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) {
Sam McCall0ae00562018-09-14 12:47:38 +0000318 if (Iter != llvm::sys::fs::directory_iterator())
319 CurrentEntry = directory_entry(Iter->path(), Iter->type());
Ben Langmuir740812b2014-06-24 19:37:16 +0000320 }
321
322 std::error_code increment() override {
323 std::error_code EC;
324 Iter.increment(EC);
Sam McCall0ae00562018-09-14 12:47:38 +0000325 CurrentEntry = (Iter == llvm::sys::fs::directory_iterator())
326 ? directory_entry()
327 : directory_entry(Iter->path(), Iter->type());
Ben Langmuir740812b2014-06-24 19:37:16 +0000328 return EC;
329 }
330};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000331
332} // namespace
Ben Langmuir740812b2014-06-24 19:37:16 +0000333
334directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
335 std::error_code &EC) {
Amara Emersone07cdb12019-01-14 18:32:09 +0000336 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
Ben Langmuir740812b2014-06-24 19:37:16 +0000337}
338
Ben Langmuirc8130a72014-02-20 21:59:23 +0000339//===-----------------------------------------------------------------------===/
340// OverlayFileSystem implementation
341//===-----------------------------------------------------------------------===/
Eugene Zelenko5a520112018-03-28 22:09:09 +0000342
Ben Langmuirc8130a72014-02-20 21:59:23 +0000343OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000344 FSList.push_back(std::move(BaseFS));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000345}
346
347void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
348 FSList.push_back(FS);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000349 // Synchronize added file systems by duplicating the working directory from
350 // the first one in the list.
351 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000352}
353
354ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
355 // FIXME: handle symlinks that cross file systems
356 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
357 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000358 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000359 return Status;
360 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000361 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000362}
363
Benjamin Kramera8857962014-10-26 22:44:13 +0000364ErrorOr<std::unique_ptr<File>>
365OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000366 // FIXME: handle symlinks that cross file systems
367 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000368 auto Result = (*I)->openFileForRead(Path);
369 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
370 return Result;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000371 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000372 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000373}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000374
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000375llvm::ErrorOr<std::string>
376OverlayFileSystem::getCurrentWorkingDirectory() const {
377 // All file systems are synchronized, just take the first working directory.
378 return FSList.front()->getCurrentWorkingDirectory();
379}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000380
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000381std::error_code
382OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
383 for (auto &FS : FSList)
384 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
385 return EC;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000386 return {};
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000387}
388
Jonas Devliegherecbb5c862018-11-08 00:01:32 +0000389std::error_code OverlayFileSystem::isLocal(const Twine &Path, bool &Result) {
390 for (auto &FS : FSList)
391 if (FS->exists(Path))
392 return FS->isLocal(Path, Result);
393 return errc::no_such_file_or_directory;
394}
395
Sam McCall99538e82018-11-09 15:11:34 +0000396std::error_code
397OverlayFileSystem::getRealPath(const Twine &Path,
398 SmallVectorImpl<char> &Output) const {
Eric Liua840a462018-05-18 13:22:49 +0000399 for (auto &FS : FSList)
400 if (FS->exists(Path))
Sam McCall99538e82018-11-09 15:11:34 +0000401 return FS->getRealPath(Path, Output);
Eric Liua840a462018-05-18 13:22:49 +0000402 return errc::no_such_file_or_directory;
403}
404
Jonas Devliegherefc514902018-10-10 13:27:25 +0000405llvm::vfs::detail::DirIterImpl::~DirIterImpl() = default;
Ben Langmuir740812b2014-06-24 19:37:16 +0000406
407namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000408
Jonas Devliegherefc514902018-10-10 13:27:25 +0000409class OverlayFSDirIterImpl : public llvm::vfs::detail::DirIterImpl {
Ben Langmuir740812b2014-06-24 19:37:16 +0000410 OverlayFileSystem &Overlays;
411 std::string Path;
412 OverlayFileSystem::iterator CurrentFS;
413 directory_iterator CurrentDirIter;
414 llvm::StringSet<> SeenNames;
415
416 std::error_code incrementFS() {
417 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
418 ++CurrentFS;
419 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
420 std::error_code EC;
421 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
422 if (EC && EC != errc::no_such_file_or_directory)
423 return EC;
424 if (CurrentDirIter != directory_iterator())
425 break; // found
426 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000427 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +0000428 }
429
430 std::error_code incrementDirIter(bool IsFirstTime) {
431 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
432 "incrementing past end");
433 std::error_code EC;
434 if (!IsFirstTime)
435 CurrentDirIter.increment(EC);
436 if (!EC && CurrentDirIter == directory_iterator())
437 EC = incrementFS();
438 return EC;
439 }
440
441 std::error_code incrementImpl(bool IsFirstTime) {
442 while (true) {
443 std::error_code EC = incrementDirIter(IsFirstTime);
444 if (EC || CurrentDirIter == directory_iterator()) {
Sam McCall0ae00562018-09-14 12:47:38 +0000445 CurrentEntry = directory_entry();
Ben Langmuir740812b2014-06-24 19:37:16 +0000446 return EC;
447 }
448 CurrentEntry = *CurrentDirIter;
Sam McCall0ae00562018-09-14 12:47:38 +0000449 StringRef Name = llvm::sys::path::filename(CurrentEntry.path());
David Blaikie61b86d42014-11-19 02:56:13 +0000450 if (SeenNames.insert(Name).second)
Ben Langmuir740812b2014-06-24 19:37:16 +0000451 return EC; // name not seen before
452 }
453 llvm_unreachable("returned above");
454 }
455
456public:
457 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
458 std::error_code &EC)
459 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
460 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
461 EC = incrementImpl(true);
462 }
463
464 std::error_code increment() override { return incrementImpl(false); }
465};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000466
467} // namespace
Ben Langmuir740812b2014-06-24 19:37:16 +0000468
469directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
470 std::error_code &EC) {
471 return directory_iterator(
472 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
473}
474
Richard Trieua87b70d2018-12-29 02:02:13 +0000475void ProxyFileSystem::anchor() {}
476
Jonas Devliegherefc514902018-10-10 13:27:25 +0000477namespace llvm {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000478namespace vfs {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000479
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000480namespace detail {
481
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000482enum InMemoryNodeKind { IME_File, IME_Directory, IME_HardLink };
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000483
484/// The in memory file system is a tree of Nodes. Every node can either be a
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000485/// file , hardlink or a directory.
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000486class InMemoryNode {
Eric Liub71e6f42018-07-11 18:43:07 +0000487 InMemoryNodeKind Kind;
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000488 std::string FileName;
Simon Marchiddbabc62018-08-06 21:48:20 +0000489
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000490public:
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000491 InMemoryNode(llvm::StringRef FileName, InMemoryNodeKind Kind)
492 : Kind(Kind), FileName(llvm::sys::path::filename(FileName)) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000493 virtual ~InMemoryNode() = default;
494
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000495 /// Get the filename of this node (the name without the directory part).
496 StringRef getFileName() const { return FileName; }
497 InMemoryNodeKind getKind() const { return Kind; }
498 virtual std::string toString(unsigned Indent) const = 0;
499};
500
501class InMemoryFile : public InMemoryNode {
502 Status Stat;
503 std::unique_ptr<llvm::MemoryBuffer> Buffer;
504
505public:
506 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
507 : InMemoryNode(Stat.getName(), IME_File), Stat(std::move(Stat)),
508 Buffer(std::move(Buffer)) {}
509
Simon Marchiddbabc62018-08-06 21:48:20 +0000510 /// Return the \p Status for this node. \p RequestedName should be the name
511 /// through which the caller referred to this node. It will override
512 /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
513 Status getStatus(StringRef RequestedName) const {
514 return Status::copyWithNewName(Stat, RequestedName);
515 }
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000516 llvm::MemoryBuffer *getBuffer() const { return Buffer.get(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000517
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000518 std::string toString(unsigned Indent) const override {
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000519 return (std::string(Indent, ' ') + Stat.getName() + "\n").str();
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000520 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000521
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000522 static bool classof(const InMemoryNode *N) {
523 return N->getKind() == IME_File;
524 }
525};
526
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000527namespace {
528
529class InMemoryHardLink : public InMemoryNode {
530 const InMemoryFile &ResolvedFile;
531
532public:
533 InMemoryHardLink(StringRef Path, const InMemoryFile &ResolvedFile)
534 : InMemoryNode(Path, IME_HardLink), ResolvedFile(ResolvedFile) {}
535 const InMemoryFile &getResolvedFile() const { return ResolvedFile; }
536
537 std::string toString(unsigned Indent) const override {
538 return std::string(Indent, ' ') + "HardLink to -> " +
539 ResolvedFile.toString(0);
540 }
541
542 static bool classof(const InMemoryNode *N) {
543 return N->getKind() == IME_HardLink;
544 }
545};
546
Simon Marchiddbabc62018-08-06 21:48:20 +0000547/// Adapt a InMemoryFile for VFS' File interface. The goal is to make
548/// \p InMemoryFileAdaptor mimic as much as possible the behavior of
549/// \p RealFile.
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000550class InMemoryFileAdaptor : public File {
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000551 const InMemoryFile &Node;
Simon Marchiddbabc62018-08-06 21:48:20 +0000552 /// The name to use when returning a Status for this file.
553 std::string RequestedName;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000554
Simon Marchia37ef292018-07-11 14:08:17 +0000555public:
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000556 explicit InMemoryFileAdaptor(const InMemoryFile &Node,
557 std::string RequestedName)
Simon Marchiddbabc62018-08-06 21:48:20 +0000558 : Node(Node), RequestedName(std::move(RequestedName)) {}
Simon Marchia37ef292018-07-11 14:08:17 +0000559
Simon Marchiddbabc62018-08-06 21:48:20 +0000560 llvm::ErrorOr<Status> status() override {
561 return Node.getStatus(RequestedName);
562 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000563
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000564 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +0000565 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
566 bool IsVolatile) override {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000567 llvm::MemoryBuffer *Buf = Node.getBuffer();
568 return llvm::MemoryBuffer::getMemBuffer(
569 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
570 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000571
572 std::error_code close() override { return {}; }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000573};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000574} // namespace
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000575
576class InMemoryDirectory : public InMemoryNode {
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000577 Status Stat;
Eric Liu495847a2018-09-24 14:52:11 +0000578 llvm::StringMap<std::unique_ptr<InMemoryNode>> Entries;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000579
580public:
581 InMemoryDirectory(Status Stat)
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000582 : InMemoryNode(Stat.getName(), IME_Directory), Stat(std::move(Stat)) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000583
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000584 /// Return the \p Status for this node. \p RequestedName should be the name
585 /// through which the caller referred to this node. It will override
586 /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
587 Status getStatus(StringRef RequestedName) const {
588 return Status::copyWithNewName(Stat, RequestedName);
589 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000590 InMemoryNode *getChild(StringRef Name) {
591 auto I = Entries.find(Name);
592 if (I != Entries.end())
593 return I->second.get();
594 return nullptr;
595 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000596
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000597 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
598 return Entries.insert(make_pair(Name, std::move(Child)))
599 .first->second.get();
600 }
601
Eugene Zelenko5a520112018-03-28 22:09:09 +0000602 using const_iterator = decltype(Entries)::const_iterator;
603
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000604 const_iterator begin() const { return Entries.begin(); }
605 const_iterator end() const { return Entries.end(); }
606
607 std::string toString(unsigned Indent) const override {
608 std::string Result =
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000609 (std::string(Indent, ' ') + Stat.getName() + "\n").str();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000610 for (const auto &Entry : Entries)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000611 Result += Entry.second->toString(Indent + 2);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000612 return Result;
613 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000614
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000615 static bool classof(const InMemoryNode *N) {
616 return N->getKind() == IME_Directory;
617 }
618};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000619
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000620namespace {
621Status getNodeStatus(const InMemoryNode *Node, StringRef RequestedName) {
622 if (auto Dir = dyn_cast<detail::InMemoryDirectory>(Node))
623 return Dir->getStatus(RequestedName);
624 if (auto File = dyn_cast<detail::InMemoryFile>(Node))
625 return File->getStatus(RequestedName);
626 if (auto Link = dyn_cast<detail::InMemoryHardLink>(Node))
627 return Link->getResolvedFile().getStatus(RequestedName);
628 llvm_unreachable("Unknown node type");
629}
630} // namespace
Eugene Zelenko5a520112018-03-28 22:09:09 +0000631} // namespace detail
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000632
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000633InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000634 : Root(new detail::InMemoryDirectory(
Pavel Labathac71c8e2016-11-09 10:52:22 +0000635 Status("", getNextVirtualUniqueID(), llvm::sys::TimePoint<>(), 0, 0,
636 0, llvm::sys::fs::file_type::directory_file,
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000637 llvm::sys::fs::perms::all_all))),
638 UseNormalizedPaths(UseNormalizedPaths) {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000639
Eugene Zelenko5a520112018-03-28 22:09:09 +0000640InMemoryFileSystem::~InMemoryFileSystem() = default;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000641
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000642std::string InMemoryFileSystem::toString() const {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000643 return Root->toString(/*Indent=*/0);
644}
645
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000646bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000647 std::unique_ptr<llvm::MemoryBuffer> Buffer,
648 Optional<uint32_t> User,
649 Optional<uint32_t> Group,
650 Optional<llvm::sys::fs::file_type> Type,
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000651 Optional<llvm::sys::fs::perms> Perms,
652 const detail::InMemoryFile *HardLinkTarget) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000653 SmallString<128> Path;
654 P.toVector(Path);
655
656 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000657 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000658 assert(!EC);
659 (void)EC;
660
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000661 if (useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000662 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000663
664 if (Path.empty())
665 return false;
666
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000667 detail::InMemoryDirectory *Dir = Root.get();
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000668 auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path);
669 const auto ResolvedUser = User.getValueOr(0);
670 const auto ResolvedGroup = Group.getValueOr(0);
671 const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file);
672 const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all);
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000673 assert(!(HardLinkTarget && Buffer) && "HardLink cannot have a buffer");
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000674 // Any intermediate directories we create should be accessible by
675 // the owner, even if Perms says otherwise for the final path.
676 const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000677 while (true) {
678 StringRef Name = *I;
679 detail::InMemoryNode *Node = Dir->getChild(Name);
680 ++I;
681 if (!Node) {
682 if (I == E) {
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000683 // End of the path.
Ben Hamilton78381012017-11-16 19:34:08 +0000684 std::unique_ptr<detail::InMemoryNode> Child;
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000685 if (HardLinkTarget)
686 Child.reset(new detail::InMemoryHardLink(P.str(), *HardLinkTarget));
687 else {
688 // Create a new file or directory.
689 Status Stat(P.str(), getNextVirtualUniqueID(),
690 llvm::sys::toTimePoint(ModificationTime), ResolvedUser,
691 ResolvedGroup, Buffer->getBufferSize(), ResolvedType,
692 ResolvedPerms);
693 if (ResolvedType == sys::fs::file_type::directory_file) {
694 Child.reset(new detail::InMemoryDirectory(std::move(Stat)));
695 } else {
696 Child.reset(
697 new detail::InMemoryFile(std::move(Stat), std::move(Buffer)));
698 }
Ben Hamilton78381012017-11-16 19:34:08 +0000699 }
700 Dir->addChild(Name, std::move(Child));
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000701 return true;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000702 }
703
704 // Create a new directory. Use the path up to here.
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000705 Status Stat(
706 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000707 getNextVirtualUniqueID(), llvm::sys::toTimePoint(ModificationTime),
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000708 ResolvedUser, ResolvedGroup, 0, sys::fs::file_type::directory_file,
709 NewDirectoryPerms);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000710 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
711 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
712 continue;
713 }
714
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000715 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000716 Dir = NewDir;
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000717 } else {
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000718 assert((isa<detail::InMemoryFile>(Node) ||
719 isa<detail::InMemoryHardLink>(Node)) &&
720 "Must be either file, hardlink or directory!");
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000721
722 // Trying to insert a directory in place of a file.
723 if (I != E)
724 return false;
725
726 // Return false only if the new file is different from the existing one.
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000727 if (auto Link = dyn_cast<detail::InMemoryHardLink>(Node)) {
728 return Link->getResolvedFile().getBuffer()->getBuffer() ==
729 Buffer->getBuffer();
730 }
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000731 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
732 Buffer->getBuffer();
733 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000734 }
735}
736
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000737bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
738 std::unique_ptr<llvm::MemoryBuffer> Buffer,
739 Optional<uint32_t> User,
740 Optional<uint32_t> Group,
741 Optional<llvm::sys::fs::file_type> Type,
742 Optional<llvm::sys::fs::perms> Perms) {
743 return addFile(P, ModificationTime, std::move(Buffer), User, Group, Type,
744 Perms, /*HardLinkTarget=*/nullptr);
745}
746
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000747bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000748 llvm::MemoryBuffer *Buffer,
749 Optional<uint32_t> User,
750 Optional<uint32_t> Group,
751 Optional<llvm::sys::fs::file_type> Type,
752 Optional<llvm::sys::fs::perms> Perms) {
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000753 return addFile(P, ModificationTime,
754 llvm::MemoryBuffer::getMemBuffer(
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000755 Buffer->getBuffer(), Buffer->getBufferIdentifier()),
756 std::move(User), std::move(Group), std::move(Type),
757 std::move(Perms));
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000758}
759
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000760static ErrorOr<const detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000761lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
762 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000763 SmallString<128> Path;
764 P.toVector(Path);
765
766 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000767 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000768 assert(!EC);
769 (void)EC;
770
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000771 if (FS.useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000772 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer4ad1c432015-10-12 13:30:38 +0000773
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000774 if (Path.empty())
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000775 return Dir;
776
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000777 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000778 while (true) {
779 detail::InMemoryNode *Node = Dir->getChild(*I);
780 ++I;
781 if (!Node)
782 return errc::no_such_file_or_directory;
783
784 // Return the file if it's at the end of the path.
785 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
786 if (I == E)
787 return File;
788 return errc::no_such_file_or_directory;
789 }
790
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000791 // If Node is HardLink then return the resolved file.
792 if (auto File = dyn_cast<detail::InMemoryHardLink>(Node)) {
793 if (I == E)
794 return &File->getResolvedFile();
795 return errc::no_such_file_or_directory;
796 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000797 // Traverse directories.
798 Dir = cast<detail::InMemoryDirectory>(Node);
799 if (I == E)
800 return Dir;
801 }
802}
803
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000804bool InMemoryFileSystem::addHardLink(const Twine &FromPath,
805 const Twine &ToPath) {
806 auto FromNode = lookupInMemoryNode(*this, Root.get(), FromPath);
807 auto ToNode = lookupInMemoryNode(*this, Root.get(), ToPath);
808 // FromPath must not have been added before. ToPath must have been added
809 // before. Resolved ToPath must be a File.
810 if (!ToNode || FromNode || !isa<detail::InMemoryFile>(*ToNode))
811 return false;
812 return this->addFile(FromPath, 0, nullptr, None, None, None, None,
813 cast<detail::InMemoryFile>(*ToNode));
814}
815
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000816llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000817 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000818 if (Node)
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000819 return detail::getNodeStatus(*Node, Path.str());
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000820 return Node.getError();
821}
822
823llvm::ErrorOr<std::unique_ptr<File>>
824InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000825 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000826 if (!Node)
827 return Node.getError();
828
829 // When we have a file provide a heap-allocated wrapper for the memory buffer
830 // to match the ownership semantics for File.
831 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
Simon Marchiddbabc62018-08-06 21:48:20 +0000832 return std::unique_ptr<File>(
833 new detail::InMemoryFileAdaptor(*F, Path.str()));
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000834
835 // FIXME: errc::not_a_file?
836 return make_error_code(llvm::errc::invalid_argument);
837}
838
839namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000840
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000841/// Adaptor from InMemoryDir::iterator to directory_iterator.
Jonas Devliegherefc514902018-10-10 13:27:25 +0000842class InMemoryDirIterator : public llvm::vfs::detail::DirIterImpl {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000843 detail::InMemoryDirectory::const_iterator I;
844 detail::InMemoryDirectory::const_iterator E;
Simon Marchiddbabc62018-08-06 21:48:20 +0000845 std::string RequestedDirName;
846
847 void setCurrentEntry() {
848 if (I != E) {
849 SmallString<256> Path(RequestedDirName);
850 llvm::sys::path::append(Path, I->second->getFileName());
Sam McCall0ae00562018-09-14 12:47:38 +0000851 sys::fs::file_type Type;
852 switch (I->second->getKind()) {
Jonas Devliegherefc514902018-10-10 13:27:25 +0000853 case detail::IME_File:
854 case detail::IME_HardLink:
855 Type = sys::fs::file_type::regular_file;
856 break;
857 case detail::IME_Directory:
858 Type = sys::fs::file_type::directory_file;
859 break;
Sam McCall0ae00562018-09-14 12:47:38 +0000860 }
861 CurrentEntry = directory_entry(Path.str(), Type);
Simon Marchiddbabc62018-08-06 21:48:20 +0000862 } else {
863 // When we're at the end, make CurrentEntry invalid and DirIterImpl will
864 // do the rest.
Sam McCall0ae00562018-09-14 12:47:38 +0000865 CurrentEntry = directory_entry();
Simon Marchiddbabc62018-08-06 21:48:20 +0000866 }
867 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000868
869public:
Eugene Zelenko5a520112018-03-28 22:09:09 +0000870 InMemoryDirIterator() = default;
871
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000872 explicit InMemoryDirIterator(const detail::InMemoryDirectory &Dir,
Simon Marchiddbabc62018-08-06 21:48:20 +0000873 std::string RequestedDirName)
874 : I(Dir.begin()), E(Dir.end()),
875 RequestedDirName(std::move(RequestedDirName)) {
876 setCurrentEntry();
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000877 }
878
879 std::error_code increment() override {
880 ++I;
Simon Marchiddbabc62018-08-06 21:48:20 +0000881 setCurrentEntry();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000882 return {};
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000883 }
884};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000885
886} // namespace
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000887
888directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
889 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000890 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000891 if (!Node) {
892 EC = Node.getError();
893 return directory_iterator(std::make_shared<InMemoryDirIterator>());
894 }
895
896 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
Simon Marchiddbabc62018-08-06 21:48:20 +0000897 return directory_iterator(
898 std::make_shared<InMemoryDirIterator>(*DirNode, Dir.str()));
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000899
900 EC = make_error_code(llvm::errc::not_a_directory);
901 return directory_iterator(std::make_shared<InMemoryDirIterator>());
902}
Benjamin Kramere9e76072016-01-09 16:33:16 +0000903
904std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
905 SmallString<128> Path;
906 P.toVector(Path);
907
908 // Fix up relative paths. This just prepends the current working directory.
909 std::error_code EC = makeAbsolute(Path);
910 assert(!EC);
911 (void)EC;
912
913 if (useNormalizedPaths())
914 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
915
916 if (!Path.empty())
917 WorkingDirectory = Path.str();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000918 return {};
Benjamin Kramere9e76072016-01-09 16:33:16 +0000919}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000920
Sam McCall99538e82018-11-09 15:11:34 +0000921std::error_code
922InMemoryFileSystem::getRealPath(const Twine &Path,
923 SmallVectorImpl<char> &Output) const {
Eric Liu33dd6192018-05-24 11:17:00 +0000924 auto CWD = getCurrentWorkingDirectory();
925 if (!CWD || CWD->empty())
926 return errc::operation_not_permitted;
927 Path.toVector(Output);
928 if (auto EC = makeAbsolute(Output))
929 return EC;
930 llvm::sys::path::remove_dots(Output, /*remove_dot_dot=*/true);
931 return {};
932}
933
Jonas Devliegherecbb5c862018-11-08 00:01:32 +0000934std::error_code InMemoryFileSystem::isLocal(const Twine &Path, bool &Result) {
935 Result = false;
936 return {};
937}
938
Eugene Zelenko5a520112018-03-28 22:09:09 +0000939} // namespace vfs
Jonas Devliegherefc514902018-10-10 13:27:25 +0000940} // namespace llvm
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000941
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000942//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000943// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000944//===-----------------------------------------------------------------------===/
945
Volodymyr Sapsai91e13162018-10-26 22:14:33 +0000946// FIXME: reuse implementation common with OverlayFSDirIterImpl as these
947// iterators are conceptually similar.
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +0000948class llvm::vfs::VFSFromYamlDirIterImpl
949 : public llvm::vfs::detail::DirIterImpl {
Ben Langmuir740812b2014-06-24 19:37:16 +0000950 std::string Dir;
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +0000951 RedirectingFileSystem::RedirectingDirectoryEntry::iterator Current, End;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000952
Volodymyr Sapsai91e13162018-10-26 22:14:33 +0000953 // To handle 'fallthrough' mode we need to iterate at first through
954 // RedirectingDirectoryEntry and then through ExternalFS. These operations are
955 // done sequentially, we just need to keep a track of what kind of iteration
956 // we are currently performing.
957
958 /// Flag telling if we should iterate through ExternalFS or stop at the last
959 /// RedirectingDirectoryEntry::iterator.
960 bool IterateExternalFS;
961 /// Flag telling if we have switched to iterating through ExternalFS.
962 bool IsExternalFSCurrent = false;
963 FileSystem &ExternalFS;
964 directory_iterator ExternalDirIter;
965 llvm::StringSet<> SeenNames;
966
967 /// To combine multiple iterations, different methods are responsible for
968 /// different iteration steps.
969 /// @{
970
971 /// Responsible for dispatching between RedirectingDirectoryEntry iteration
972 /// and ExternalFS iteration.
973 std::error_code incrementImpl(bool IsFirstTime);
974 /// Responsible for RedirectingDirectoryEntry iteration.
975 std::error_code incrementContent(bool IsFirstTime);
976 /// Responsible for ExternalFS iteration.
977 std::error_code incrementExternal();
978 /// @}
Volodymyr Sapsai3aa88b52018-08-07 23:00:40 +0000979
Ben Langmuir740812b2014-06-24 19:37:16 +0000980public:
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +0000981 VFSFromYamlDirIterImpl(
982 const Twine &Path,
983 RedirectingFileSystem::RedirectingDirectoryEntry::iterator Begin,
984 RedirectingFileSystem::RedirectingDirectoryEntry::iterator End,
985 bool IterateExternalFS, FileSystem &ExternalFS, std::error_code &EC);
Eugene Zelenko5a520112018-03-28 22:09:09 +0000986
Ben Langmuir740812b2014-06-24 19:37:16 +0000987 std::error_code increment() override;
988};
989
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +0000990llvm::ErrorOr<std::string>
991RedirectingFileSystem::getCurrentWorkingDirectory() const {
992 return ExternalFS->getCurrentWorkingDirectory();
993}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000994
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +0000995std::error_code
996RedirectingFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
997 return ExternalFS->setCurrentWorkingDirectory(Path);
998}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000999
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001000std::error_code RedirectingFileSystem::isLocal(const Twine &Path,
1001 bool &Result) {
1002 return ExternalFS->isLocal(Path, Result);
1003}
Eugene Zelenko5a520112018-03-28 22:09:09 +00001004
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001005directory_iterator RedirectingFileSystem::dir_begin(const Twine &Dir,
1006 std::error_code &EC) {
1007 ErrorOr<RedirectingFileSystem::Entry *> E = lookupPath(Dir);
1008 if (!E) {
1009 EC = E.getError();
1010 if (IsFallthrough && EC == errc::no_such_file_or_directory)
1011 return ExternalFS->dir_begin(Dir, EC);
1012 return {};
1013 }
1014 ErrorOr<Status> S = status(Dir, *E);
1015 if (!S) {
1016 EC = S.getError();
1017 return {};
1018 }
1019 if (!S->isDirectory()) {
1020 EC = std::error_code(static_cast<int>(errc::not_a_directory),
1021 std::system_category());
1022 return {};
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001023 }
Eugene Zelenko5a520112018-03-28 22:09:09 +00001024
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001025 auto *D = cast<RedirectingFileSystem::RedirectingDirectoryEntry>(*E);
1026 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(
1027 Dir, D->contents_begin(), D->contents_end(),
1028 /*IterateExternalFS=*/IsFallthrough, *ExternalFS, EC));
1029}
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001030
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001031void RedirectingFileSystem::setExternalContentsPrefixDir(StringRef PrefixDir) {
1032 ExternalContentsPrefixDir = PrefixDir.str();
1033}
Jonas Devliegherecbb5c862018-11-08 00:01:32 +00001034
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001035StringRef RedirectingFileSystem::getExternalContentsPrefixDir() const {
1036 return ExternalContentsPrefixDir;
1037}
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001038
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001039#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001040LLVM_DUMP_METHOD void RedirectingFileSystem::dump() const {
1041 for (const auto &Root : Roots)
1042 dumpEntry(Root.get());
1043}
1044
1045LLVM_DUMP_METHOD void
1046RedirectingFileSystem::dumpEntry(RedirectingFileSystem::Entry *E,
1047 int NumSpaces) const {
1048 StringRef Name = E->getName();
1049 for (int i = 0, e = NumSpaces; i < e; ++i)
1050 dbgs() << " ";
1051 dbgs() << "'" << Name.str().c_str() << "'"
1052 << "\n";
1053
1054 if (E->getKind() == RedirectingFileSystem::EK_Directory) {
1055 auto *DE = dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(E);
1056 assert(DE && "Should be a directory");
1057
1058 for (std::unique_ptr<Entry> &SubEntry :
1059 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1060 dumpEntry(SubEntry.get(), NumSpaces + 2);
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001061 }
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001062}
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001063#endif
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001064
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001065/// A helper class to hold the common YAML parsing state.
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001066class llvm::vfs::RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001067 yaml::Stream &Stream;
1068
Jonas Devliegherefc514902018-10-10 13:27:25 +00001069 void error(yaml::Node *N, const Twine &Msg) { Stream.printError(N, Msg); }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001070
1071 // false on error
1072 bool parseScalarString(yaml::Node *N, StringRef &Result,
1073 SmallVectorImpl<char> &Storage) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001074 const auto *S = dyn_cast<yaml::ScalarNode>(N);
1075
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001076 if (!S) {
1077 error(N, "expected string");
1078 return false;
1079 }
1080 Result = S->getValue(Storage);
1081 return true;
1082 }
1083
1084 // false on error
1085 bool parseScalarBool(yaml::Node *N, bool &Result) {
1086 SmallString<5> Storage;
1087 StringRef Value;
1088 if (!parseScalarString(N, Value, Storage))
1089 return false;
1090
1091 if (Value.equals_lower("true") || Value.equals_lower("on") ||
1092 Value.equals_lower("yes") || Value == "1") {
1093 Result = true;
1094 return true;
1095 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
1096 Value.equals_lower("no") || Value == "0") {
1097 Result = false;
1098 return true;
1099 }
1100
1101 error(N, "expected boolean value");
1102 return false;
1103 }
1104
1105 struct KeyStatus {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001106 bool Required;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001107 bool Seen = false;
1108
1109 KeyStatus(bool Required = false) : Required(Required) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001110 };
Eugene Zelenko5a520112018-03-28 22:09:09 +00001111
1112 using KeyStatusPair = std::pair<StringRef, KeyStatus>;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001113
1114 // false on error
1115 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1116 DenseMap<StringRef, KeyStatus> &Keys) {
1117 if (!Keys.count(Key)) {
1118 error(KeyNode, "unknown key");
1119 return false;
1120 }
1121 KeyStatus &S = Keys[Key];
1122 if (S.Seen) {
1123 error(KeyNode, Twine("duplicate key '") + Key + "'");
1124 return false;
1125 }
1126 S.Seen = true;
1127 return true;
1128 }
1129
1130 // false on error
1131 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001132 for (const auto &I : Keys) {
1133 if (I.second.Required && !I.second.Seen) {
1134 error(Obj, Twine("missing key '") + I.first + "'");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001135 return false;
1136 }
1137 }
1138 return true;
1139 }
1140
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001141 RedirectingFileSystem::Entry *
1142 lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1143 RedirectingFileSystem::Entry *ParentEntry = nullptr) {
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001144 if (!ParentEntry) { // Look for a existent root
Eugene Zelenko5a520112018-03-28 22:09:09 +00001145 for (const auto &Root : FS->Roots) {
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001146 if (Name.equals(Root->getName())) {
1147 ParentEntry = Root.get();
1148 return ParentEntry;
1149 }
1150 }
1151 } else { // Advance to the next component
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001152 auto *DE = dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(
1153 ParentEntry);
1154 for (std::unique_ptr<RedirectingFileSystem::Entry> &Content :
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001155 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001156 auto *DirContent =
1157 dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(
1158 Content.get());
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001159 if (DirContent && Name.equals(Content->getName()))
1160 return DirContent;
1161 }
1162 }
1163
1164 // ... or create a new one
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001165 std::unique_ptr<RedirectingFileSystem::Entry> E =
1166 llvm::make_unique<RedirectingFileSystem::RedirectingDirectoryEntry>(
1167 Name, Status("", getNextVirtualUniqueID(),
1168 std::chrono::system_clock::now(), 0, 0, 0,
1169 file_type::directory_file, sys::fs::all_all));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001170
1171 if (!ParentEntry) { // Add a new root to the overlay
1172 FS->Roots.push_back(std::move(E));
1173 ParentEntry = FS->Roots.back().get();
1174 return ParentEntry;
1175 }
1176
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001177 auto *DE =
1178 dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(ParentEntry);
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001179 DE->addContent(std::move(E));
1180 return DE->getLastContent();
1181 }
1182
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001183 void uniqueOverlayTree(RedirectingFileSystem *FS,
1184 RedirectingFileSystem::Entry *SrcE,
1185 RedirectingFileSystem::Entry *NewParentE = nullptr) {
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001186 StringRef Name = SrcE->getName();
1187 switch (SrcE->getKind()) {
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001188 case RedirectingFileSystem::EK_Directory: {
1189 auto *DE =
1190 dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(SrcE);
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001191 assert(DE && "Must be a directory");
1192 // Empty directories could be present in the YAML as a way to
1193 // describe a file for a current directory after some of its subdir
1194 // is parsed. This only leads to redundant walks, ignore it.
1195 if (!Name.empty())
1196 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001197 for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001198 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1199 uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1200 break;
1201 }
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001202 case RedirectingFileSystem::EK_File: {
1203 auto *FE = dyn_cast<RedirectingFileSystem::RedirectingFileEntry>(SrcE);
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001204 assert(FE && "Must be a file");
1205 assert(NewParentE && "Parent entry must exist");
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001206 auto *DE = dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(
1207 NewParentE);
1208 DE->addContent(
1209 llvm::make_unique<RedirectingFileSystem::RedirectingFileEntry>(
1210 Name, FE->getExternalContentsPath(), FE->getUseName()));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001211 break;
1212 }
1213 }
1214 }
1215
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001216 std::unique_ptr<RedirectingFileSystem::Entry>
1217 parseEntry(yaml::Node *N, RedirectingFileSystem *FS, bool IsRootEntry) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001218 auto *M = dyn_cast<yaml::MappingNode>(N);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001219 if (!M) {
1220 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +00001221 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001222 }
1223
1224 KeyStatusPair Fields[] = {
Jonas Devliegherefc514902018-10-10 13:27:25 +00001225 KeyStatusPair("name", true),
1226 KeyStatusPair("type", true),
1227 KeyStatusPair("contents", false),
1228 KeyStatusPair("external-contents", false),
1229 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001230 };
1231
Craig Topperac67c052015-11-30 03:11:10 +00001232 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001233
1234 bool HasContents = false; // external or otherwise
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001235 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>>
1236 EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001237 std::string ExternalContentsPath;
1238 std::string Name;
Volodymyr Sapsai3b2f6a42018-08-07 19:05:41 +00001239 yaml::Node *NameValueNode;
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001240 auto UseExternalName =
1241 RedirectingFileSystem::RedirectingFileEntry::NK_NotSet;
1242 RedirectingFileSystem::EntryKind Kind;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001243
Eugene Zelenko5a520112018-03-28 22:09:09 +00001244 for (auto &I : *M) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001245 StringRef Key;
1246 // Reuse the buffer for key and value, since we don't look at key after
1247 // parsing value.
1248 SmallString<256> Buffer;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001249 if (!parseScalarString(I.getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001250 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001251
Eugene Zelenko5a520112018-03-28 22:09:09 +00001252 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001253 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001254
1255 StringRef Value;
1256 if (Key == "name") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001257 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001258 return nullptr;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001259
Volodymyr Sapsai3b2f6a42018-08-07 19:05:41 +00001260 NameValueNode = I.getValue();
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001261 if (FS->UseCanonicalizedPaths) {
1262 SmallString<256> Path(Value);
1263 // Guarantee that old YAML files containing paths with ".." and "."
1264 // are properly canonicalized before read into the VFS.
1265 Path = sys::path::remove_leading_dotslash(Path);
1266 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1267 Name = Path.str();
1268 } else {
1269 Name = Value;
1270 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001271 } else if (Key == "type") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001272 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001273 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001274 if (Value == "file")
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001275 Kind = RedirectingFileSystem::EK_File;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001276 else if (Value == "directory")
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001277 Kind = RedirectingFileSystem::EK_Directory;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001278 else {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001279 error(I.getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +00001280 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001281 }
1282 } else if (Key == "contents") {
1283 if (HasContents) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001284 error(I.getKey(),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001285 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001286 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001287 }
1288 HasContents = true;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001289 auto *Contents = dyn_cast<yaml::SequenceNode>(I.getValue());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001290 if (!Contents) {
1291 // FIXME: this is only for directories, what about files?
Eugene Zelenko5a520112018-03-28 22:09:09 +00001292 error(I.getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +00001293 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001294 }
1295
Eugene Zelenko5a520112018-03-28 22:09:09 +00001296 for (auto &I : *Contents) {
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001297 if (std::unique_ptr<RedirectingFileSystem::Entry> E =
Volodymyr Sapsai3b2f6a42018-08-07 19:05:41 +00001298 parseEntry(&I, FS, /*IsRootEntry*/ false))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001299 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001300 else
Craig Topperf1186c52014-05-08 06:41:40 +00001301 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001302 }
1303 } else if (Key == "external-contents") {
1304 if (HasContents) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001305 error(I.getKey(),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001306 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001307 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001308 }
1309 HasContents = true;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001310 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001311 return nullptr;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001312
1313 SmallString<256> FullPath;
1314 if (FS->IsRelativeOverlay) {
1315 FullPath = FS->getExternalContentsPrefixDir();
1316 assert(!FullPath.empty() &&
1317 "External contents prefix directory must exist");
1318 llvm::sys::path::append(FullPath, Value);
1319 } else {
1320 FullPath = Value;
1321 }
1322
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001323 if (FS->UseCanonicalizedPaths) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001324 // Guarantee that old YAML files containing paths with ".." and "."
1325 // are properly canonicalized before read into the VFS.
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001326 FullPath = sys::path::remove_leading_dotslash(FullPath);
1327 sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001328 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001329 ExternalContentsPath = FullPath.str();
Ben Langmuirb59cf672014-02-27 00:25:12 +00001330 } else if (Key == "use-external-name") {
1331 bool Val;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001332 if (!parseScalarBool(I.getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001333 return nullptr;
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001334 UseExternalName =
1335 Val ? RedirectingFileSystem::RedirectingFileEntry::NK_External
1336 : RedirectingFileSystem::RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001337 } else {
1338 llvm_unreachable("key missing from Keys");
1339 }
1340 }
1341
1342 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001343 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001344
1345 // check for missing keys
1346 if (!HasContents) {
1347 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001348 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001349 }
1350 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001351 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001352
Ben Langmuirb59cf672014-02-27 00:25:12 +00001353 // check invalid configuration
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001354 if (Kind == RedirectingFileSystem::EK_Directory &&
1355 UseExternalName !=
1356 RedirectingFileSystem::RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001357 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001358 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001359 }
1360
Volodymyr Sapsai3b2f6a42018-08-07 19:05:41 +00001361 if (IsRootEntry && !sys::path::is_absolute(Name)) {
1362 assert(NameValueNode && "Name presence should be checked earlier");
1363 error(NameValueNode,
1364 "entry with relative path at the root level is not discoverable");
1365 return nullptr;
1366 }
1367
Ben Langmuir93853232014-03-05 21:32:20 +00001368 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001369 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001370 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1371 while (Trimmed.size() > RootPathLen &&
1372 sys::path::is_separator(Trimmed.back()))
Jonas Devliegherefc514902018-10-10 13:27:25 +00001373 Trimmed = Trimmed.slice(0, Trimmed.size() - 1);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001374 // Get the last component
1375 StringRef LastComponent = sys::path::filename(Trimmed);
1376
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001377 std::unique_ptr<RedirectingFileSystem::Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001378 switch (Kind) {
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001379 case RedirectingFileSystem::EK_File:
1380 Result = llvm::make_unique<RedirectingFileSystem::RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001381 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001382 break;
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001383 case RedirectingFileSystem::EK_Directory:
1384 Result =
1385 llvm::make_unique<RedirectingFileSystem::RedirectingDirectoryEntry>(
1386 LastComponent, std::move(EntryArrayContents),
1387 Status("", getNextVirtualUniqueID(),
1388 std::chrono::system_clock::now(), 0, 0, 0,
1389 file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001390 break;
1391 }
1392
1393 StringRef Parent = sys::path::parent_path(Trimmed);
1394 if (Parent.empty())
1395 return Result;
1396
1397 // if 'name' contains multiple components, create implicit directory entries
1398 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1399 E = sys::path::rend(Parent);
1400 I != E; ++I) {
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001401 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> Entries;
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001402 Entries.push_back(std::move(Result));
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001403 Result =
1404 llvm::make_unique<RedirectingFileSystem::RedirectingDirectoryEntry>(
1405 *I, std::move(Entries),
1406 Status("", getNextVirtualUniqueID(),
1407 std::chrono::system_clock::now(), 0, 0, 0,
1408 file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001409 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001410 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001411 }
1412
1413public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001414 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001415
1416 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001417 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001418 auto *Top = dyn_cast<yaml::MappingNode>(Root);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001419 if (!Top) {
1420 error(Root, "expected mapping node");
1421 return false;
1422 }
1423
1424 KeyStatusPair Fields[] = {
Jonas Devliegherefc514902018-10-10 13:27:25 +00001425 KeyStatusPair("version", true),
1426 KeyStatusPair("case-sensitive", false),
1427 KeyStatusPair("use-external-names", false),
1428 KeyStatusPair("overlay-relative", false),
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001429 KeyStatusPair("fallthrough", false),
Jonas Devliegherefc514902018-10-10 13:27:25 +00001430 KeyStatusPair("roots", true),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001431 };
1432
Craig Topperac67c052015-11-30 03:11:10 +00001433 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001434 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> RootEntries;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001435
1436 // Parse configuration and 'roots'
Eugene Zelenko5a520112018-03-28 22:09:09 +00001437 for (auto &I : *Top) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001438 SmallString<10> KeyBuffer;
1439 StringRef Key;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001440 if (!parseScalarString(I.getKey(), Key, KeyBuffer))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001441 return false;
1442
Eugene Zelenko5a520112018-03-28 22:09:09 +00001443 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001444 return false;
1445
1446 if (Key == "roots") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001447 auto *Roots = dyn_cast<yaml::SequenceNode>(I.getValue());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001448 if (!Roots) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001449 error(I.getValue(), "expected array");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001450 return false;
1451 }
1452
Eugene Zelenko5a520112018-03-28 22:09:09 +00001453 for (auto &I : *Roots) {
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001454 if (std::unique_ptr<RedirectingFileSystem::Entry> E =
Volodymyr Sapsai3b2f6a42018-08-07 19:05:41 +00001455 parseEntry(&I, FS, /*IsRootEntry*/ true))
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001456 RootEntries.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001457 else
1458 return false;
1459 }
1460 } else if (Key == "version") {
1461 StringRef VersionString;
1462 SmallString<4> Storage;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001463 if (!parseScalarString(I.getValue(), VersionString, Storage))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001464 return false;
1465 int Version;
1466 if (VersionString.getAsInteger<int>(10, Version)) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001467 error(I.getValue(), "expected integer");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001468 return false;
1469 }
1470 if (Version < 0) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001471 error(I.getValue(), "invalid version number");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001472 return false;
1473 }
1474 if (Version != 0) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001475 error(I.getValue(), "version mismatch, expected 0");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001476 return false;
1477 }
1478 } else if (Key == "case-sensitive") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001479 if (!parseScalarBool(I.getValue(), FS->CaseSensitive))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001480 return false;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001481 } else if (Key == "overlay-relative") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001482 if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay))
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001483 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001484 } else if (Key == "use-external-names") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001485 if (!parseScalarBool(I.getValue(), FS->UseExternalNames))
Ben Langmuirb59cf672014-02-27 00:25:12 +00001486 return false;
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001487 } else if (Key == "fallthrough") {
1488 if (!parseScalarBool(I.getValue(), FS->IsFallthrough))
1489 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001490 } else {
1491 llvm_unreachable("key missing from Keys");
1492 }
1493 }
1494
1495 if (Stream.failed())
1496 return false;
1497
1498 if (!checkMissingKeys(Top, Keys))
1499 return false;
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001500
1501 // Now that we sucessefully parsed the YAML file, canonicalize the internal
1502 // representation to a proper directory tree so that we can search faster
1503 // inside the VFS.
Eugene Zelenko5a520112018-03-28 22:09:09 +00001504 for (auto &E : RootEntries)
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001505 uniqueOverlayTree(FS, E.get());
1506
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001507 return true;
1508 }
1509};
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001510
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001511RedirectingFileSystem *
1512RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1513 SourceMgr::DiagHandlerTy DiagHandler,
1514 StringRef YAMLFilePath, void *DiagContext,
1515 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001516 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001517 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001518
Ben Langmuir97882e72014-02-24 20:56:37 +00001519 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001520 yaml::document_iterator DI = Stream.begin();
1521 yaml::Node *Root = DI->getRoot();
1522 if (DI == Stream.end() || !Root) {
1523 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001524 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001525 }
1526
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001527 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001528
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001529 std::unique_ptr<RedirectingFileSystem> FS(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001530 new RedirectingFileSystem(std::move(ExternalFS)));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001531
1532 if (!YAMLFilePath.empty()) {
1533 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1534 // to each 'external-contents' path.
1535 //
1536 // Example:
1537 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
1538 // yields:
1539 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1540 //
1541 SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1542 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1543 assert(!EC && "Overlay dir final path must be absolute");
1544 (void)EC;
1545 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1546 }
1547
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001548 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001549 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001550
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001551 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001552}
1553
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001554ErrorOr<RedirectingFileSystem::Entry *>
1555RedirectingFileSystem::lookupPath(const Twine &Path_) const {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001556 SmallString<256> Path;
1557 Path_.toVector(Path);
1558
1559 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001560 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001561 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001562
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001563 // Canonicalize path by removing ".", "..", "./", etc components. This is
1564 // a VFS request, do bot bother about symlinks in the path components
1565 // but canonicalize in order to perform the correct entry search.
1566 if (UseCanonicalizedPaths) {
1567 Path = sys::path::remove_leading_dotslash(Path);
1568 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1569 }
1570
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001571 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001572 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001573
1574 sys::path::const_iterator Start = sys::path::begin(Path);
1575 sys::path::const_iterator End = sys::path::end(Path);
Eugene Zelenko5a520112018-03-28 22:09:09 +00001576 for (const auto &Root : Roots) {
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001577 ErrorOr<RedirectingFileSystem::Entry *> Result =
1578 lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001579 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001580 return Result;
1581 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001582 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001583}
1584
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001585ErrorOr<RedirectingFileSystem::Entry *>
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001586RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
Volodymyr Sapsai76100332018-11-16 01:15:54 +00001587 sys::path::const_iterator End,
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001588 RedirectingFileSystem::Entry *From) const {
Nico Weber1865df42018-04-27 19:11:14 +00001589#ifndef _WIN32
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001590 assert(!isTraversalComponent(*Start) &&
1591 !isTraversalComponent(From->getName()) &&
1592 "Paths should not contain traversal components");
1593#else
1594 // FIXME: this is here to support windows, remove it once canonicalized
1595 // paths become globally default.
Bruno Cardoso Lopesbe056b12016-02-23 17:06:50 +00001596 if (Start->equals("."))
1597 ++Start;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001598#endif
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001599
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001600 StringRef FromName = From->getName();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001601
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001602 // Forward the search to the next component in case this is an empty one.
1603 if (!FromName.empty()) {
1604 if (CaseSensitive ? !Start->equals(FromName)
1605 : !Start->equals_lower(FromName))
1606 // failure to match
1607 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001608
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001609 ++Start;
1610
1611 if (Start == End) {
1612 // Match!
1613 return From;
1614 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001615 }
1616
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001617 auto *DE = dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001618 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001619 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001620
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001621 for (const std::unique_ptr<RedirectingFileSystem::Entry> &DirEntry :
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001622 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001623 ErrorOr<RedirectingFileSystem::Entry *> Result =
1624 lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001625 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001626 return Result;
1627 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001628 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001629}
1630
Ben Langmuirf13302e2015-12-10 23:41:39 +00001631static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1632 Status ExternalStatus) {
1633 Status S = ExternalStatus;
1634 if (!UseExternalNames)
Jordan Rupprechta8fb7292018-07-24 20:28:07 +00001635 S = Status::copyWithNewName(S, Path.str());
Ben Langmuirf13302e2015-12-10 23:41:39 +00001636 S.IsVFSMapped = true;
1637 return S;
1638}
1639
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001640ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path,
1641 RedirectingFileSystem::Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001642 assert(E != nullptr);
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001643 if (auto *F = dyn_cast<RedirectingFileSystem::RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001644 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001645 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuir5de00f32014-05-23 18:15:47 +00001646 if (S)
Ben Langmuirf13302e2015-12-10 23:41:39 +00001647 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1648 *S);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001649 return S;
1650 } else { // directory
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001651 auto *DE = cast<RedirectingFileSystem::RedirectingDirectoryEntry>(E);
Jordan Rupprechta8fb7292018-07-24 20:28:07 +00001652 return Status::copyWithNewName(DE->getStatus(), Path.str());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001653 }
1654}
1655
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001656ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001657 ErrorOr<RedirectingFileSystem::Entry *> Result = lookupPath(Path);
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001658 if (!Result) {
1659 if (IsFallthrough &&
1660 Result.getError() == llvm::errc::no_such_file_or_directory) {
1661 return ExternalFS->status(Path);
1662 }
Ben Langmuir740812b2014-06-24 19:37:16 +00001663 return Result.getError();
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001664 }
Ben Langmuir740812b2014-06-24 19:37:16 +00001665 return status(Path, *Result);
1666}
1667
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001668namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001669
Ben Langmuirf13302e2015-12-10 23:41:39 +00001670/// Provide a file wrapper with an overriden status.
1671class FileWithFixedStatus : public File {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001672 std::unique_ptr<File> InnerFile;
Ben Langmuirf13302e2015-12-10 23:41:39 +00001673 Status S;
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001674
1675public:
Ben Langmuirf13302e2015-12-10 23:41:39 +00001676 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
Benjamin Kramercfeacf52016-05-27 14:27:13 +00001677 : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001678
Ben Langmuirf13302e2015-12-10 23:41:39 +00001679 ErrorOr<Status> status() override { return S; }
1680 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Eugene Zelenko5a520112018-03-28 22:09:09 +00001681
Benjamin Kramer737501c2015-10-05 21:20:19 +00001682 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1683 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001684 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1685 IsVolatile);
1686 }
Eugene Zelenko5a520112018-03-28 22:09:09 +00001687
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001688 std::error_code close() override { return InnerFile->close(); }
1689};
Eugene Zelenko5a520112018-03-28 22:09:09 +00001690
1691} // namespace
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001692
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001693ErrorOr<std::unique_ptr<File>>
1694RedirectingFileSystem::openFileForRead(const Twine &Path) {
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001695 ErrorOr<RedirectingFileSystem::Entry *> E = lookupPath(Path);
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001696 if (!E) {
1697 if (IsFallthrough &&
1698 E.getError() == llvm::errc::no_such_file_or_directory) {
1699 return ExternalFS->openFileForRead(Path);
1700 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001701 return E.getError();
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001702 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001703
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001704 auto *F = dyn_cast<RedirectingFileSystem::RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001705 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001706 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001707
Benjamin Kramera8857962014-10-26 22:44:13 +00001708 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1709 if (!Result)
1710 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001711
Ben Langmuirf13302e2015-12-10 23:41:39 +00001712 auto ExternalStatus = (*Result)->status();
1713 if (!ExternalStatus)
1714 return ExternalStatus.getError();
Ben Langmuird066d4c2014-02-28 21:16:07 +00001715
Ben Langmuirf13302e2015-12-10 23:41:39 +00001716 // FIXME: Update the status with the name and VFSMapped.
1717 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1718 *ExternalStatus);
1719 return std::unique_ptr<File>(
1720 llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001721}
1722
Volodymyr Sapsai76100332018-11-16 01:15:54 +00001723std::error_code
1724RedirectingFileSystem::getRealPath(const Twine &Path,
1725 SmallVectorImpl<char> &Output) const {
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001726 ErrorOr<RedirectingFileSystem::Entry *> Result = lookupPath(Path);
Volodymyr Sapsai76100332018-11-16 01:15:54 +00001727 if (!Result) {
1728 if (IsFallthrough &&
1729 Result.getError() == llvm::errc::no_such_file_or_directory) {
1730 return ExternalFS->getRealPath(Path, Output);
1731 }
1732 return Result.getError();
1733 }
1734
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001735 if (auto *F =
1736 dyn_cast<RedirectingFileSystem::RedirectingFileEntry>(*Result)) {
Volodymyr Sapsai76100332018-11-16 01:15:54 +00001737 return ExternalFS->getRealPath(F->getExternalContentsPath(), Output);
1738 }
1739 // Even if there is a directory entry, fall back to ExternalFS if allowed,
1740 // because directories don't have a single external contents path.
1741 return IsFallthrough ? ExternalFS->getRealPath(Path, Output)
1742 : llvm::errc::invalid_argument;
1743}
1744
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001745IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001746vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001747 SourceMgr::DiagHandlerTy DiagHandler,
Jonas Devliegherefc514902018-10-10 13:27:25 +00001748 StringRef YAMLFilePath, void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001749 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001750 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001751 YAMLFilePath, DiagContext,
1752 std::move(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001753}
1754
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001755static void getVFSEntries(RedirectingFileSystem::Entry *SrcE,
1756 SmallVectorImpl<StringRef> &Path,
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001757 SmallVectorImpl<YAMLVFSEntry> &Entries) {
1758 auto Kind = SrcE->getKind();
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001759 if (Kind == RedirectingFileSystem::EK_Directory) {
1760 auto *DE = dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(SrcE);
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001761 assert(DE && "Must be a directory");
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001762 for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001763 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1764 Path.push_back(SubEntry->getName());
1765 getVFSEntries(SubEntry.get(), Path, Entries);
1766 Path.pop_back();
1767 }
1768 return;
1769 }
1770
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001771 assert(Kind == RedirectingFileSystem::EK_File && "Must be a EK_File");
1772 auto *FE = dyn_cast<RedirectingFileSystem::RedirectingFileEntry>(SrcE);
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001773 assert(FE && "Must be a file");
1774 SmallString<128> VPath;
1775 for (auto &Comp : Path)
1776 llvm::sys::path::append(VPath, Comp);
1777 Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
1778}
1779
1780void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1781 SourceMgr::DiagHandlerTy DiagHandler,
1782 StringRef YAMLFilePath,
1783 SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
1784 void *DiagContext,
1785 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1786 RedirectingFileSystem *VFS = RedirectingFileSystem::create(
1787 std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
1788 std::move(ExternalFS));
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001789 ErrorOr<RedirectingFileSystem::Entry *> RootE = VFS->lookupPath("/");
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001790 if (!RootE)
1791 return;
1792 SmallVector<StringRef, 8> Components;
1793 Components.push_back("/");
1794 getVFSEntries(*RootE, Components, CollectedEntries);
1795}
1796
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001797UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001798 static std::atomic<unsigned> UID;
1799 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001800 // The following assumes that uint64_t max will never collide with a real
1801 // dev_t value from the OS.
1802 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1803}
Justin Bogner9c785292014-05-20 21:43:27 +00001804
Justin Bogner9c785292014-05-20 21:43:27 +00001805void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1806 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1807 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1808 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1809 Mappings.emplace_back(VirtualPath, RealPath);
1810}
1811
Justin Bogner44fa450342014-05-21 22:46:51 +00001812namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001813
Justin Bogner44fa450342014-05-21 22:46:51 +00001814class JSONWriter {
1815 llvm::raw_ostream &OS;
1816 SmallVector<StringRef, 16> DirStack;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001817
1818 unsigned getDirIndent() { return 4 * DirStack.size(); }
1819 unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
Justin Bogner44fa450342014-05-21 22:46:51 +00001820 bool containedIn(StringRef Parent, StringRef Path);
1821 StringRef containedPart(StringRef Parent, StringRef Path);
1822 void startDirectory(StringRef Path);
1823 void endDirectory();
1824 void writeEntry(StringRef VPath, StringRef RPath);
1825
1826public:
1827 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +00001828
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001829 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
1830 Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
Volodymyr Sapsai7faf7ae2018-10-24 22:40:54 +00001831 StringRef OverlayDir);
Justin Bogner44fa450342014-05-21 22:46:51 +00001832};
Eugene Zelenko5a520112018-03-28 22:09:09 +00001833
1834} // namespace
Justin Bogner9c785292014-05-20 21:43:27 +00001835
Justin Bogner44fa450342014-05-21 22:46:51 +00001836bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001837 using namespace llvm::sys;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001838
Justin Bogner1c078f22014-05-20 22:12:58 +00001839 // Compare each path component.
1840 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1841 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1842 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1843 if (*IParent != *IChild)
1844 return false;
1845 }
1846 // Have we exhausted the parent path?
1847 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001848}
1849
Justin Bogner44fa450342014-05-21 22:46:51 +00001850StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1851 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001852 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001853 return Path.slice(Parent.size() + 1, StringRef::npos);
1854}
1855
Justin Bogner44fa450342014-05-21 22:46:51 +00001856void JSONWriter::startDirectory(StringRef Path) {
1857 StringRef Name =
1858 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1859 DirStack.push_back(Path);
1860 unsigned Indent = getDirIndent();
1861 OS.indent(Indent) << "{\n";
1862 OS.indent(Indent + 2) << "'type': 'directory',\n";
1863 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1864 OS.indent(Indent + 2) << "'contents': [\n";
1865}
1866
1867void JSONWriter::endDirectory() {
1868 unsigned Indent = getDirIndent();
1869 OS.indent(Indent + 2) << "]\n";
1870 OS.indent(Indent) << "}";
1871
1872 DirStack.pop_back();
1873}
1874
1875void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1876 unsigned Indent = getFileIndent();
1877 OS.indent(Indent) << "{\n";
1878 OS.indent(Indent + 2) << "'type': 'file',\n";
1879 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1880 OS.indent(Indent + 2) << "'external-contents': \""
1881 << llvm::yaml::escape(RPath) << "\"\n";
1882 OS.indent(Indent) << "}";
1883}
1884
1885void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001886 Optional<bool> UseExternalNames,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001887 Optional<bool> IsCaseSensitive,
1888 Optional<bool> IsOverlayRelative,
1889 StringRef OverlayDir) {
Justin Bogner44fa450342014-05-21 22:46:51 +00001890 using namespace llvm::sys;
1891
1892 OS << "{\n"
1893 " 'version': 0,\n";
1894 if (IsCaseSensitive.hasValue())
1895 OS << " 'case-sensitive': '"
1896 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001897 if (UseExternalNames.hasValue())
1898 OS << " 'use-external-names': '"
1899 << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001900 bool UseOverlayRelative = false;
1901 if (IsOverlayRelative.hasValue()) {
1902 UseOverlayRelative = IsOverlayRelative.getValue();
Jonas Devliegherefc514902018-10-10 13:27:25 +00001903 OS << " 'overlay-relative': '" << (UseOverlayRelative ? "true" : "false")
1904 << "',\n";
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001905 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001906 OS << " 'roots': [\n";
1907
Justin Bogner73466402014-07-15 01:24:35 +00001908 if (!Entries.empty()) {
1909 const YAMLVFSEntry &Entry = Entries.front();
1910 startDirectory(path::parent_path(Entry.VPath));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001911
1912 StringRef RPath = Entry.RPath;
1913 if (UseOverlayRelative) {
1914 unsigned OverlayDirLen = OverlayDir.size();
1915 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1916 "Overlay dir must be contained in RPath");
1917 RPath = RPath.slice(OverlayDirLen, RPath.size());
1918 }
1919
1920 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001921
Justin Bogner73466402014-07-15 01:24:35 +00001922 for (const auto &Entry : Entries.slice(1)) {
1923 StringRef Dir = path::parent_path(Entry.VPath);
1924 if (Dir == DirStack.back())
1925 OS << ",\n";
1926 else {
1927 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1928 OS << "\n";
1929 endDirectory();
1930 }
1931 OS << ",\n";
1932 startDirectory(Dir);
1933 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001934 StringRef RPath = Entry.RPath;
1935 if (UseOverlayRelative) {
1936 unsigned OverlayDirLen = OverlayDir.size();
1937 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1938 "Overlay dir must be contained in RPath");
1939 RPath = RPath.slice(OverlayDirLen, RPath.size());
1940 }
1941 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner73466402014-07-15 01:24:35 +00001942 }
1943
1944 while (!DirStack.empty()) {
1945 OS << "\n";
1946 endDirectory();
1947 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001948 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001949 }
1950
Justin Bogner73466402014-07-15 01:24:35 +00001951 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001952 << "}\n";
1953}
1954
Justin Bogner9c785292014-05-20 21:43:27 +00001955void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
Fangrui Song55fab262018-09-26 22:16:28 +00001956 llvm::sort(Mappings, [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001957 return LHS.VPath < RHS.VPath;
1958 });
1959
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001960 JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
Volodymyr Sapsai7faf7ae2018-10-24 22:40:54 +00001961 IsOverlayRelative, OverlayDir);
Justin Bogner9c785292014-05-20 21:43:27 +00001962}
Ben Langmuir740812b2014-06-24 19:37:16 +00001963
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001964VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00001965 const Twine &_Path,
1966 RedirectingFileSystem::RedirectingDirectoryEntry::iterator Begin,
1967 RedirectingFileSystem::RedirectingDirectoryEntry::iterator End,
1968 bool IterateExternalFS, FileSystem &ExternalFS, std::error_code &EC)
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001969 : Dir(_Path.str()), Current(Begin), End(End),
1970 IterateExternalFS(IterateExternalFS), ExternalFS(ExternalFS) {
1971 EC = incrementImpl(/*IsFirstTime=*/true);
Ben Langmuir740812b2014-06-24 19:37:16 +00001972}
1973
1974std::error_code VFSFromYamlDirIterImpl::increment() {
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001975 return incrementImpl(/*IsFirstTime=*/false);
Volodymyr Sapsai3aa88b52018-08-07 23:00:40 +00001976}
1977
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001978std::error_code VFSFromYamlDirIterImpl::incrementExternal() {
1979 assert(!(IsExternalFSCurrent && ExternalDirIter == directory_iterator()) &&
1980 "incrementing past end");
1981 std::error_code EC;
1982 if (IsExternalFSCurrent) {
1983 ExternalDirIter.increment(EC);
1984 } else if (IterateExternalFS) {
1985 ExternalDirIter = ExternalFS.dir_begin(Dir, EC);
1986 IsExternalFSCurrent = true;
1987 if (EC && EC != errc::no_such_file_or_directory)
1988 return EC;
1989 EC = {};
1990 }
1991 if (EC || ExternalDirIter == directory_iterator()) {
1992 CurrentEntry = directory_entry();
1993 } else {
1994 CurrentEntry = *ExternalDirIter;
1995 }
1996 return EC;
1997}
1998
1999std::error_code VFSFromYamlDirIterImpl::incrementContent(bool IsFirstTime) {
Erich Keanef1d30612018-10-29 21:21:55 +00002000 assert((IsFirstTime || Current != End) && "cannot iterate past end");
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00002001 if (!IsFirstTime)
2002 ++Current;
Volodymyr Sapsai3aa88b52018-08-07 23:00:40 +00002003 while (Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00002004 SmallString<128> PathStr(Dir);
2005 llvm::sys::path::append(PathStr, (*Current)->getName());
Sam McCall0ae00562018-09-14 12:47:38 +00002006 sys::fs::file_type Type;
2007 switch ((*Current)->getKind()) {
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00002008 case RedirectingFileSystem::EK_Directory:
Jonas Devliegherefc514902018-10-10 13:27:25 +00002009 Type = sys::fs::file_type::directory_file;
2010 break;
Jonas Devlieghere1a0ce652019-01-15 22:36:41 +00002011 case RedirectingFileSystem::EK_File:
Jonas Devliegherefc514902018-10-10 13:27:25 +00002012 Type = sys::fs::file_type::regular_file;
2013 break;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00002014 }
Sam McCall0ae00562018-09-14 12:47:38 +00002015 CurrentEntry = directory_entry(PathStr.str(), Type);
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00002016 return {};
Bruno Cardoso Lopese43e2632016-08-12 02:17:26 +00002017 }
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00002018 return incrementExternal();
2019}
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00002020
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00002021std::error_code VFSFromYamlDirIterImpl::incrementImpl(bool IsFirstTime) {
2022 while (true) {
2023 std::error_code EC = IsExternalFSCurrent ? incrementExternal()
2024 : incrementContent(IsFirstTime);
2025 if (EC || CurrentEntry.path().empty())
2026 return EC;
2027 StringRef Name = llvm::sys::path::filename(CurrentEntry.path());
2028 if (SeenNames.insert(Name).second)
2029 return EC; // name not seen before
2030 }
2031 llvm_unreachable("returned above");
Ben Langmuir740812b2014-06-24 19:37:16 +00002032}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002033
Jonas Devliegherefc514902018-10-10 13:27:25 +00002034vfs::recursive_directory_iterator::recursive_directory_iterator(
2035 FileSystem &FS_, const Twine &Path, std::error_code &EC)
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002036 : FS(&FS_) {
2037 directory_iterator I = FS->dir_begin(Path, EC);
Juergen Ributzkaf9787432017-03-14 00:14:40 +00002038 if (I != directory_iterator()) {
Jonas Devlieghere41fb9512018-10-31 23:36:10 +00002039 State = std::make_shared<detail::RecDirIterState>();
2040 State->Stack.push(I);
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002041 }
2042}
2043
2044vfs::recursive_directory_iterator &
2045recursive_directory_iterator::increment(std::error_code &EC) {
Jonas Devlieghere41fb9512018-10-31 23:36:10 +00002046 assert(FS && State && !State->Stack.empty() && "incrementing past end");
2047 assert(!State->Stack.top()->path().empty() && "non-canonical end iterator");
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002048 vfs::directory_iterator End;
Jonas Devlieghere41fb9512018-10-31 23:36:10 +00002049
2050 if (State->HasNoPushRequest)
2051 State->HasNoPushRequest = false;
2052 else {
2053 if (State->Stack.top()->type() == sys::fs::file_type::directory_file) {
2054 vfs::directory_iterator I = FS->dir_begin(State->Stack.top()->path(), EC);
2055 if (I != End) {
2056 State->Stack.push(I);
2057 return *this;
2058 }
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002059 }
2060 }
2061
Jonas Devlieghere41fb9512018-10-31 23:36:10 +00002062 while (!State->Stack.empty() && State->Stack.top().increment(EC) == End)
2063 State->Stack.pop();
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002064
Jonas Devlieghere41fb9512018-10-31 23:36:10 +00002065 if (State->Stack.empty())
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002066 State.reset(); // end iterator
2067
2068 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002069}