blob: 81ac5bbaa9cbeb5ea7dc324561d1aac6176a5050 [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,
135 SmallVectorImpl<char> &Output) const {
136 return errc::operation_not_permitted;
137}
138
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000139bool FileSystem::exists(const Twine &Path) {
140 auto Status = status(Path);
141 return Status && Status->exists();
142}
143
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000144#ifndef NDEBUG
145static bool isTraversalComponent(StringRef Component) {
146 return Component.equals("..") || Component.equals(".");
147}
148
149static bool pathHasTraversal(StringRef Path) {
150 using namespace llvm::sys;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000151
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000152 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
153 if (isTraversalComponent(Comp))
154 return true;
155 return false;
156}
157#endif
158
Ben Langmuirc8130a72014-02-20 21:59:23 +0000159//===-----------------------------------------------------------------------===/
160// RealFileSystem implementation
161//===-----------------------------------------------------------------------===/
162
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000163namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000164
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000165/// Wrapper around a raw file descriptor.
Ben Langmuirc8130a72014-02-20 21:59:23 +0000166class RealFile : public File {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000167 friend class RealFileSystem;
168
Ben Langmuirc8130a72014-02-20 21:59:23 +0000169 int FD;
Ben Langmuird066d4c2014-02-28 21:16:07 +0000170 Status S;
Taewook Ohf42103c2016-06-13 20:40:21 +0000171 std::string RealName;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000172
Taewook Ohf42103c2016-06-13 20:40:21 +0000173 RealFile(int FD, StringRef NewName, StringRef NewRealPathName)
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000174 : FD(FD), S(NewName, {}, {}, {}, {}, {},
Taewook Ohf42103c2016-06-13 20:40:21 +0000175 llvm::sys::fs::file_type::status_error, {}),
176 RealName(NewRealPathName.str()) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000177 assert(FD >= 0 && "Invalid or inactive file descriptor");
178 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000179
Ben Langmuirc8130a72014-02-20 21:59:23 +0000180public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000181 ~RealFile() override;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000182
Craig Toppera798a9d2014-03-02 09:32:10 +0000183 ErrorOr<Status> status() override;
Jordan Rupprechta8fb7292018-07-24 20:28:07 +0000184 ErrorOr<std::string> getName() override;
Benjamin Kramer737501c2015-10-05 21:20:19 +0000185 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
186 int64_t FileSize,
187 bool RequiresNullTerminator,
188 bool IsVolatile) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000189 std::error_code close() override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000190};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000191
192} // namespace
193
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000194RealFile::~RealFile() { close(); }
Ben Langmuirc8130a72014-02-20 21:59:23 +0000195
196ErrorOr<Status> RealFile::status() {
197 assert(FD != -1 && "cannot stat closed file");
Ben Langmuird066d4c2014-02-28 21:16:07 +0000198 if (!S.isStatusKnown()) {
199 file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000200 if (std::error_code EC = sys::fs::status(FD, RealStatus))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000201 return EC;
Jordan Rupprechta8fb7292018-07-24 20:28:07 +0000202 S = Status::copyWithNewName(RealStatus, S.getName());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000203 }
204 return S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000205}
206
Jordan Rupprechta8fb7292018-07-24 20:28:07 +0000207ErrorOr<std::string> RealFile::getName() {
208 return RealName.empty() ? S.getName().str() : RealName;
Taewook Ohf42103c2016-06-13 20:40:21 +0000209}
210
Benjamin Kramera8857962014-10-26 22:44:13 +0000211ErrorOr<std::unique_ptr<MemoryBuffer>>
212RealFile::getBuffer(const Twine &Name, int64_t FileSize,
213 bool RequiresNullTerminator, bool IsVolatile) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000214 assert(FD != -1 && "cannot get buffer for closed file");
Benjamin Kramera8857962014-10-26 22:44:13 +0000215 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
216 IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000217}
218
Rafael Espindola8e650d72014-06-12 20:37:59 +0000219std::error_code RealFile::close() {
David Majnemer6a6206d2016-03-04 05:26:14 +0000220 std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000221 FD = -1;
David Majnemer6a6206d2016-03-04 05:26:14 +0000222 return EC;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000223}
224
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000225namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000226
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000227/// The file system according to your operating system.
Ben Langmuirc8130a72014-02-20 21:59:23 +0000228class RealFileSystem : public FileSystem {
229public:
Craig Toppera798a9d2014-03-02 09:32:10 +0000230 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000231 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000232 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000233
234 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
235 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
Eric Liu5fb18fe2018-05-17 10:26:23 +0000236 std::error_code getRealPath(const Twine &Path,
237 SmallVectorImpl<char> &Output) const override;
Jonas Devliegherefc514902018-10-10 13:27:25 +0000238
Eric Liucea78e32018-09-05 09:45:27 +0000239private:
240 mutable std::mutex CWDMutex;
241 mutable std::string CWDCache;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000242};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000243
244} // namespace
Ben Langmuirc8130a72014-02-20 21:59:23 +0000245
246ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
247 sys::fs::file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000248 if (std::error_code EC = sys::fs::status(Path, RealStatus))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000249 return EC;
Jordan Rupprechta8fb7292018-07-24 20:28:07 +0000250 return Status::copyWithNewName(RealStatus, Path.str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000251}
252
Benjamin Kramera8857962014-10-26 22:44:13 +0000253ErrorOr<std::unique_ptr<File>>
254RealFileSystem::openFileForRead(const Twine &Name) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000255 int FD;
Taewook Ohf42103c2016-06-13 20:40:21 +0000256 SmallString<256> RealName;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000257 if (std::error_code EC =
258 sys::fs::openFileForRead(Name, FD, sys::fs::OF_None, &RealName))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000259 return EC;
Taewook Ohf42103c2016-06-13 20:40:21 +0000260 return std::unique_ptr<File>(new RealFile(FD, Name.str(), RealName.str()));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000261}
262
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000263llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
Eric Liucea78e32018-09-05 09:45:27 +0000264 std::lock_guard<std::mutex> Lock(CWDMutex);
265 if (!CWDCache.empty())
266 return CWDCache;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000267 SmallString<256> Dir;
268 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
269 return EC;
Eric Liucea78e32018-09-05 09:45:27 +0000270 CWDCache = Dir.str();
271 return CWDCache;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000272}
273
274std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
275 // FIXME: chdir is thread hostile; on the other hand, creating the same
276 // behavior as chdir is complex: chdir resolves the path once, thus
277 // guaranteeing that all subsequent relative path operations work
278 // on the same path the original chdir resulted in. This makes a
279 // difference for example on network filesystems, where symlinks might be
280 // switched during runtime of the tool. Fixing this depends on having a
281 // file system abstraction that allows openat() style interactions.
Eric Liucea78e32018-09-05 09:45:27 +0000282 if (auto EC = llvm::sys::fs::set_current_path(Path))
283 return EC;
284
285 // Invalidate cache.
286 std::lock_guard<std::mutex> Lock(CWDMutex);
287 CWDCache.clear();
288 return std::error_code();
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000289}
290
Eric Liu5fb18fe2018-05-17 10:26:23 +0000291std::error_code
292RealFileSystem::getRealPath(const Twine &Path,
293 SmallVectorImpl<char> &Output) const {
294 return llvm::sys::fs::real_path(Path, Output);
295}
296
Ben Langmuirc8130a72014-02-20 21:59:23 +0000297IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
298 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
299 return FS;
300}
301
Ben Langmuir740812b2014-06-24 19:37:16 +0000302namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000303
Jonas Devliegherefc514902018-10-10 13:27:25 +0000304class RealFSDirIter : public llvm::vfs::detail::DirIterImpl {
Ben Langmuir740812b2014-06-24 19:37:16 +0000305 llvm::sys::fs::directory_iterator Iter;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000306
Ben Langmuir740812b2014-06-24 19:37:16 +0000307public:
Juergen Ributzka4a259562017-03-10 21:23:29 +0000308 RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) {
Sam McCall0ae00562018-09-14 12:47:38 +0000309 if (Iter != llvm::sys::fs::directory_iterator())
310 CurrentEntry = directory_entry(Iter->path(), Iter->type());
Ben Langmuir740812b2014-06-24 19:37:16 +0000311 }
312
313 std::error_code increment() override {
314 std::error_code EC;
315 Iter.increment(EC);
Sam McCall0ae00562018-09-14 12:47:38 +0000316 CurrentEntry = (Iter == llvm::sys::fs::directory_iterator())
317 ? directory_entry()
318 : directory_entry(Iter->path(), Iter->type());
Ben Langmuir740812b2014-06-24 19:37:16 +0000319 return EC;
320 }
321};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000322
323} // namespace
Ben Langmuir740812b2014-06-24 19:37:16 +0000324
325directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
326 std::error_code &EC) {
327 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
328}
329
Ben Langmuirc8130a72014-02-20 21:59:23 +0000330//===-----------------------------------------------------------------------===/
331// OverlayFileSystem implementation
332//===-----------------------------------------------------------------------===/
Eugene Zelenko5a520112018-03-28 22:09:09 +0000333
Ben Langmuirc8130a72014-02-20 21:59:23 +0000334OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000335 FSList.push_back(std::move(BaseFS));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000336}
337
338void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
339 FSList.push_back(FS);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000340 // Synchronize added file systems by duplicating the working directory from
341 // the first one in the list.
342 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000343}
344
345ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
346 // FIXME: handle symlinks that cross file systems
347 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
348 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000349 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000350 return Status;
351 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000352 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000353}
354
Benjamin Kramera8857962014-10-26 22:44:13 +0000355ErrorOr<std::unique_ptr<File>>
356OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000357 // FIXME: handle symlinks that cross file systems
358 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000359 auto Result = (*I)->openFileForRead(Path);
360 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
361 return Result;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000362 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000363 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000364}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000365
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000366llvm::ErrorOr<std::string>
367OverlayFileSystem::getCurrentWorkingDirectory() const {
368 // All file systems are synchronized, just take the first working directory.
369 return FSList.front()->getCurrentWorkingDirectory();
370}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000371
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000372std::error_code
373OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
374 for (auto &FS : FSList)
375 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
376 return EC;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000377 return {};
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000378}
379
Eric Liua840a462018-05-18 13:22:49 +0000380std::error_code
381OverlayFileSystem::getRealPath(const Twine &Path,
382 SmallVectorImpl<char> &Output) const {
383 for (auto &FS : FSList)
384 if (FS->exists(Path))
385 return FS->getRealPath(Path, Output);
386 return errc::no_such_file_or_directory;
387}
388
Jonas Devliegherefc514902018-10-10 13:27:25 +0000389llvm::vfs::detail::DirIterImpl::~DirIterImpl() = default;
Ben Langmuir740812b2014-06-24 19:37:16 +0000390
391namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000392
Jonas Devliegherefc514902018-10-10 13:27:25 +0000393class OverlayFSDirIterImpl : public llvm::vfs::detail::DirIterImpl {
Ben Langmuir740812b2014-06-24 19:37:16 +0000394 OverlayFileSystem &Overlays;
395 std::string Path;
396 OverlayFileSystem::iterator CurrentFS;
397 directory_iterator CurrentDirIter;
398 llvm::StringSet<> SeenNames;
399
400 std::error_code incrementFS() {
401 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
402 ++CurrentFS;
403 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
404 std::error_code EC;
405 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
406 if (EC && EC != errc::no_such_file_or_directory)
407 return EC;
408 if (CurrentDirIter != directory_iterator())
409 break; // found
410 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000411 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +0000412 }
413
414 std::error_code incrementDirIter(bool IsFirstTime) {
415 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
416 "incrementing past end");
417 std::error_code EC;
418 if (!IsFirstTime)
419 CurrentDirIter.increment(EC);
420 if (!EC && CurrentDirIter == directory_iterator())
421 EC = incrementFS();
422 return EC;
423 }
424
425 std::error_code incrementImpl(bool IsFirstTime) {
426 while (true) {
427 std::error_code EC = incrementDirIter(IsFirstTime);
428 if (EC || CurrentDirIter == directory_iterator()) {
Sam McCall0ae00562018-09-14 12:47:38 +0000429 CurrentEntry = directory_entry();
Ben Langmuir740812b2014-06-24 19:37:16 +0000430 return EC;
431 }
432 CurrentEntry = *CurrentDirIter;
Sam McCall0ae00562018-09-14 12:47:38 +0000433 StringRef Name = llvm::sys::path::filename(CurrentEntry.path());
David Blaikie61b86d42014-11-19 02:56:13 +0000434 if (SeenNames.insert(Name).second)
Ben Langmuir740812b2014-06-24 19:37:16 +0000435 return EC; // name not seen before
436 }
437 llvm_unreachable("returned above");
438 }
439
440public:
441 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
442 std::error_code &EC)
443 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
444 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
445 EC = incrementImpl(true);
446 }
447
448 std::error_code increment() override { return incrementImpl(false); }
449};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000450
451} // namespace
Ben Langmuir740812b2014-06-24 19:37:16 +0000452
453directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
454 std::error_code &EC) {
455 return directory_iterator(
456 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
457}
458
Jonas Devliegherefc514902018-10-10 13:27:25 +0000459namespace llvm {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000460namespace vfs {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000461
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000462namespace detail {
463
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000464enum InMemoryNodeKind { IME_File, IME_Directory, IME_HardLink };
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000465
466/// The in memory file system is a tree of Nodes. Every node can either be a
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000467/// file , hardlink or a directory.
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000468class InMemoryNode {
Eric Liub71e6f42018-07-11 18:43:07 +0000469 InMemoryNodeKind Kind;
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000470 std::string FileName;
Simon Marchiddbabc62018-08-06 21:48:20 +0000471
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000472public:
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000473 InMemoryNode(llvm::StringRef FileName, InMemoryNodeKind Kind)
474 : Kind(Kind), FileName(llvm::sys::path::filename(FileName)) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000475 virtual ~InMemoryNode() = default;
476
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000477 /// Get the filename of this node (the name without the directory part).
478 StringRef getFileName() const { return FileName; }
479 InMemoryNodeKind getKind() const { return Kind; }
480 virtual std::string toString(unsigned Indent) const = 0;
481};
482
483class InMemoryFile : public InMemoryNode {
484 Status Stat;
485 std::unique_ptr<llvm::MemoryBuffer> Buffer;
486
487public:
488 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
489 : InMemoryNode(Stat.getName(), IME_File), Stat(std::move(Stat)),
490 Buffer(std::move(Buffer)) {}
491
Simon Marchiddbabc62018-08-06 21:48:20 +0000492 /// Return the \p Status for this node. \p RequestedName should be the name
493 /// through which the caller referred to this node. It will override
494 /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
495 Status getStatus(StringRef RequestedName) const {
496 return Status::copyWithNewName(Stat, RequestedName);
497 }
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000498 llvm::MemoryBuffer *getBuffer() const { return Buffer.get(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000499
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000500 std::string toString(unsigned Indent) const override {
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000501 return (std::string(Indent, ' ') + Stat.getName() + "\n").str();
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000502 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000503
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000504 static bool classof(const InMemoryNode *N) {
505 return N->getKind() == IME_File;
506 }
507};
508
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000509namespace {
510
511class InMemoryHardLink : public InMemoryNode {
512 const InMemoryFile &ResolvedFile;
513
514public:
515 InMemoryHardLink(StringRef Path, const InMemoryFile &ResolvedFile)
516 : InMemoryNode(Path, IME_HardLink), ResolvedFile(ResolvedFile) {}
517 const InMemoryFile &getResolvedFile() const { return ResolvedFile; }
518
519 std::string toString(unsigned Indent) const override {
520 return std::string(Indent, ' ') + "HardLink to -> " +
521 ResolvedFile.toString(0);
522 }
523
524 static bool classof(const InMemoryNode *N) {
525 return N->getKind() == IME_HardLink;
526 }
527};
528
Simon Marchiddbabc62018-08-06 21:48:20 +0000529/// Adapt a InMemoryFile for VFS' File interface. The goal is to make
530/// \p InMemoryFileAdaptor mimic as much as possible the behavior of
531/// \p RealFile.
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000532class InMemoryFileAdaptor : public File {
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000533 const InMemoryFile &Node;
Simon Marchiddbabc62018-08-06 21:48:20 +0000534 /// The name to use when returning a Status for this file.
535 std::string RequestedName;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000536
Simon Marchia37ef292018-07-11 14:08:17 +0000537public:
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000538 explicit InMemoryFileAdaptor(const InMemoryFile &Node,
539 std::string RequestedName)
Simon Marchiddbabc62018-08-06 21:48:20 +0000540 : Node(Node), RequestedName(std::move(RequestedName)) {}
Simon Marchia37ef292018-07-11 14:08:17 +0000541
Simon Marchiddbabc62018-08-06 21:48:20 +0000542 llvm::ErrorOr<Status> status() override {
543 return Node.getStatus(RequestedName);
544 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000545
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000546 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +0000547 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
548 bool IsVolatile) override {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000549 llvm::MemoryBuffer *Buf = Node.getBuffer();
550 return llvm::MemoryBuffer::getMemBuffer(
551 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
552 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000553
554 std::error_code close() override { return {}; }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000555};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000556} // namespace
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000557
558class InMemoryDirectory : public InMemoryNode {
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000559 Status Stat;
Eric Liu495847a2018-09-24 14:52:11 +0000560 llvm::StringMap<std::unique_ptr<InMemoryNode>> Entries;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000561
562public:
563 InMemoryDirectory(Status Stat)
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000564 : InMemoryNode(Stat.getName(), IME_Directory), Stat(std::move(Stat)) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000565
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000566 /// Return the \p Status for this node. \p RequestedName should be the name
567 /// through which the caller referred to this node. It will override
568 /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
569 Status getStatus(StringRef RequestedName) const {
570 return Status::copyWithNewName(Stat, RequestedName);
571 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000572 InMemoryNode *getChild(StringRef Name) {
573 auto I = Entries.find(Name);
574 if (I != Entries.end())
575 return I->second.get();
576 return nullptr;
577 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000578
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000579 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
580 return Entries.insert(make_pair(Name, std::move(Child)))
581 .first->second.get();
582 }
583
Eugene Zelenko5a520112018-03-28 22:09:09 +0000584 using const_iterator = decltype(Entries)::const_iterator;
585
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000586 const_iterator begin() const { return Entries.begin(); }
587 const_iterator end() const { return Entries.end(); }
588
589 std::string toString(unsigned Indent) const override {
590 std::string Result =
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000591 (std::string(Indent, ' ') + Stat.getName() + "\n").str();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000592 for (const auto &Entry : Entries)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000593 Result += Entry.second->toString(Indent + 2);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000594 return Result;
595 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000596
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000597 static bool classof(const InMemoryNode *N) {
598 return N->getKind() == IME_Directory;
599 }
600};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000601
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000602namespace {
603Status getNodeStatus(const InMemoryNode *Node, StringRef RequestedName) {
604 if (auto Dir = dyn_cast<detail::InMemoryDirectory>(Node))
605 return Dir->getStatus(RequestedName);
606 if (auto File = dyn_cast<detail::InMemoryFile>(Node))
607 return File->getStatus(RequestedName);
608 if (auto Link = dyn_cast<detail::InMemoryHardLink>(Node))
609 return Link->getResolvedFile().getStatus(RequestedName);
610 llvm_unreachable("Unknown node type");
611}
612} // namespace
Eugene Zelenko5a520112018-03-28 22:09:09 +0000613} // namespace detail
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000614
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000615InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000616 : Root(new detail::InMemoryDirectory(
Pavel Labathac71c8e2016-11-09 10:52:22 +0000617 Status("", getNextVirtualUniqueID(), llvm::sys::TimePoint<>(), 0, 0,
618 0, llvm::sys::fs::file_type::directory_file,
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000619 llvm::sys::fs::perms::all_all))),
620 UseNormalizedPaths(UseNormalizedPaths) {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000621
Eugene Zelenko5a520112018-03-28 22:09:09 +0000622InMemoryFileSystem::~InMemoryFileSystem() = default;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000623
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000624std::string InMemoryFileSystem::toString() const {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000625 return Root->toString(/*Indent=*/0);
626}
627
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000628bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000629 std::unique_ptr<llvm::MemoryBuffer> Buffer,
630 Optional<uint32_t> User,
631 Optional<uint32_t> Group,
632 Optional<llvm::sys::fs::file_type> Type,
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000633 Optional<llvm::sys::fs::perms> Perms,
634 const detail::InMemoryFile *HardLinkTarget) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000635 SmallString<128> Path;
636 P.toVector(Path);
637
638 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000639 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000640 assert(!EC);
641 (void)EC;
642
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000643 if (useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000644 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000645
646 if (Path.empty())
647 return false;
648
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000649 detail::InMemoryDirectory *Dir = Root.get();
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000650 auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path);
651 const auto ResolvedUser = User.getValueOr(0);
652 const auto ResolvedGroup = Group.getValueOr(0);
653 const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file);
654 const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all);
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000655 assert(!(HardLinkTarget && Buffer) && "HardLink cannot have a buffer");
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000656 // Any intermediate directories we create should be accessible by
657 // the owner, even if Perms says otherwise for the final path.
658 const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000659 while (true) {
660 StringRef Name = *I;
661 detail::InMemoryNode *Node = Dir->getChild(Name);
662 ++I;
663 if (!Node) {
664 if (I == E) {
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000665 // End of the path.
Ben Hamilton78381012017-11-16 19:34:08 +0000666 std::unique_ptr<detail::InMemoryNode> Child;
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000667 if (HardLinkTarget)
668 Child.reset(new detail::InMemoryHardLink(P.str(), *HardLinkTarget));
669 else {
670 // Create a new file or directory.
671 Status Stat(P.str(), getNextVirtualUniqueID(),
672 llvm::sys::toTimePoint(ModificationTime), ResolvedUser,
673 ResolvedGroup, Buffer->getBufferSize(), ResolvedType,
674 ResolvedPerms);
675 if (ResolvedType == sys::fs::file_type::directory_file) {
676 Child.reset(new detail::InMemoryDirectory(std::move(Stat)));
677 } else {
678 Child.reset(
679 new detail::InMemoryFile(std::move(Stat), std::move(Buffer)));
680 }
Ben Hamilton78381012017-11-16 19:34:08 +0000681 }
682 Dir->addChild(Name, std::move(Child));
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000683 return true;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000684 }
685
686 // Create a new directory. Use the path up to here.
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000687 Status Stat(
688 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000689 getNextVirtualUniqueID(), llvm::sys::toTimePoint(ModificationTime),
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000690 ResolvedUser, ResolvedGroup, 0, sys::fs::file_type::directory_file,
691 NewDirectoryPerms);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000692 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
693 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
694 continue;
695 }
696
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000697 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000698 Dir = NewDir;
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000699 } else {
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000700 assert((isa<detail::InMemoryFile>(Node) ||
701 isa<detail::InMemoryHardLink>(Node)) &&
702 "Must be either file, hardlink or directory!");
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000703
704 // Trying to insert a directory in place of a file.
705 if (I != E)
706 return false;
707
708 // Return false only if the new file is different from the existing one.
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000709 if (auto Link = dyn_cast<detail::InMemoryHardLink>(Node)) {
710 return Link->getResolvedFile().getBuffer()->getBuffer() ==
711 Buffer->getBuffer();
712 }
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000713 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
714 Buffer->getBuffer();
715 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000716 }
717}
718
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000719bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
720 std::unique_ptr<llvm::MemoryBuffer> Buffer,
721 Optional<uint32_t> User,
722 Optional<uint32_t> Group,
723 Optional<llvm::sys::fs::file_type> Type,
724 Optional<llvm::sys::fs::perms> Perms) {
725 return addFile(P, ModificationTime, std::move(Buffer), User, Group, Type,
726 Perms, /*HardLinkTarget=*/nullptr);
727}
728
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000729bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000730 llvm::MemoryBuffer *Buffer,
731 Optional<uint32_t> User,
732 Optional<uint32_t> Group,
733 Optional<llvm::sys::fs::file_type> Type,
734 Optional<llvm::sys::fs::perms> Perms) {
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000735 return addFile(P, ModificationTime,
736 llvm::MemoryBuffer::getMemBuffer(
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000737 Buffer->getBuffer(), Buffer->getBufferIdentifier()),
738 std::move(User), std::move(Group), std::move(Type),
739 std::move(Perms));
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000740}
741
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000742static ErrorOr<const detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000743lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
744 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000745 SmallString<128> Path;
746 P.toVector(Path);
747
748 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000749 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000750 assert(!EC);
751 (void)EC;
752
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000753 if (FS.useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000754 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer4ad1c432015-10-12 13:30:38 +0000755
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000756 if (Path.empty())
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000757 return Dir;
758
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000759 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000760 while (true) {
761 detail::InMemoryNode *Node = Dir->getChild(*I);
762 ++I;
763 if (!Node)
764 return errc::no_such_file_or_directory;
765
766 // Return the file if it's at the end of the path.
767 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
768 if (I == E)
769 return File;
770 return errc::no_such_file_or_directory;
771 }
772
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000773 // If Node is HardLink then return the resolved file.
774 if (auto File = dyn_cast<detail::InMemoryHardLink>(Node)) {
775 if (I == E)
776 return &File->getResolvedFile();
777 return errc::no_such_file_or_directory;
778 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000779 // Traverse directories.
780 Dir = cast<detail::InMemoryDirectory>(Node);
781 if (I == E)
782 return Dir;
783 }
784}
785
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000786bool InMemoryFileSystem::addHardLink(const Twine &FromPath,
787 const Twine &ToPath) {
788 auto FromNode = lookupInMemoryNode(*this, Root.get(), FromPath);
789 auto ToNode = lookupInMemoryNode(*this, Root.get(), ToPath);
790 // FromPath must not have been added before. ToPath must have been added
791 // before. Resolved ToPath must be a File.
792 if (!ToNode || FromNode || !isa<detail::InMemoryFile>(*ToNode))
793 return false;
794 return this->addFile(FromPath, 0, nullptr, None, None, None, None,
795 cast<detail::InMemoryFile>(*ToNode));
796}
797
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000798llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000799 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000800 if (Node)
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000801 return detail::getNodeStatus(*Node, Path.str());
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000802 return Node.getError();
803}
804
805llvm::ErrorOr<std::unique_ptr<File>>
806InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000807 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000808 if (!Node)
809 return Node.getError();
810
811 // When we have a file provide a heap-allocated wrapper for the memory buffer
812 // to match the ownership semantics for File.
813 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
Simon Marchiddbabc62018-08-06 21:48:20 +0000814 return std::unique_ptr<File>(
815 new detail::InMemoryFileAdaptor(*F, Path.str()));
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000816
817 // FIXME: errc::not_a_file?
818 return make_error_code(llvm::errc::invalid_argument);
819}
820
821namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000822
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000823/// Adaptor from InMemoryDir::iterator to directory_iterator.
Jonas Devliegherefc514902018-10-10 13:27:25 +0000824class InMemoryDirIterator : public llvm::vfs::detail::DirIterImpl {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000825 detail::InMemoryDirectory::const_iterator I;
826 detail::InMemoryDirectory::const_iterator E;
Simon Marchiddbabc62018-08-06 21:48:20 +0000827 std::string RequestedDirName;
828
829 void setCurrentEntry() {
830 if (I != E) {
831 SmallString<256> Path(RequestedDirName);
832 llvm::sys::path::append(Path, I->second->getFileName());
Sam McCall0ae00562018-09-14 12:47:38 +0000833 sys::fs::file_type Type;
834 switch (I->second->getKind()) {
Jonas Devliegherefc514902018-10-10 13:27:25 +0000835 case detail::IME_File:
836 case detail::IME_HardLink:
837 Type = sys::fs::file_type::regular_file;
838 break;
839 case detail::IME_Directory:
840 Type = sys::fs::file_type::directory_file;
841 break;
Sam McCall0ae00562018-09-14 12:47:38 +0000842 }
843 CurrentEntry = directory_entry(Path.str(), Type);
Simon Marchiddbabc62018-08-06 21:48:20 +0000844 } else {
845 // When we're at the end, make CurrentEntry invalid and DirIterImpl will
846 // do the rest.
Sam McCall0ae00562018-09-14 12:47:38 +0000847 CurrentEntry = directory_entry();
Simon Marchiddbabc62018-08-06 21:48:20 +0000848 }
849 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000850
851public:
Eugene Zelenko5a520112018-03-28 22:09:09 +0000852 InMemoryDirIterator() = default;
853
Ilya Biryukovd5554c512018-09-04 14:15:53 +0000854 explicit InMemoryDirIterator(const detail::InMemoryDirectory &Dir,
Simon Marchiddbabc62018-08-06 21:48:20 +0000855 std::string RequestedDirName)
856 : I(Dir.begin()), E(Dir.end()),
857 RequestedDirName(std::move(RequestedDirName)) {
858 setCurrentEntry();
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000859 }
860
861 std::error_code increment() override {
862 ++I;
Simon Marchiddbabc62018-08-06 21:48:20 +0000863 setCurrentEntry();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000864 return {};
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000865 }
866};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000867
868} // namespace
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000869
870directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
871 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000872 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000873 if (!Node) {
874 EC = Node.getError();
875 return directory_iterator(std::make_shared<InMemoryDirIterator>());
876 }
877
878 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
Simon Marchiddbabc62018-08-06 21:48:20 +0000879 return directory_iterator(
880 std::make_shared<InMemoryDirIterator>(*DirNode, Dir.str()));
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000881
882 EC = make_error_code(llvm::errc::not_a_directory);
883 return directory_iterator(std::make_shared<InMemoryDirIterator>());
884}
Benjamin Kramere9e76072016-01-09 16:33:16 +0000885
886std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
887 SmallString<128> Path;
888 P.toVector(Path);
889
890 // Fix up relative paths. This just prepends the current working directory.
891 std::error_code EC = makeAbsolute(Path);
892 assert(!EC);
893 (void)EC;
894
895 if (useNormalizedPaths())
896 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
897
898 if (!Path.empty())
899 WorkingDirectory = Path.str();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000900 return {};
Benjamin Kramere9e76072016-01-09 16:33:16 +0000901}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000902
Eric Liu33dd6192018-05-24 11:17:00 +0000903std::error_code
904InMemoryFileSystem::getRealPath(const Twine &Path,
905 SmallVectorImpl<char> &Output) const {
906 auto CWD = getCurrentWorkingDirectory();
907 if (!CWD || CWD->empty())
908 return errc::operation_not_permitted;
909 Path.toVector(Output);
910 if (auto EC = makeAbsolute(Output))
911 return EC;
912 llvm::sys::path::remove_dots(Output, /*remove_dot_dot=*/true);
913 return {};
914}
915
Eugene Zelenko5a520112018-03-28 22:09:09 +0000916} // namespace vfs
Jonas Devliegherefc514902018-10-10 13:27:25 +0000917} // namespace llvm
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000918
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000919//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000920// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000921//===-----------------------------------------------------------------------===/
922
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000923namespace {
924
Jonas Devliegherefc514902018-10-10 13:27:25 +0000925enum EntryKind { EK_Directory, EK_File };
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000926
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000927/// A single file or directory in the VFS.
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000928class Entry {
929 EntryKind Kind;
930 std::string Name;
931
932public:
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000933 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000934 virtual ~Entry() = default;
935
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000936 StringRef getName() const { return Name; }
937 EntryKind getKind() const { return Kind; }
938};
939
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000940class RedirectingDirectoryEntry : public Entry {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000941 std::vector<std::unique_ptr<Entry>> Contents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000942 Status S;
943
944public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000945 RedirectingDirectoryEntry(StringRef Name,
946 std::vector<std::unique_ptr<Entry>> Contents,
947 Status S)
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000948 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000949 S(std::move(S)) {}
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000950 RedirectingDirectoryEntry(StringRef Name, Status S)
951 : Entry(EK_Directory, Name), S(std::move(S)) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000952
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000953 Status getStatus() { return S; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000954
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000955 void addContent(std::unique_ptr<Entry> Content) {
956 Contents.push_back(std::move(Content));
957 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000958
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000959 Entry *getLastContent() const { return Contents.back().get(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000960
961 using iterator = decltype(Contents)::iterator;
962
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000963 iterator contents_begin() { return Contents.begin(); }
964 iterator contents_end() { return Contents.end(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000965
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000966 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
967};
968
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000969class RedirectingFileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000970public:
Jonas Devliegherefc514902018-10-10 13:27:25 +0000971 enum NameKind { NK_NotSet, NK_External, NK_Virtual };
Eugene Zelenko5a520112018-03-28 22:09:09 +0000972
Ben Langmuirb59cf672014-02-27 00:25:12 +0000973private:
974 std::string ExternalContentsPath;
975 NameKind UseName;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000976
Ben Langmuirb59cf672014-02-27 00:25:12 +0000977public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000978 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
979 NameKind UseName)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000980 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
981 UseName(UseName) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000982
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000983 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000984
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000985 /// whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000986 bool useExternalName(bool GlobalUseExternalName) const {
987 return UseName == NK_NotSet ? GlobalUseExternalName
988 : (UseName == NK_External);
989 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000990
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000991 NameKind getUseName() const { return UseName; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000992
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000993 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
994};
995
Volodymyr Sapsai91e13162018-10-26 22:14:33 +0000996// FIXME: reuse implementation common with OverlayFSDirIterImpl as these
997// iterators are conceptually similar.
Jonas Devliegherefc514902018-10-10 13:27:25 +0000998class VFSFromYamlDirIterImpl : public llvm::vfs::detail::DirIterImpl {
Ben Langmuir740812b2014-06-24 19:37:16 +0000999 std::string Dir;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001000 RedirectingDirectoryEntry::iterator Current, End;
1001
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001002 // To handle 'fallthrough' mode we need to iterate at first through
1003 // RedirectingDirectoryEntry and then through ExternalFS. These operations are
1004 // done sequentially, we just need to keep a track of what kind of iteration
1005 // we are currently performing.
1006
1007 /// Flag telling if we should iterate through ExternalFS or stop at the last
1008 /// RedirectingDirectoryEntry::iterator.
1009 bool IterateExternalFS;
1010 /// Flag telling if we have switched to iterating through ExternalFS.
1011 bool IsExternalFSCurrent = false;
1012 FileSystem &ExternalFS;
1013 directory_iterator ExternalDirIter;
1014 llvm::StringSet<> SeenNames;
1015
1016 /// To combine multiple iterations, different methods are responsible for
1017 /// different iteration steps.
1018 /// @{
1019
1020 /// Responsible for dispatching between RedirectingDirectoryEntry iteration
1021 /// and ExternalFS iteration.
1022 std::error_code incrementImpl(bool IsFirstTime);
1023 /// Responsible for RedirectingDirectoryEntry iteration.
1024 std::error_code incrementContent(bool IsFirstTime);
1025 /// Responsible for ExternalFS iteration.
1026 std::error_code incrementExternal();
1027 /// @}
Volodymyr Sapsai3aa88b52018-08-07 23:00:40 +00001028
Ben Langmuir740812b2014-06-24 19:37:16 +00001029public:
Sam McCall0ae00562018-09-14 12:47:38 +00001030 VFSFromYamlDirIterImpl(const Twine &Path,
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001031 RedirectingDirectoryEntry::iterator Begin,
1032 RedirectingDirectoryEntry::iterator End,
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001033 bool IterateExternalFS, FileSystem &ExternalFS,
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001034 std::error_code &EC);
Eugene Zelenko5a520112018-03-28 22:09:09 +00001035
Ben Langmuir740812b2014-06-24 19:37:16 +00001036 std::error_code increment() override;
1037};
1038
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001039/// A virtual file system parsed from a YAML file.
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001040///
1041/// Currently, this class allows creating virtual directories and mapping
1042/// virtual file paths to existing external files, available in \c ExternalFS.
1043///
1044/// The basic structure of the parsed file is:
1045/// \verbatim
1046/// {
1047/// 'version': <version number>,
1048/// <optional configuration>
1049/// 'roots': [
1050/// <directory entries>
1051/// ]
1052/// }
1053/// \endverbatim
1054///
1055/// All configuration options are optional.
1056/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +00001057/// 'use-external-names': <boolean, default=true>
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001058/// 'overlay-relative': <boolean, default=false>
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001059/// 'fallthrough': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001060///
1061/// Virtual directories are represented as
1062/// \verbatim
1063/// {
1064/// 'type': 'directory',
1065/// 'name': <string>,
1066/// 'contents': [ <file or directory entries> ]
1067/// }
1068/// \endverbatim
1069///
1070/// The default attributes for virtual directories are:
1071/// \verbatim
1072/// MTime = now() when created
1073/// Perms = 0777
1074/// User = Group = 0
1075/// Size = 0
1076/// UniqueID = unspecified unique value
1077/// \endverbatim
1078///
1079/// Re-mapped files are represented as
1080/// \verbatim
1081/// {
1082/// 'type': 'file',
1083/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +00001084/// 'use-external-name': <boolean> # Optional
Volodymyr Sapsaic1bf7aa2018-08-08 01:28:37 +00001085/// 'external-contents': <path to external file>
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001086/// }
1087/// \endverbatim
1088///
1089/// and inherit their attributes from the external contents.
1090///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001091/// In both cases, the 'name' field may contain multiple path components (e.g.
1092/// /path/to/file). However, any directory that contains more than one child
1093/// must be uniquely represented by a directory entry.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001094class RedirectingFileSystem : public vfs::FileSystem {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001095 friend class RedirectingFileSystemParser;
1096
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001097 /// The root(s) of the virtual file system.
1098 std::vector<std::unique_ptr<Entry>> Roots;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001099
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001100 /// The file system to use for external references.
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001101 IntrusiveRefCntPtr<FileSystem> ExternalFS;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001102
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001103 /// If IsRelativeOverlay is set, this represents the directory
1104 /// path that should be prefixed to each 'external-contents' entry
1105 /// when reading from YAML files.
1106 std::string ExternalContentsPrefixDir;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001107
1108 /// @name Configuration
1109 /// @{
1110
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001111 /// Whether to perform case-sensitive comparisons.
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001112 ///
1113 /// Currently, case-insensitive matching only works correctly with ASCII.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +00001114 bool CaseSensitive = true;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001115
Volodymyr Sapsaic1bf7aa2018-08-08 01:28:37 +00001116 /// IsRelativeOverlay marks whether a ExternalContentsPrefixDir path must
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001117 /// be prefixed in every 'external-contents' when reading from YAML files.
1118 bool IsRelativeOverlay = false;
1119
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001120 /// Whether to use to use the value of 'external-contents' for the
Ben Langmuirb59cf672014-02-27 00:25:12 +00001121 /// names of files. This global value is overridable on a per-file basis.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +00001122 bool UseExternalNames = true;
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001123
1124 /// Whether to attempt a file lookup in external file system after it wasn't
1125 /// found in VFS.
1126 bool IsFallthrough = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001127 /// @}
1128
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001129 /// Virtual file paths and external files could be canonicalized without "..",
1130 /// "." and "./" in their paths. FIXME: some unittests currently fail on
1131 /// win32 when using remove_dots and remove_leading_dotslash on paths.
1132 bool UseCanonicalizedPaths =
Nico Weber1865df42018-04-27 19:11:14 +00001133#ifdef _WIN32
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001134 false;
1135#else
1136 true;
1137#endif
1138
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001139private:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001140 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +00001141 : ExternalFS(std::move(ExternalFS)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001142
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001143 /// Looks up the path <tt>[Start, End)</tt> in \p From, possibly
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001144 /// recursing into the contents of \p From if it is a directory.
1145 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
1146 sys::path::const_iterator End, Entry *From);
1147
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001148 /// Get the status of a given an \c Entry.
Ben Langmuir740812b2014-06-24 19:37:16 +00001149 ErrorOr<Status> status(const Twine &Path, Entry *E);
1150
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001151public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001152 /// Looks up \p Path in \c Roots.
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001153 ErrorOr<Entry *> lookupPath(const Twine &Path);
1154
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001155 /// Parses \p Buffer, which is expected to be in YAML format and
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001156 /// returns a virtual file system representing its contents.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001157 static RedirectingFileSystem *
1158 create(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001159 SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
1160 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001161
Craig Toppera798a9d2014-03-02 09:32:10 +00001162 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +00001163 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +00001164
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001165 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
1166 return ExternalFS->getCurrentWorkingDirectory();
1167 }
Eugene Zelenko5a520112018-03-28 22:09:09 +00001168
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001169 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
1170 return ExternalFS->setCurrentWorkingDirectory(Path);
1171 }
1172
Jonas Devliegherefc514902018-10-10 13:27:25 +00001173 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override {
Ben Langmuir740812b2014-06-24 19:37:16 +00001174 ErrorOr<Entry *> E = lookupPath(Dir);
1175 if (!E) {
1176 EC = E.getError();
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001177 if (IsFallthrough && EC == errc::no_such_file_or_directory)
1178 return ExternalFS->dir_begin(Dir, EC);
Eugene Zelenko5a520112018-03-28 22:09:09 +00001179 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001180 }
1181 ErrorOr<Status> S = status(Dir, *E);
1182 if (!S) {
1183 EC = S.getError();
Eugene Zelenko5a520112018-03-28 22:09:09 +00001184 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001185 }
1186 if (!S->isDirectory()) {
1187 EC = std::error_code(static_cast<int>(errc::not_a_directory),
1188 std::system_category());
Eugene Zelenko5a520112018-03-28 22:09:09 +00001189 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001190 }
1191
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001192 auto *D = cast<RedirectingDirectoryEntry>(*E);
Sam McCall0ae00562018-09-14 12:47:38 +00001193 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001194 Dir, D->contents_begin(), D->contents_end(),
1195 /*IterateExternalFS=*/IsFallthrough, *ExternalFS, EC));
Ben Langmuir740812b2014-06-24 19:37:16 +00001196 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001197
1198 void setExternalContentsPrefixDir(StringRef PrefixDir) {
1199 ExternalContentsPrefixDir = PrefixDir.str();
1200 }
1201
1202 StringRef getExternalContentsPrefixDir() const {
1203 return ExternalContentsPrefixDir;
1204 }
1205
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001206#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Jonas Devliegherefc514902018-10-10 13:27:25 +00001207 LLVM_DUMP_METHOD void dump() const {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001208 for (const auto &Root : Roots)
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001209 dumpEntry(Root.get());
1210 }
1211
Jonas Devliegherefc514902018-10-10 13:27:25 +00001212 LLVM_DUMP_METHOD void dumpEntry(Entry *E, int NumSpaces = 0) const {
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001213 StringRef Name = E->getName();
1214 for (int i = 0, e = NumSpaces; i < e; ++i)
1215 dbgs() << " ";
Jonas Devliegherefc514902018-10-10 13:27:25 +00001216 dbgs() << "'" << Name.str().c_str() << "'"
1217 << "\n";
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001218
1219 if (E->getKind() == EK_Directory) {
1220 auto *DE = dyn_cast<RedirectingDirectoryEntry>(E);
1221 assert(DE && "Should be a directory");
1222
1223 for (std::unique_ptr<Entry> &SubEntry :
1224 llvm::make_range(DE->contents_begin(), DE->contents_end()))
Jonas Devliegherefc514902018-10-10 13:27:25 +00001225 dumpEntry(SubEntry.get(), NumSpaces + 2);
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001226 }
1227 }
1228#endif
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001229};
1230
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001231/// A helper class to hold the common YAML parsing state.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001232class RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001233 yaml::Stream &Stream;
1234
Jonas Devliegherefc514902018-10-10 13:27:25 +00001235 void error(yaml::Node *N, const Twine &Msg) { Stream.printError(N, Msg); }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001236
1237 // false on error
1238 bool parseScalarString(yaml::Node *N, StringRef &Result,
1239 SmallVectorImpl<char> &Storage) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001240 const auto *S = dyn_cast<yaml::ScalarNode>(N);
1241
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001242 if (!S) {
1243 error(N, "expected string");
1244 return false;
1245 }
1246 Result = S->getValue(Storage);
1247 return true;
1248 }
1249
1250 // false on error
1251 bool parseScalarBool(yaml::Node *N, bool &Result) {
1252 SmallString<5> Storage;
1253 StringRef Value;
1254 if (!parseScalarString(N, Value, Storage))
1255 return false;
1256
1257 if (Value.equals_lower("true") || Value.equals_lower("on") ||
1258 Value.equals_lower("yes") || Value == "1") {
1259 Result = true;
1260 return true;
1261 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
1262 Value.equals_lower("no") || Value == "0") {
1263 Result = false;
1264 return true;
1265 }
1266
1267 error(N, "expected boolean value");
1268 return false;
1269 }
1270
1271 struct KeyStatus {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001272 bool Required;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001273 bool Seen = false;
1274
1275 KeyStatus(bool Required = false) : Required(Required) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001276 };
Eugene Zelenko5a520112018-03-28 22:09:09 +00001277
1278 using KeyStatusPair = std::pair<StringRef, KeyStatus>;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001279
1280 // false on error
1281 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1282 DenseMap<StringRef, KeyStatus> &Keys) {
1283 if (!Keys.count(Key)) {
1284 error(KeyNode, "unknown key");
1285 return false;
1286 }
1287 KeyStatus &S = Keys[Key];
1288 if (S.Seen) {
1289 error(KeyNode, Twine("duplicate key '") + Key + "'");
1290 return false;
1291 }
1292 S.Seen = true;
1293 return true;
1294 }
1295
1296 // false on error
1297 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001298 for (const auto &I : Keys) {
1299 if (I.second.Required && !I.second.Seen) {
1300 error(Obj, Twine("missing key '") + I.first + "'");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001301 return false;
1302 }
1303 }
1304 return true;
1305 }
1306
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001307 Entry *lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1308 Entry *ParentEntry = nullptr) {
1309 if (!ParentEntry) { // Look for a existent root
Eugene Zelenko5a520112018-03-28 22:09:09 +00001310 for (const auto &Root : FS->Roots) {
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001311 if (Name.equals(Root->getName())) {
1312 ParentEntry = Root.get();
1313 return ParentEntry;
1314 }
1315 }
1316 } else { // Advance to the next component
1317 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1318 for (std::unique_ptr<Entry> &Content :
1319 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1320 auto *DirContent = dyn_cast<RedirectingDirectoryEntry>(Content.get());
1321 if (DirContent && Name.equals(Content->getName()))
1322 return DirContent;
1323 }
1324 }
1325
1326 // ... or create a new one
1327 std::unique_ptr<Entry> E = llvm::make_unique<RedirectingDirectoryEntry>(
Pavel Labathac71c8e2016-11-09 10:52:22 +00001328 Name,
1329 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1330 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001331
1332 if (!ParentEntry) { // Add a new root to the overlay
1333 FS->Roots.push_back(std::move(E));
1334 ParentEntry = FS->Roots.back().get();
1335 return ParentEntry;
1336 }
1337
1338 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1339 DE->addContent(std::move(E));
1340 return DE->getLastContent();
1341 }
1342
1343 void uniqueOverlayTree(RedirectingFileSystem *FS, Entry *SrcE,
1344 Entry *NewParentE = nullptr) {
1345 StringRef Name = SrcE->getName();
1346 switch (SrcE->getKind()) {
1347 case EK_Directory: {
1348 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1349 assert(DE && "Must be a directory");
1350 // Empty directories could be present in the YAML as a way to
1351 // describe a file for a current directory after some of its subdir
1352 // is parsed. This only leads to redundant walks, ignore it.
1353 if (!Name.empty())
1354 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1355 for (std::unique_ptr<Entry> &SubEntry :
1356 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1357 uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1358 break;
1359 }
1360 case EK_File: {
1361 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1362 assert(FE && "Must be a file");
1363 assert(NewParentE && "Parent entry must exist");
1364 auto *DE = dyn_cast<RedirectingDirectoryEntry>(NewParentE);
1365 DE->addContent(llvm::make_unique<RedirectingFileEntry>(
1366 Name, FE->getExternalContentsPath(), FE->getUseName()));
1367 break;
1368 }
1369 }
1370 }
1371
Volodymyr Sapsai3b2f6a42018-08-07 19:05:41 +00001372 std::unique_ptr<Entry> parseEntry(yaml::Node *N, RedirectingFileSystem *FS,
1373 bool IsRootEntry) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001374 auto *M = dyn_cast<yaml::MappingNode>(N);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001375 if (!M) {
1376 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +00001377 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001378 }
1379
1380 KeyStatusPair Fields[] = {
Jonas Devliegherefc514902018-10-10 13:27:25 +00001381 KeyStatusPair("name", true),
1382 KeyStatusPair("type", true),
1383 KeyStatusPair("contents", false),
1384 KeyStatusPair("external-contents", false),
1385 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001386 };
1387
Craig Topperac67c052015-11-30 03:11:10 +00001388 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001389
1390 bool HasContents = false; // external or otherwise
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001391 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001392 std::string ExternalContentsPath;
1393 std::string Name;
Volodymyr Sapsai3b2f6a42018-08-07 19:05:41 +00001394 yaml::Node *NameValueNode;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001395 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001396 EntryKind Kind;
1397
Eugene Zelenko5a520112018-03-28 22:09:09 +00001398 for (auto &I : *M) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001399 StringRef Key;
1400 // Reuse the buffer for key and value, since we don't look at key after
1401 // parsing value.
1402 SmallString<256> Buffer;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001403 if (!parseScalarString(I.getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001404 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001405
Eugene Zelenko5a520112018-03-28 22:09:09 +00001406 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001407 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001408
1409 StringRef Value;
1410 if (Key == "name") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001411 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001412 return nullptr;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001413
Volodymyr Sapsai3b2f6a42018-08-07 19:05:41 +00001414 NameValueNode = I.getValue();
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001415 if (FS->UseCanonicalizedPaths) {
1416 SmallString<256> Path(Value);
1417 // Guarantee that old YAML files containing paths with ".." and "."
1418 // are properly canonicalized before read into the VFS.
1419 Path = sys::path::remove_leading_dotslash(Path);
1420 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1421 Name = Path.str();
1422 } else {
1423 Name = Value;
1424 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001425 } else if (Key == "type") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001426 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001427 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001428 if (Value == "file")
1429 Kind = EK_File;
1430 else if (Value == "directory")
1431 Kind = EK_Directory;
1432 else {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001433 error(I.getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +00001434 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001435 }
1436 } else if (Key == "contents") {
1437 if (HasContents) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001438 error(I.getKey(),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001439 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001440 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001441 }
1442 HasContents = true;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001443 auto *Contents = dyn_cast<yaml::SequenceNode>(I.getValue());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001444 if (!Contents) {
1445 // FIXME: this is only for directories, what about files?
Eugene Zelenko5a520112018-03-28 22:09:09 +00001446 error(I.getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +00001447 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001448 }
1449
Eugene Zelenko5a520112018-03-28 22:09:09 +00001450 for (auto &I : *Contents) {
Volodymyr Sapsai3b2f6a42018-08-07 19:05:41 +00001451 if (std::unique_ptr<Entry> E =
1452 parseEntry(&I, FS, /*IsRootEntry*/ false))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001453 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001454 else
Craig Topperf1186c52014-05-08 06:41:40 +00001455 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001456 }
1457 } else if (Key == "external-contents") {
1458 if (HasContents) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001459 error(I.getKey(),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001460 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001461 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001462 }
1463 HasContents = true;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001464 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001465 return nullptr;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001466
1467 SmallString<256> FullPath;
1468 if (FS->IsRelativeOverlay) {
1469 FullPath = FS->getExternalContentsPrefixDir();
1470 assert(!FullPath.empty() &&
1471 "External contents prefix directory must exist");
1472 llvm::sys::path::append(FullPath, Value);
1473 } else {
1474 FullPath = Value;
1475 }
1476
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001477 if (FS->UseCanonicalizedPaths) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001478 // Guarantee that old YAML files containing paths with ".." and "."
1479 // are properly canonicalized before read into the VFS.
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001480 FullPath = sys::path::remove_leading_dotslash(FullPath);
1481 sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001482 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001483 ExternalContentsPath = FullPath.str();
Ben Langmuirb59cf672014-02-27 00:25:12 +00001484 } else if (Key == "use-external-name") {
1485 bool Val;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001486 if (!parseScalarBool(I.getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001487 return nullptr;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001488 UseExternalName = Val ? RedirectingFileEntry::NK_External
1489 : RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001490 } else {
1491 llvm_unreachable("key missing from Keys");
1492 }
1493 }
1494
1495 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001496 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001497
1498 // check for missing keys
1499 if (!HasContents) {
1500 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001501 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001502 }
1503 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001504 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001505
Ben Langmuirb59cf672014-02-27 00:25:12 +00001506 // check invalid configuration
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001507 if (Kind == EK_Directory &&
1508 UseExternalName != RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001509 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001510 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001511 }
1512
Volodymyr Sapsai3b2f6a42018-08-07 19:05:41 +00001513 if (IsRootEntry && !sys::path::is_absolute(Name)) {
1514 assert(NameValueNode && "Name presence should be checked earlier");
1515 error(NameValueNode,
1516 "entry with relative path at the root level is not discoverable");
1517 return nullptr;
1518 }
1519
Ben Langmuir93853232014-03-05 21:32:20 +00001520 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001521 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001522 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1523 while (Trimmed.size() > RootPathLen &&
1524 sys::path::is_separator(Trimmed.back()))
Jonas Devliegherefc514902018-10-10 13:27:25 +00001525 Trimmed = Trimmed.slice(0, Trimmed.size() - 1);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001526 // Get the last component
1527 StringRef LastComponent = sys::path::filename(Trimmed);
1528
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001529 std::unique_ptr<Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001530 switch (Kind) {
1531 case EK_File:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001532 Result = llvm::make_unique<RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001533 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001534 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001535 case EK_Directory:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001536 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001537 LastComponent, std::move(EntryArrayContents),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001538 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1539 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001540 break;
1541 }
1542
1543 StringRef Parent = sys::path::parent_path(Trimmed);
1544 if (Parent.empty())
1545 return Result;
1546
1547 // if 'name' contains multiple components, create implicit directory entries
1548 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1549 E = sys::path::rend(Parent);
1550 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001551 std::vector<std::unique_ptr<Entry>> Entries;
1552 Entries.push_back(std::move(Result));
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001553 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001554 *I, std::move(Entries),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001555 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1556 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001557 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001558 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001559 }
1560
1561public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001562 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001563
1564 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001565 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001566 auto *Top = dyn_cast<yaml::MappingNode>(Root);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001567 if (!Top) {
1568 error(Root, "expected mapping node");
1569 return false;
1570 }
1571
1572 KeyStatusPair Fields[] = {
Jonas Devliegherefc514902018-10-10 13:27:25 +00001573 KeyStatusPair("version", true),
1574 KeyStatusPair("case-sensitive", false),
1575 KeyStatusPair("use-external-names", false),
1576 KeyStatusPair("overlay-relative", false),
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001577 KeyStatusPair("fallthrough", false),
Jonas Devliegherefc514902018-10-10 13:27:25 +00001578 KeyStatusPair("roots", true),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001579 };
1580
Craig Topperac67c052015-11-30 03:11:10 +00001581 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001582 std::vector<std::unique_ptr<Entry>> RootEntries;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001583
1584 // Parse configuration and 'roots'
Eugene Zelenko5a520112018-03-28 22:09:09 +00001585 for (auto &I : *Top) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001586 SmallString<10> KeyBuffer;
1587 StringRef Key;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001588 if (!parseScalarString(I.getKey(), Key, KeyBuffer))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001589 return false;
1590
Eugene Zelenko5a520112018-03-28 22:09:09 +00001591 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001592 return false;
1593
1594 if (Key == "roots") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001595 auto *Roots = dyn_cast<yaml::SequenceNode>(I.getValue());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001596 if (!Roots) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001597 error(I.getValue(), "expected array");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001598 return false;
1599 }
1600
Eugene Zelenko5a520112018-03-28 22:09:09 +00001601 for (auto &I : *Roots) {
Volodymyr Sapsai3b2f6a42018-08-07 19:05:41 +00001602 if (std::unique_ptr<Entry> E =
1603 parseEntry(&I, FS, /*IsRootEntry*/ true))
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001604 RootEntries.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001605 else
1606 return false;
1607 }
1608 } else if (Key == "version") {
1609 StringRef VersionString;
1610 SmallString<4> Storage;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001611 if (!parseScalarString(I.getValue(), VersionString, Storage))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001612 return false;
1613 int Version;
1614 if (VersionString.getAsInteger<int>(10, Version)) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001615 error(I.getValue(), "expected integer");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001616 return false;
1617 }
1618 if (Version < 0) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001619 error(I.getValue(), "invalid version number");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001620 return false;
1621 }
1622 if (Version != 0) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001623 error(I.getValue(), "version mismatch, expected 0");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001624 return false;
1625 }
1626 } else if (Key == "case-sensitive") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001627 if (!parseScalarBool(I.getValue(), FS->CaseSensitive))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001628 return false;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001629 } else if (Key == "overlay-relative") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001630 if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay))
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001631 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001632 } else if (Key == "use-external-names") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001633 if (!parseScalarBool(I.getValue(), FS->UseExternalNames))
Ben Langmuirb59cf672014-02-27 00:25:12 +00001634 return false;
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001635 } else if (Key == "fallthrough") {
1636 if (!parseScalarBool(I.getValue(), FS->IsFallthrough))
1637 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001638 } else {
1639 llvm_unreachable("key missing from Keys");
1640 }
1641 }
1642
1643 if (Stream.failed())
1644 return false;
1645
1646 if (!checkMissingKeys(Top, Keys))
1647 return false;
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001648
1649 // Now that we sucessefully parsed the YAML file, canonicalize the internal
1650 // representation to a proper directory tree so that we can search faster
1651 // inside the VFS.
Eugene Zelenko5a520112018-03-28 22:09:09 +00001652 for (auto &E : RootEntries)
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001653 uniqueOverlayTree(FS, E.get());
1654
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001655 return true;
1656 }
1657};
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001658
Eugene Zelenko5a520112018-03-28 22:09:09 +00001659} // namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001660
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001661RedirectingFileSystem *
1662RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1663 SourceMgr::DiagHandlerTy DiagHandler,
1664 StringRef YAMLFilePath, void *DiagContext,
1665 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001666 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001667 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001668
Ben Langmuir97882e72014-02-24 20:56:37 +00001669 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001670 yaml::document_iterator DI = Stream.begin();
1671 yaml::Node *Root = DI->getRoot();
1672 if (DI == Stream.end() || !Root) {
1673 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001674 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001675 }
1676
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001677 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001678
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001679 std::unique_ptr<RedirectingFileSystem> FS(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001680 new RedirectingFileSystem(std::move(ExternalFS)));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001681
1682 if (!YAMLFilePath.empty()) {
1683 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1684 // to each 'external-contents' path.
1685 //
1686 // Example:
1687 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
1688 // yields:
1689 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1690 //
1691 SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1692 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1693 assert(!EC && "Overlay dir final path must be absolute");
1694 (void)EC;
1695 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1696 }
1697
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001698 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001699 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001700
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001701 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001702}
1703
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001704ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001705 SmallString<256> Path;
1706 Path_.toVector(Path);
1707
1708 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001709 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001710 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001711
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001712 // Canonicalize path by removing ".", "..", "./", etc components. This is
1713 // a VFS request, do bot bother about symlinks in the path components
1714 // but canonicalize in order to perform the correct entry search.
1715 if (UseCanonicalizedPaths) {
1716 Path = sys::path::remove_leading_dotslash(Path);
1717 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1718 }
1719
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001720 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001721 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001722
1723 sys::path::const_iterator Start = sys::path::begin(Path);
1724 sys::path::const_iterator End = sys::path::end(Path);
Eugene Zelenko5a520112018-03-28 22:09:09 +00001725 for (const auto &Root : Roots) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001726 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001727 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001728 return Result;
1729 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001730 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001731}
1732
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001733ErrorOr<Entry *>
1734RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1735 sys::path::const_iterator End, Entry *From) {
Nico Weber1865df42018-04-27 19:11:14 +00001736#ifndef _WIN32
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001737 assert(!isTraversalComponent(*Start) &&
1738 !isTraversalComponent(From->getName()) &&
1739 "Paths should not contain traversal components");
1740#else
1741 // FIXME: this is here to support windows, remove it once canonicalized
1742 // paths become globally default.
Bruno Cardoso Lopesbe056b12016-02-23 17:06:50 +00001743 if (Start->equals("."))
1744 ++Start;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001745#endif
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001746
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001747 StringRef FromName = From->getName();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001748
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001749 // Forward the search to the next component in case this is an empty one.
1750 if (!FromName.empty()) {
1751 if (CaseSensitive ? !Start->equals(FromName)
1752 : !Start->equals_lower(FromName))
1753 // failure to match
1754 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001755
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001756 ++Start;
1757
1758 if (Start == End) {
1759 // Match!
1760 return From;
1761 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001762 }
1763
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001764 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001765 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001766 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001767
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001768 for (const std::unique_ptr<Entry> &DirEntry :
1769 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1770 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001771 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001772 return Result;
1773 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001774 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001775}
1776
Ben Langmuirf13302e2015-12-10 23:41:39 +00001777static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1778 Status ExternalStatus) {
1779 Status S = ExternalStatus;
1780 if (!UseExternalNames)
Jordan Rupprechta8fb7292018-07-24 20:28:07 +00001781 S = Status::copyWithNewName(S, Path.str());
Ben Langmuirf13302e2015-12-10 23:41:39 +00001782 S.IsVFSMapped = true;
1783 return S;
1784}
1785
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001786ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001787 assert(E != nullptr);
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001788 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001789 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001790 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuir5de00f32014-05-23 18:15:47 +00001791 if (S)
Ben Langmuirf13302e2015-12-10 23:41:39 +00001792 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1793 *S);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001794 return S;
1795 } else { // directory
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001796 auto *DE = cast<RedirectingDirectoryEntry>(E);
Jordan Rupprechta8fb7292018-07-24 20:28:07 +00001797 return Status::copyWithNewName(DE->getStatus(), Path.str());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001798 }
1799}
1800
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001801ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001802 ErrorOr<Entry *> Result = lookupPath(Path);
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001803 if (!Result) {
1804 if (IsFallthrough &&
1805 Result.getError() == llvm::errc::no_such_file_or_directory) {
1806 return ExternalFS->status(Path);
1807 }
Ben Langmuir740812b2014-06-24 19:37:16 +00001808 return Result.getError();
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001809 }
Ben Langmuir740812b2014-06-24 19:37:16 +00001810 return status(Path, *Result);
1811}
1812
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001813namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001814
Ben Langmuirf13302e2015-12-10 23:41:39 +00001815/// Provide a file wrapper with an overriden status.
1816class FileWithFixedStatus : public File {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001817 std::unique_ptr<File> InnerFile;
Ben Langmuirf13302e2015-12-10 23:41:39 +00001818 Status S;
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001819
1820public:
Ben Langmuirf13302e2015-12-10 23:41:39 +00001821 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
Benjamin Kramercfeacf52016-05-27 14:27:13 +00001822 : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001823
Ben Langmuirf13302e2015-12-10 23:41:39 +00001824 ErrorOr<Status> status() override { return S; }
1825 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Eugene Zelenko5a520112018-03-28 22:09:09 +00001826
Benjamin Kramer737501c2015-10-05 21:20:19 +00001827 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1828 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001829 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1830 IsVolatile);
1831 }
Eugene Zelenko5a520112018-03-28 22:09:09 +00001832
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001833 std::error_code close() override { return InnerFile->close(); }
1834};
Eugene Zelenko5a520112018-03-28 22:09:09 +00001835
1836} // namespace
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001837
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001838ErrorOr<std::unique_ptr<File>>
1839RedirectingFileSystem::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001840 ErrorOr<Entry *> E = lookupPath(Path);
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001841 if (!E) {
1842 if (IsFallthrough &&
1843 E.getError() == llvm::errc::no_such_file_or_directory) {
1844 return ExternalFS->openFileForRead(Path);
1845 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001846 return E.getError();
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00001847 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001848
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001849 auto *F = dyn_cast<RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001850 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001851 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001852
Benjamin Kramera8857962014-10-26 22:44:13 +00001853 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1854 if (!Result)
1855 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001856
Ben Langmuirf13302e2015-12-10 23:41:39 +00001857 auto ExternalStatus = (*Result)->status();
1858 if (!ExternalStatus)
1859 return ExternalStatus.getError();
Ben Langmuird066d4c2014-02-28 21:16:07 +00001860
Ben Langmuirf13302e2015-12-10 23:41:39 +00001861 // FIXME: Update the status with the name and VFSMapped.
1862 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1863 *ExternalStatus);
1864 return std::unique_ptr<File>(
1865 llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001866}
1867
1868IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001869vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001870 SourceMgr::DiagHandlerTy DiagHandler,
Jonas Devliegherefc514902018-10-10 13:27:25 +00001871 StringRef YAMLFilePath, void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001872 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001873 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001874 YAMLFilePath, DiagContext,
1875 std::move(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001876}
1877
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001878static void getVFSEntries(Entry *SrcE, SmallVectorImpl<StringRef> &Path,
1879 SmallVectorImpl<YAMLVFSEntry> &Entries) {
1880 auto Kind = SrcE->getKind();
1881 if (Kind == EK_Directory) {
1882 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1883 assert(DE && "Must be a directory");
1884 for (std::unique_ptr<Entry> &SubEntry :
1885 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1886 Path.push_back(SubEntry->getName());
1887 getVFSEntries(SubEntry.get(), Path, Entries);
1888 Path.pop_back();
1889 }
1890 return;
1891 }
1892
1893 assert(Kind == EK_File && "Must be a EK_File");
1894 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1895 assert(FE && "Must be a file");
1896 SmallString<128> VPath;
1897 for (auto &Comp : Path)
1898 llvm::sys::path::append(VPath, Comp);
1899 Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
1900}
1901
1902void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1903 SourceMgr::DiagHandlerTy DiagHandler,
1904 StringRef YAMLFilePath,
1905 SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
1906 void *DiagContext,
1907 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1908 RedirectingFileSystem *VFS = RedirectingFileSystem::create(
1909 std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
1910 std::move(ExternalFS));
1911 ErrorOr<Entry *> RootE = VFS->lookupPath("/");
1912 if (!RootE)
1913 return;
1914 SmallVector<StringRef, 8> Components;
1915 Components.push_back("/");
1916 getVFSEntries(*RootE, Components, CollectedEntries);
1917}
1918
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001919UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001920 static std::atomic<unsigned> UID;
1921 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001922 // The following assumes that uint64_t max will never collide with a real
1923 // dev_t value from the OS.
1924 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1925}
Justin Bogner9c785292014-05-20 21:43:27 +00001926
Justin Bogner9c785292014-05-20 21:43:27 +00001927void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1928 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1929 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1930 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1931 Mappings.emplace_back(VirtualPath, RealPath);
1932}
1933
Justin Bogner44fa450342014-05-21 22:46:51 +00001934namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001935
Justin Bogner44fa450342014-05-21 22:46:51 +00001936class JSONWriter {
1937 llvm::raw_ostream &OS;
1938 SmallVector<StringRef, 16> DirStack;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001939
1940 unsigned getDirIndent() { return 4 * DirStack.size(); }
1941 unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
Justin Bogner44fa450342014-05-21 22:46:51 +00001942 bool containedIn(StringRef Parent, StringRef Path);
1943 StringRef containedPart(StringRef Parent, StringRef Path);
1944 void startDirectory(StringRef Path);
1945 void endDirectory();
1946 void writeEntry(StringRef VPath, StringRef RPath);
1947
1948public:
1949 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +00001950
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001951 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
1952 Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
Volodymyr Sapsai7faf7ae2018-10-24 22:40:54 +00001953 StringRef OverlayDir);
Justin Bogner44fa450342014-05-21 22:46:51 +00001954};
Eugene Zelenko5a520112018-03-28 22:09:09 +00001955
1956} // namespace
Justin Bogner9c785292014-05-20 21:43:27 +00001957
Justin Bogner44fa450342014-05-21 22:46:51 +00001958bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001959 using namespace llvm::sys;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001960
Justin Bogner1c078f22014-05-20 22:12:58 +00001961 // Compare each path component.
1962 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1963 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1964 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1965 if (*IParent != *IChild)
1966 return false;
1967 }
1968 // Have we exhausted the parent path?
1969 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001970}
1971
Justin Bogner44fa450342014-05-21 22:46:51 +00001972StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1973 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001974 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001975 return Path.slice(Parent.size() + 1, StringRef::npos);
1976}
1977
Justin Bogner44fa450342014-05-21 22:46:51 +00001978void JSONWriter::startDirectory(StringRef Path) {
1979 StringRef Name =
1980 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1981 DirStack.push_back(Path);
1982 unsigned Indent = getDirIndent();
1983 OS.indent(Indent) << "{\n";
1984 OS.indent(Indent + 2) << "'type': 'directory',\n";
1985 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1986 OS.indent(Indent + 2) << "'contents': [\n";
1987}
1988
1989void JSONWriter::endDirectory() {
1990 unsigned Indent = getDirIndent();
1991 OS.indent(Indent + 2) << "]\n";
1992 OS.indent(Indent) << "}";
1993
1994 DirStack.pop_back();
1995}
1996
1997void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1998 unsigned Indent = getFileIndent();
1999 OS.indent(Indent) << "{\n";
2000 OS.indent(Indent + 2) << "'type': 'file',\n";
2001 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
2002 OS.indent(Indent + 2) << "'external-contents': \""
2003 << llvm::yaml::escape(RPath) << "\"\n";
2004 OS.indent(Indent) << "}";
2005}
2006
2007void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00002008 Optional<bool> UseExternalNames,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00002009 Optional<bool> IsCaseSensitive,
2010 Optional<bool> IsOverlayRelative,
2011 StringRef OverlayDir) {
Justin Bogner44fa450342014-05-21 22:46:51 +00002012 using namespace llvm::sys;
2013
2014 OS << "{\n"
2015 " 'version': 0,\n";
2016 if (IsCaseSensitive.hasValue())
2017 OS << " 'case-sensitive': '"
2018 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00002019 if (UseExternalNames.hasValue())
2020 OS << " 'use-external-names': '"
2021 << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00002022 bool UseOverlayRelative = false;
2023 if (IsOverlayRelative.hasValue()) {
2024 UseOverlayRelative = IsOverlayRelative.getValue();
Jonas Devliegherefc514902018-10-10 13:27:25 +00002025 OS << " 'overlay-relative': '" << (UseOverlayRelative ? "true" : "false")
2026 << "',\n";
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00002027 }
Justin Bogner44fa450342014-05-21 22:46:51 +00002028 OS << " 'roots': [\n";
2029
Justin Bogner73466402014-07-15 01:24:35 +00002030 if (!Entries.empty()) {
2031 const YAMLVFSEntry &Entry = Entries.front();
2032 startDirectory(path::parent_path(Entry.VPath));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00002033
2034 StringRef RPath = Entry.RPath;
2035 if (UseOverlayRelative) {
2036 unsigned OverlayDirLen = OverlayDir.size();
2037 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
2038 "Overlay dir must be contained in RPath");
2039 RPath = RPath.slice(OverlayDirLen, RPath.size());
2040 }
2041
2042 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00002043
Justin Bogner73466402014-07-15 01:24:35 +00002044 for (const auto &Entry : Entries.slice(1)) {
2045 StringRef Dir = path::parent_path(Entry.VPath);
2046 if (Dir == DirStack.back())
2047 OS << ",\n";
2048 else {
2049 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
2050 OS << "\n";
2051 endDirectory();
2052 }
2053 OS << ",\n";
2054 startDirectory(Dir);
2055 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00002056 StringRef RPath = Entry.RPath;
2057 if (UseOverlayRelative) {
2058 unsigned OverlayDirLen = OverlayDir.size();
2059 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
2060 "Overlay dir must be contained in RPath");
2061 RPath = RPath.slice(OverlayDirLen, RPath.size());
2062 }
2063 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner73466402014-07-15 01:24:35 +00002064 }
2065
2066 while (!DirStack.empty()) {
2067 OS << "\n";
2068 endDirectory();
2069 }
Justin Bogner44fa450342014-05-21 22:46:51 +00002070 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00002071 }
2072
Justin Bogner73466402014-07-15 01:24:35 +00002073 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00002074 << "}\n";
2075}
2076
Justin Bogner9c785292014-05-20 21:43:27 +00002077void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
Fangrui Song55fab262018-09-26 22:16:28 +00002078 llvm::sort(Mappings, [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00002079 return LHS.VPath < RHS.VPath;
2080 });
2081
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00002082 JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
Volodymyr Sapsai7faf7ae2018-10-24 22:40:54 +00002083 IsOverlayRelative, OverlayDir);
Justin Bogner9c785292014-05-20 21:43:27 +00002084}
Ben Langmuir740812b2014-06-24 19:37:16 +00002085
Benjamin Kramer49692ed2015-10-09 13:28:13 +00002086VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
Sam McCall0ae00562018-09-14 12:47:38 +00002087 const Twine &_Path, RedirectingDirectoryEntry::iterator Begin,
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00002088 RedirectingDirectoryEntry::iterator End, bool IterateExternalFS,
2089 FileSystem &ExternalFS, std::error_code &EC)
2090 : Dir(_Path.str()), Current(Begin), End(End),
2091 IterateExternalFS(IterateExternalFS), ExternalFS(ExternalFS) {
2092 EC = incrementImpl(/*IsFirstTime=*/true);
Ben Langmuir740812b2014-06-24 19:37:16 +00002093}
2094
2095std::error_code VFSFromYamlDirIterImpl::increment() {
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00002096 return incrementImpl(/*IsFirstTime=*/false);
Volodymyr Sapsai3aa88b52018-08-07 23:00:40 +00002097}
2098
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00002099std::error_code VFSFromYamlDirIterImpl::incrementExternal() {
2100 assert(!(IsExternalFSCurrent && ExternalDirIter == directory_iterator()) &&
2101 "incrementing past end");
2102 std::error_code EC;
2103 if (IsExternalFSCurrent) {
2104 ExternalDirIter.increment(EC);
2105 } else if (IterateExternalFS) {
2106 ExternalDirIter = ExternalFS.dir_begin(Dir, EC);
2107 IsExternalFSCurrent = true;
2108 if (EC && EC != errc::no_such_file_or_directory)
2109 return EC;
2110 EC = {};
2111 }
2112 if (EC || ExternalDirIter == directory_iterator()) {
2113 CurrentEntry = directory_entry();
2114 } else {
2115 CurrentEntry = *ExternalDirIter;
2116 }
2117 return EC;
2118}
2119
2120std::error_code VFSFromYamlDirIterImpl::incrementContent(bool IsFirstTime) {
Erich Keanef1d30612018-10-29 21:21:55 +00002121 assert((IsFirstTime || Current != End) && "cannot iterate past end");
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00002122 if (!IsFirstTime)
2123 ++Current;
Volodymyr Sapsai3aa88b52018-08-07 23:00:40 +00002124 while (Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00002125 SmallString<128> PathStr(Dir);
2126 llvm::sys::path::append(PathStr, (*Current)->getName());
Sam McCall0ae00562018-09-14 12:47:38 +00002127 sys::fs::file_type Type;
2128 switch ((*Current)->getKind()) {
Jonas Devliegherefc514902018-10-10 13:27:25 +00002129 case EK_Directory:
2130 Type = sys::fs::file_type::directory_file;
2131 break;
2132 case EK_File:
2133 Type = sys::fs::file_type::regular_file;
2134 break;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00002135 }
Sam McCall0ae00562018-09-14 12:47:38 +00002136 CurrentEntry = directory_entry(PathStr.str(), Type);
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00002137 return {};
Bruno Cardoso Lopese43e2632016-08-12 02:17:26 +00002138 }
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00002139 return incrementExternal();
2140}
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00002141
Volodymyr Sapsai91e13162018-10-26 22:14:33 +00002142std::error_code VFSFromYamlDirIterImpl::incrementImpl(bool IsFirstTime) {
2143 while (true) {
2144 std::error_code EC = IsExternalFSCurrent ? incrementExternal()
2145 : incrementContent(IsFirstTime);
2146 if (EC || CurrentEntry.path().empty())
2147 return EC;
2148 StringRef Name = llvm::sys::path::filename(CurrentEntry.path());
2149 if (SeenNames.insert(Name).second)
2150 return EC; // name not seen before
2151 }
2152 llvm_unreachable("returned above");
Ben Langmuir740812b2014-06-24 19:37:16 +00002153}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002154
Jonas Devliegherefc514902018-10-10 13:27:25 +00002155vfs::recursive_directory_iterator::recursive_directory_iterator(
2156 FileSystem &FS_, const Twine &Path, std::error_code &EC)
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002157 : FS(&FS_) {
2158 directory_iterator I = FS->dir_begin(Path, EC);
Juergen Ributzkaf9787432017-03-14 00:14:40 +00002159 if (I != directory_iterator()) {
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002160 State = std::make_shared<IterState>();
2161 State->push(I);
2162 }
2163}
2164
2165vfs::recursive_directory_iterator &
2166recursive_directory_iterator::increment(std::error_code &EC) {
2167 assert(FS && State && !State->empty() && "incrementing past end");
Sam McCall0ae00562018-09-14 12:47:38 +00002168 assert(!State->top()->path().empty() && "non-canonical end iterator");
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002169 vfs::directory_iterator End;
Sam McCall0ae00562018-09-14 12:47:38 +00002170 if (State->top()->type() == sys::fs::file_type::directory_file) {
2171 vfs::directory_iterator I = FS->dir_begin(State->top()->path(), EC);
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00002172 if (I != End) {
2173 State->push(I);
2174 return *this;
2175 }
2176 }
2177
2178 while (!State->empty() && State->top().increment(EC) == End)
2179 State->pop();
2180
2181 if (State->empty())
2182 State.reset(); // end iterator
2183
2184 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002185}