blob: fd000196d3a44f40df376ee61eac24dab21dae64 [file] [log] [blame]
Ben Langmuirc8130a72014-02-20 21:59:23 +00001//===- VirtualFileSystem.cpp - Virtual File System Layer --------*- C++ -*-===//
2//
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//===----------------------------------------------------------------------===//
9// This file implements the VirtualFileSystem interface.
10//===----------------------------------------------------------------------===//
11
12#include "clang/Basic/VirtualFileSystem.h"
Benjamin Kramer71ce3762015-10-12 16:16:39 +000013#include "clang/Basic/FileManager.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000014#include "llvm/ADT/DenseMap.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000015#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/StringExtras.h"
Ben Langmuir740812b2014-06-24 19:37:16 +000017#include "llvm/ADT/StringSet.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "llvm/ADT/iterator_range.h"
Benjamin Kramercfeacf52016-05-27 14:27:13 +000019#include "llvm/Config/llvm-config.h"
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +000020#include "llvm/Support/Debug.h"
Rafael Espindola71de0b62014-06-13 17:20:50 +000021#include "llvm/Support/Errc.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000022#include "llvm/Support/MemoryBuffer.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000023#include "llvm/Support/Path.h"
David Majnemer6a6206d2016-03-04 05:26:14 +000024#include "llvm/Support/Process.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000025#include "llvm/Support/YAMLParser.h"
Benjamin Kramer4527fb22014-03-02 17:08:31 +000026#include <atomic>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000027#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000028#include <utility>
Ben Langmuirc8130a72014-02-20 21:59:23 +000029
30using namespace clang;
31using namespace clang::vfs;
32using namespace llvm;
33using llvm::sys::fs::file_status;
34using llvm::sys::fs::file_type;
35using llvm::sys::fs::perms;
36using llvm::sys::fs::UniqueID;
37
38Status::Status(const file_status &Status)
39 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
40 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
Ben Langmuir5de00f32014-05-23 18:15:47 +000041 Type(Status.type()), Perms(Status.permissions()), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000042
Pavel Labathac71c8e2016-11-09 10:52:22 +000043Status::Status(StringRef Name, UniqueID UID, sys::TimePoint<> MTime,
Benjamin Kramer268b51a2015-10-05 13:15:33 +000044 uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
45 perms Perms)
Ben Langmuirb59cf672014-02-27 00:25:12 +000046 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
Ben Langmuir5de00f32014-05-23 18:15:47 +000047 Type(Type), Perms(Perms), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000048
Benjamin Kramer268b51a2015-10-05 13:15:33 +000049Status Status::copyWithNewName(const Status &In, StringRef NewName) {
50 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
51 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
52 In.getPermissions());
53}
54
55Status Status::copyWithNewName(const file_status &In, StringRef NewName) {
56 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
57 In.getUser(), In.getGroup(), In.getSize(), In.type(),
58 In.permissions());
59}
60
Ben Langmuirc8130a72014-02-20 21:59:23 +000061bool Status::equivalent(const Status &Other) const {
Benjamin Kramerd5152912017-07-20 11:57:02 +000062 assert(isStatusKnown() && Other.isStatusKnown());
Ben Langmuirc8130a72014-02-20 21:59:23 +000063 return getUniqueID() == Other.getUniqueID();
64}
65bool Status::isDirectory() const {
66 return Type == file_type::directory_file;
67}
68bool Status::isRegularFile() const {
69 return Type == file_type::regular_file;
70}
71bool Status::isOther() const {
72 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
73}
74bool Status::isSymlink() const {
75 return Type == file_type::symlink_file;
76}
77bool Status::isStatusKnown() const {
78 return Type != file_type::status_error;
79}
80bool Status::exists() const {
81 return isStatusKnown() && Type != file_type::file_not_found;
82}
83
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000084File::~File() {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000085
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000086FileSystem::~FileSystem() {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000087
Benjamin Kramera8857962014-10-26 22:44:13 +000088ErrorOr<std::unique_ptr<MemoryBuffer>>
89FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
90 bool RequiresNullTerminator, bool IsVolatile) {
91 auto F = openFileForRead(Name);
92 if (!F)
93 return F.getError();
Ben Langmuirc8130a72014-02-20 21:59:23 +000094
Benjamin Kramera8857962014-10-26 22:44:13 +000095 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +000096}
97
Benjamin Kramer7708b2a2015-10-05 13:55:20 +000098std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
Bob Wilsonf43354f2016-03-26 18:55:13 +000099 if (llvm::sys::path::is_absolute(Path))
100 return std::error_code();
101
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000102 auto WorkingDir = getCurrentWorkingDirectory();
103 if (!WorkingDir)
104 return WorkingDir.getError();
105
106 return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
107}
108
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000109bool FileSystem::exists(const Twine &Path) {
110 auto Status = status(Path);
111 return Status && Status->exists();
112}
113
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000114#ifndef NDEBUG
115static bool isTraversalComponent(StringRef Component) {
116 return Component.equals("..") || Component.equals(".");
117}
118
119static bool pathHasTraversal(StringRef Path) {
120 using namespace llvm::sys;
121 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
122 if (isTraversalComponent(Comp))
123 return true;
124 return false;
125}
126#endif
127
Ben Langmuirc8130a72014-02-20 21:59:23 +0000128//===-----------------------------------------------------------------------===/
129// RealFileSystem implementation
130//===-----------------------------------------------------------------------===/
131
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000132namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000133/// \brief Wrapper around a raw file descriptor.
134class RealFile : public File {
135 int FD;
Ben Langmuird066d4c2014-02-28 21:16:07 +0000136 Status S;
Taewook Ohf42103c2016-06-13 20:40:21 +0000137 std::string RealName;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000138 friend class RealFileSystem;
Taewook Ohf42103c2016-06-13 20:40:21 +0000139 RealFile(int FD, StringRef NewName, StringRef NewRealPathName)
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000140 : FD(FD), S(NewName, {}, {}, {}, {}, {},
Taewook Ohf42103c2016-06-13 20:40:21 +0000141 llvm::sys::fs::file_type::status_error, {}),
142 RealName(NewRealPathName.str()) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000143 assert(FD >= 0 && "Invalid or inactive file descriptor");
144 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000145
Ben Langmuirc8130a72014-02-20 21:59:23 +0000146public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000147 ~RealFile() override;
Craig Toppera798a9d2014-03-02 09:32:10 +0000148 ErrorOr<Status> status() override;
Taewook Ohf42103c2016-06-13 20:40:21 +0000149 ErrorOr<std::string> getName() override;
Benjamin Kramer737501c2015-10-05 21:20:19 +0000150 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
151 int64_t FileSize,
152 bool RequiresNullTerminator,
153 bool IsVolatile) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000154 std::error_code close() override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000155};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000156} // end anonymous namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000157RealFile::~RealFile() { close(); }
Ben Langmuirc8130a72014-02-20 21:59:23 +0000158
159ErrorOr<Status> RealFile::status() {
160 assert(FD != -1 && "cannot stat closed file");
Ben Langmuird066d4c2014-02-28 21:16:07 +0000161 if (!S.isStatusKnown()) {
162 file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000163 if (std::error_code EC = sys::fs::status(FD, RealStatus))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000164 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000165 S = Status::copyWithNewName(RealStatus, S.getName());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000166 }
167 return S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000168}
169
Taewook Ohf42103c2016-06-13 20:40:21 +0000170ErrorOr<std::string> RealFile::getName() {
171 return RealName.empty() ? S.getName().str() : RealName;
172}
173
Benjamin Kramera8857962014-10-26 22:44:13 +0000174ErrorOr<std::unique_ptr<MemoryBuffer>>
175RealFile::getBuffer(const Twine &Name, int64_t FileSize,
176 bool RequiresNullTerminator, bool IsVolatile) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000177 assert(FD != -1 && "cannot get buffer for closed file");
Benjamin Kramera8857962014-10-26 22:44:13 +0000178 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
179 IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000180}
181
Rafael Espindola8e650d72014-06-12 20:37:59 +0000182std::error_code RealFile::close() {
David Majnemer6a6206d2016-03-04 05:26:14 +0000183 std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000184 FD = -1;
David Majnemer6a6206d2016-03-04 05:26:14 +0000185 return EC;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000186}
187
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000188namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000189/// \brief The file system according to your operating system.
190class RealFileSystem : public FileSystem {
191public:
Craig Toppera798a9d2014-03-02 09:32:10 +0000192 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000193 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000194 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000195
196 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
197 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000198};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000199} // end anonymous namespace
Ben Langmuirc8130a72014-02-20 21:59:23 +0000200
201ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
202 sys::fs::file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000203 if (std::error_code EC = sys::fs::status(Path, RealStatus))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000204 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000205 return Status::copyWithNewName(RealStatus, Path.str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000206}
207
Benjamin Kramera8857962014-10-26 22:44:13 +0000208ErrorOr<std::unique_ptr<File>>
209RealFileSystem::openFileForRead(const Twine &Name) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000210 int FD;
Taewook Ohf42103c2016-06-13 20:40:21 +0000211 SmallString<256> RealName;
212 if (std::error_code EC = sys::fs::openFileForRead(Name, FD, &RealName))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000213 return EC;
Taewook Ohf42103c2016-06-13 20:40:21 +0000214 return std::unique_ptr<File>(new RealFile(FD, Name.str(), RealName.str()));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000215}
216
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000217llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
218 SmallString<256> Dir;
219 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
220 return EC;
221 return Dir.str().str();
222}
223
224std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
225 // FIXME: chdir is thread hostile; on the other hand, creating the same
226 // behavior as chdir is complex: chdir resolves the path once, thus
227 // guaranteeing that all subsequent relative path operations work
228 // on the same path the original chdir resulted in. This makes a
229 // difference for example on network filesystems, where symlinks might be
230 // switched during runtime of the tool. Fixing this depends on having a
231 // file system abstraction that allows openat() style interactions.
Pavel Labathdcbd6142017-01-24 11:14:29 +0000232 return llvm::sys::fs::set_current_path(Path);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000233}
234
Ben Langmuirc8130a72014-02-20 21:59:23 +0000235IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
236 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
237 return FS;
238}
239
Ben Langmuir740812b2014-06-24 19:37:16 +0000240namespace {
241class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
Ben Langmuir740812b2014-06-24 19:37:16 +0000242 llvm::sys::fs::directory_iterator Iter;
243public:
Juergen Ributzka4a259562017-03-10 21:23:29 +0000244 RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) {
Ben Langmuir740812b2014-06-24 19:37:16 +0000245 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
246 llvm::sys::fs::file_status S;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000247 EC = llvm::sys::fs::status(Iter->path(), S, true);
Juergen Ributzkaf9787432017-03-14 00:14:40 +0000248 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000249 }
250 }
251
252 std::error_code increment() override {
253 std::error_code EC;
254 Iter.increment(EC);
255 if (EC) {
256 return EC;
257 } else if (Iter == llvm::sys::fs::directory_iterator()) {
258 CurrentEntry = Status();
259 } else {
260 llvm::sys::fs::file_status S;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000261 EC = llvm::sys::fs::status(Iter->path(), S, true);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000262 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000263 }
264 return EC;
265 }
266};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000267}
Ben Langmuir740812b2014-06-24 19:37:16 +0000268
269directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
270 std::error_code &EC) {
271 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
272}
273
Ben Langmuirc8130a72014-02-20 21:59:23 +0000274//===-----------------------------------------------------------------------===/
275// OverlayFileSystem implementation
276//===-----------------------------------------------------------------------===/
277OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000278 FSList.push_back(std::move(BaseFS));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000279}
280
281void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
282 FSList.push_back(FS);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000283 // Synchronize added file systems by duplicating the working directory from
284 // the first one in the list.
285 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000286}
287
288ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
289 // FIXME: handle symlinks that cross file systems
290 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
291 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000292 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000293 return Status;
294 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000295 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000296}
297
Benjamin Kramera8857962014-10-26 22:44:13 +0000298ErrorOr<std::unique_ptr<File>>
299OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000300 // FIXME: handle symlinks that cross file systems
301 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000302 auto Result = (*I)->openFileForRead(Path);
303 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
304 return Result;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000305 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000306 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000307}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000308
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000309llvm::ErrorOr<std::string>
310OverlayFileSystem::getCurrentWorkingDirectory() const {
311 // All file systems are synchronized, just take the first working directory.
312 return FSList.front()->getCurrentWorkingDirectory();
313}
314std::error_code
315OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
316 for (auto &FS : FSList)
317 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
318 return EC;
319 return std::error_code();
320}
321
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000322clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
Ben Langmuir740812b2014-06-24 19:37:16 +0000323
324namespace {
325class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
326 OverlayFileSystem &Overlays;
327 std::string Path;
328 OverlayFileSystem::iterator CurrentFS;
329 directory_iterator CurrentDirIter;
330 llvm::StringSet<> SeenNames;
331
332 std::error_code incrementFS() {
333 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
334 ++CurrentFS;
335 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
336 std::error_code EC;
337 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
338 if (EC && EC != errc::no_such_file_or_directory)
339 return EC;
340 if (CurrentDirIter != directory_iterator())
341 break; // found
342 }
343 return std::error_code();
344 }
345
346 std::error_code incrementDirIter(bool IsFirstTime) {
347 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
348 "incrementing past end");
349 std::error_code EC;
350 if (!IsFirstTime)
351 CurrentDirIter.increment(EC);
352 if (!EC && CurrentDirIter == directory_iterator())
353 EC = incrementFS();
354 return EC;
355 }
356
357 std::error_code incrementImpl(bool IsFirstTime) {
358 while (true) {
359 std::error_code EC = incrementDirIter(IsFirstTime);
360 if (EC || CurrentDirIter == directory_iterator()) {
361 CurrentEntry = Status();
362 return EC;
363 }
364 CurrentEntry = *CurrentDirIter;
365 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
David Blaikie61b86d42014-11-19 02:56:13 +0000366 if (SeenNames.insert(Name).second)
Ben Langmuir740812b2014-06-24 19:37:16 +0000367 return EC; // name not seen before
368 }
369 llvm_unreachable("returned above");
370 }
371
372public:
373 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
374 std::error_code &EC)
375 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
376 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
377 EC = incrementImpl(true);
378 }
379
380 std::error_code increment() override { return incrementImpl(false); }
381};
382} // end anonymous namespace
383
384directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
385 std::error_code &EC) {
386 return directory_iterator(
387 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
388}
389
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000390namespace clang {
391namespace vfs {
392namespace detail {
393
394enum InMemoryNodeKind { IME_File, IME_Directory };
395
396/// The in memory file system is a tree of Nodes. Every node can either be a
397/// file or a directory.
398class InMemoryNode {
399 Status Stat;
400 InMemoryNodeKind Kind;
401
402public:
403 InMemoryNode(Status Stat, InMemoryNodeKind Kind)
404 : Stat(std::move(Stat)), Kind(Kind) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000405 virtual ~InMemoryNode() {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000406 const Status &getStatus() const { return Stat; }
407 InMemoryNodeKind getKind() const { return Kind; }
408 virtual std::string toString(unsigned Indent) const = 0;
409};
410
411namespace {
412class InMemoryFile : public InMemoryNode {
413 std::unique_ptr<llvm::MemoryBuffer> Buffer;
414
415public:
416 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
417 : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
418
419 llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
420 std::string toString(unsigned Indent) const override {
421 return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
422 }
423 static bool classof(const InMemoryNode *N) {
424 return N->getKind() == IME_File;
425 }
426};
427
428/// Adapt a InMemoryFile for VFS' File interface.
429class InMemoryFileAdaptor : public File {
430 InMemoryFile &Node;
431
432public:
433 explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
434
435 llvm::ErrorOr<Status> status() override { return Node.getStatus(); }
436 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +0000437 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
438 bool IsVolatile) override {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000439 llvm::MemoryBuffer *Buf = Node.getBuffer();
440 return llvm::MemoryBuffer::getMemBuffer(
441 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
442 }
443 std::error_code close() override { return std::error_code(); }
444};
445} // end anonymous namespace
446
447class InMemoryDirectory : public InMemoryNode {
448 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
449
450public:
451 InMemoryDirectory(Status Stat)
452 : InMemoryNode(std::move(Stat), IME_Directory) {}
453 InMemoryNode *getChild(StringRef Name) {
454 auto I = Entries.find(Name);
455 if (I != Entries.end())
456 return I->second.get();
457 return nullptr;
458 }
459 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
460 return Entries.insert(make_pair(Name, std::move(Child)))
461 .first->second.get();
462 }
463
464 typedef decltype(Entries)::const_iterator const_iterator;
465 const_iterator begin() const { return Entries.begin(); }
466 const_iterator end() const { return Entries.end(); }
467
468 std::string toString(unsigned Indent) const override {
469 std::string Result =
470 (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
471 for (const auto &Entry : Entries) {
472 Result += Entry.second->toString(Indent + 2);
473 }
474 return Result;
475 }
476 static bool classof(const InMemoryNode *N) {
477 return N->getKind() == IME_Directory;
478 }
479};
480}
481
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000482InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000483 : Root(new detail::InMemoryDirectory(
Pavel Labathac71c8e2016-11-09 10:52:22 +0000484 Status("", getNextVirtualUniqueID(), llvm::sys::TimePoint<>(), 0, 0,
485 0, llvm::sys::fs::file_type::directory_file,
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000486 llvm::sys::fs::perms::all_all))),
487 UseNormalizedPaths(UseNormalizedPaths) {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000488
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000489InMemoryFileSystem::~InMemoryFileSystem() {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000490
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000491std::string InMemoryFileSystem::toString() const {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000492 return Root->toString(/*Indent=*/0);
493}
494
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000495bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000496 std::unique_ptr<llvm::MemoryBuffer> Buffer,
497 Optional<uint32_t> User,
498 Optional<uint32_t> Group,
499 Optional<llvm::sys::fs::file_type> Type,
500 Optional<llvm::sys::fs::perms> Perms) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000501 SmallString<128> Path;
502 P.toVector(Path);
503
504 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000505 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000506 assert(!EC);
507 (void)EC;
508
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000509 if (useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000510 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000511
512 if (Path.empty())
513 return false;
514
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000515 detail::InMemoryDirectory *Dir = Root.get();
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000516 auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path);
517 const auto ResolvedUser = User.getValueOr(0);
518 const auto ResolvedGroup = Group.getValueOr(0);
519 const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file);
520 const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all);
521 // Any intermediate directories we create should be accessible by
522 // the owner, even if Perms says otherwise for the final path.
523 const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000524 while (true) {
525 StringRef Name = *I;
526 detail::InMemoryNode *Node = Dir->getChild(Name);
527 ++I;
528 if (!Node) {
529 if (I == E) {
530 // End of the path, create a new file.
Benjamin Kramer1b8dbe32015-10-06 14:45:16 +0000531 Status Stat(P.str(), getNextVirtualUniqueID(),
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000532 llvm::sys::toTimePoint(ModificationTime), ResolvedUser,
533 ResolvedGroup, Buffer->getBufferSize(), ResolvedType,
534 ResolvedPerms);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000535 Dir->addChild(Name, llvm::make_unique<detail::InMemoryFile>(
536 std::move(Stat), std::move(Buffer)));
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000537 return true;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000538 }
539
540 // Create a new directory. Use the path up to here.
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000541 Status Stat(
542 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000543 getNextVirtualUniqueID(), llvm::sys::toTimePoint(ModificationTime),
544 ResolvedUser, ResolvedGroup, Buffer->getBufferSize(),
545 sys::fs::file_type::directory_file, NewDirectoryPerms);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000546 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
547 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
548 continue;
549 }
550
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000551 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000552 Dir = NewDir;
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000553 } else {
554 assert(isa<detail::InMemoryFile>(Node) &&
555 "Must be either file or directory!");
556
557 // Trying to insert a directory in place of a file.
558 if (I != E)
559 return false;
560
561 // Return false only if the new file is different from the existing one.
562 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
563 Buffer->getBuffer();
564 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000565 }
566}
567
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000568bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000569 llvm::MemoryBuffer *Buffer,
570 Optional<uint32_t> User,
571 Optional<uint32_t> Group,
572 Optional<llvm::sys::fs::file_type> Type,
573 Optional<llvm::sys::fs::perms> Perms) {
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000574 return addFile(P, ModificationTime,
575 llvm::MemoryBuffer::getMemBuffer(
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000576 Buffer->getBuffer(), Buffer->getBufferIdentifier()),
577 std::move(User), std::move(Group), std::move(Type),
578 std::move(Perms));
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000579}
580
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000581static ErrorOr<detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000582lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
583 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000584 SmallString<128> Path;
585 P.toVector(Path);
586
587 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000588 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000589 assert(!EC);
590 (void)EC;
591
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000592 if (FS.useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000593 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer4ad1c432015-10-12 13:30:38 +0000594
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000595 if (Path.empty())
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000596 return Dir;
597
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000598 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000599 while (true) {
600 detail::InMemoryNode *Node = Dir->getChild(*I);
601 ++I;
602 if (!Node)
603 return errc::no_such_file_or_directory;
604
605 // Return the file if it's at the end of the path.
606 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
607 if (I == E)
608 return File;
609 return errc::no_such_file_or_directory;
610 }
611
612 // Traverse directories.
613 Dir = cast<detail::InMemoryDirectory>(Node);
614 if (I == E)
615 return Dir;
616 }
617}
618
619llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000620 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000621 if (Node)
622 return (*Node)->getStatus();
623 return Node.getError();
624}
625
626llvm::ErrorOr<std::unique_ptr<File>>
627InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000628 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000629 if (!Node)
630 return Node.getError();
631
632 // When we have a file provide a heap-allocated wrapper for the memory buffer
633 // to match the ownership semantics for File.
634 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
635 return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
636
637 // FIXME: errc::not_a_file?
638 return make_error_code(llvm::errc::invalid_argument);
639}
640
641namespace {
642/// Adaptor from InMemoryDir::iterator to directory_iterator.
643class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
644 detail::InMemoryDirectory::const_iterator I;
645 detail::InMemoryDirectory::const_iterator E;
646
647public:
648 InMemoryDirIterator() {}
649 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
650 : I(Dir.begin()), E(Dir.end()) {
651 if (I != E)
652 CurrentEntry = I->second->getStatus();
653 }
654
655 std::error_code increment() override {
656 ++I;
657 // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
658 // the rest.
659 CurrentEntry = I != E ? I->second->getStatus() : Status();
660 return std::error_code();
661 }
662};
663} // end anonymous namespace
664
665directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
666 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000667 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000668 if (!Node) {
669 EC = Node.getError();
670 return directory_iterator(std::make_shared<InMemoryDirIterator>());
671 }
672
673 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
674 return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
675
676 EC = make_error_code(llvm::errc::not_a_directory);
677 return directory_iterator(std::make_shared<InMemoryDirIterator>());
678}
Benjamin Kramere9e76072016-01-09 16:33:16 +0000679
680std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
681 SmallString<128> Path;
682 P.toVector(Path);
683
684 // Fix up relative paths. This just prepends the current working directory.
685 std::error_code EC = makeAbsolute(Path);
686 assert(!EC);
687 (void)EC;
688
689 if (useNormalizedPaths())
690 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
691
692 if (!Path.empty())
693 WorkingDirectory = Path.str();
694 return std::error_code();
695}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000696}
697}
698
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000699//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000700// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000701//===-----------------------------------------------------------------------===/
702
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000703namespace {
704
705enum EntryKind {
706 EK_Directory,
707 EK_File
708};
709
710/// \brief A single file or directory in the VFS.
711class Entry {
712 EntryKind Kind;
713 std::string Name;
714
715public:
716 virtual ~Entry();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000717 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
718 StringRef getName() const { return Name; }
719 EntryKind getKind() const { return Kind; }
720};
721
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000722class RedirectingDirectoryEntry : public Entry {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000723 std::vector<std::unique_ptr<Entry>> Contents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000724 Status S;
725
726public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000727 RedirectingDirectoryEntry(StringRef Name,
728 std::vector<std::unique_ptr<Entry>> Contents,
729 Status S)
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000730 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000731 S(std::move(S)) {}
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000732 RedirectingDirectoryEntry(StringRef Name, Status S)
733 : Entry(EK_Directory, Name), S(std::move(S)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000734 Status getStatus() { return S; }
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000735 void addContent(std::unique_ptr<Entry> Content) {
736 Contents.push_back(std::move(Content));
737 }
738 Entry *getLastContent() const { return Contents.back().get(); }
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000739 typedef decltype(Contents)::iterator iterator;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000740 iterator contents_begin() { return Contents.begin(); }
741 iterator contents_end() { return Contents.end(); }
742 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
743};
744
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000745class RedirectingFileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000746public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000747 enum NameKind {
748 NK_NotSet,
749 NK_External,
750 NK_Virtual
751 };
752private:
753 std::string ExternalContentsPath;
754 NameKind UseName;
755public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000756 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
757 NameKind UseName)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000758 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
759 UseName(UseName) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000760 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Ben Langmuirb59cf672014-02-27 00:25:12 +0000761 /// \brief whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000762 bool useExternalName(bool GlobalUseExternalName) const {
763 return UseName == NK_NotSet ? GlobalUseExternalName
764 : (UseName == NK_External);
765 }
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000766 NameKind getUseName() const { return UseName; }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000767 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
768};
769
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000770class RedirectingFileSystem;
Ben Langmuir740812b2014-06-24 19:37:16 +0000771
772class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
773 std::string Dir;
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000774 RedirectingFileSystem &FS;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000775 RedirectingDirectoryEntry::iterator Current, End;
776
Ben Langmuir740812b2014-06-24 19:37:16 +0000777public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000778 VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000779 RedirectingDirectoryEntry::iterator Begin,
780 RedirectingDirectoryEntry::iterator End,
781 std::error_code &EC);
Ben Langmuir740812b2014-06-24 19:37:16 +0000782 std::error_code increment() override;
783};
784
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000785/// \brief A virtual file system parsed from a YAML file.
786///
787/// Currently, this class allows creating virtual directories and mapping
788/// virtual file paths to existing external files, available in \c ExternalFS.
789///
790/// The basic structure of the parsed file is:
791/// \verbatim
792/// {
793/// 'version': <version number>,
794/// <optional configuration>
795/// 'roots': [
796/// <directory entries>
797/// ]
798/// }
799/// \endverbatim
800///
801/// All configuration options are optional.
802/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000803/// 'use-external-names': <boolean, default=true>
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000804/// 'overlay-relative': <boolean, default=false>
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000805/// 'ignore-non-existent-contents': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000806///
807/// Virtual directories are represented as
808/// \verbatim
809/// {
810/// 'type': 'directory',
811/// 'name': <string>,
812/// 'contents': [ <file or directory entries> ]
813/// }
814/// \endverbatim
815///
816/// The default attributes for virtual directories are:
817/// \verbatim
818/// MTime = now() when created
819/// Perms = 0777
820/// User = Group = 0
821/// Size = 0
822/// UniqueID = unspecified unique value
823/// \endverbatim
824///
825/// Re-mapped files are represented as
826/// \verbatim
827/// {
828/// 'type': 'file',
829/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000830/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000831/// 'external-contents': <path to external file>)
832/// }
833/// \endverbatim
834///
835/// and inherit their attributes from the external contents.
836///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000837/// In both cases, the 'name' field may contain multiple path components (e.g.
838/// /path/to/file). However, any directory that contains more than one child
839/// must be uniquely represented by a directory entry.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000840class RedirectingFileSystem : public vfs::FileSystem {
841 /// The root(s) of the virtual file system.
842 std::vector<std::unique_ptr<Entry>> Roots;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000843 /// \brief The file system to use for external references.
844 IntrusiveRefCntPtr<FileSystem> ExternalFS;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000845 /// If IsRelativeOverlay is set, this represents the directory
846 /// path that should be prefixed to each 'external-contents' entry
847 /// when reading from YAML files.
848 std::string ExternalContentsPrefixDir;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000849
850 /// @name Configuration
851 /// @{
852
853 /// \brief Whether to perform case-sensitive comparisons.
854 ///
855 /// Currently, case-insensitive matching only works correctly with ASCII.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000856 bool CaseSensitive = true;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000857
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000858 /// IsRelativeOverlay marks whether a IsExternalContentsPrefixDir path must
859 /// be prefixed in every 'external-contents' when reading from YAML files.
860 bool IsRelativeOverlay = false;
861
Ben Langmuirb59cf672014-02-27 00:25:12 +0000862 /// \brief Whether to use to use the value of 'external-contents' for the
863 /// names of files. This global value is overridable on a per-file basis.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000864 bool UseExternalNames = true;
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000865
866 /// \brief Whether an invalid path obtained via 'external-contents' should
867 /// cause iteration on the VFS to stop. If 'true', the VFS should ignore
868 /// the entry and continue with the next. Allows YAML files to be shared
869 /// across multiple compiler invocations regardless of prior existent
870 /// paths in 'external-contents'. This global value is overridable on a
871 /// per-file basis.
872 bool IgnoreNonExistentContents = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000873 /// @}
874
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000875 /// Virtual file paths and external files could be canonicalized without "..",
876 /// "." and "./" in their paths. FIXME: some unittests currently fail on
877 /// win32 when using remove_dots and remove_leading_dotslash on paths.
878 bool UseCanonicalizedPaths =
879#ifdef LLVM_ON_WIN32
880 false;
881#else
882 true;
883#endif
884
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000885 friend class RedirectingFileSystemParser;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000886
887private:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000888 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000889 : ExternalFS(std::move(ExternalFS)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000890
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000891 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
892 /// recursing into the contents of \p From if it is a directory.
893 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
894 sys::path::const_iterator End, Entry *From);
895
Ben Langmuir740812b2014-06-24 19:37:16 +0000896 /// \brief Get the status of a given an \c Entry.
897 ErrorOr<Status> status(const Twine &Path, Entry *E);
898
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000899public:
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +0000900 /// \brief Looks up \p Path in \c Roots.
901 ErrorOr<Entry *> lookupPath(const Twine &Path);
902
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000903 /// \brief Parses \p Buffer, which is expected to be in YAML format and
904 /// returns a virtual file system representing its contents.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000905 static RedirectingFileSystem *
906 create(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000907 SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
908 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000909
Craig Toppera798a9d2014-03-02 09:32:10 +0000910 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000911 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000912
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000913 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
914 return ExternalFS->getCurrentWorkingDirectory();
915 }
916 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
917 return ExternalFS->setCurrentWorkingDirectory(Path);
918 }
919
Ben Langmuir740812b2014-06-24 19:37:16 +0000920 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
921 ErrorOr<Entry *> E = lookupPath(Dir);
922 if (!E) {
923 EC = E.getError();
924 return directory_iterator();
925 }
926 ErrorOr<Status> S = status(Dir, *E);
927 if (!S) {
928 EC = S.getError();
929 return directory_iterator();
930 }
931 if (!S->isDirectory()) {
932 EC = std::error_code(static_cast<int>(errc::not_a_directory),
933 std::system_category());
934 return directory_iterator();
935 }
936
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000937 auto *D = cast<RedirectingDirectoryEntry>(*E);
Ben Langmuir740812b2014-06-24 19:37:16 +0000938 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
939 *this, D->contents_begin(), D->contents_end(), EC));
940 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000941
942 void setExternalContentsPrefixDir(StringRef PrefixDir) {
943 ExternalContentsPrefixDir = PrefixDir.str();
944 }
945
946 StringRef getExternalContentsPrefixDir() const {
947 return ExternalContentsPrefixDir;
948 }
949
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000950 bool ignoreNonExistentContents() const {
951 return IgnoreNonExistentContents;
952 }
953
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +0000954#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
955LLVM_DUMP_METHOD void dump() const {
956 for (const std::unique_ptr<Entry> &Root : Roots)
957 dumpEntry(Root.get());
958 }
959
960LLVM_DUMP_METHOD void dumpEntry(Entry *E, int NumSpaces = 0) const {
961 StringRef Name = E->getName();
962 for (int i = 0, e = NumSpaces; i < e; ++i)
963 dbgs() << " ";
964 dbgs() << "'" << Name.str().c_str() << "'" << "\n";
965
966 if (E->getKind() == EK_Directory) {
967 auto *DE = dyn_cast<RedirectingDirectoryEntry>(E);
968 assert(DE && "Should be a directory");
969
970 for (std::unique_ptr<Entry> &SubEntry :
971 llvm::make_range(DE->contents_begin(), DE->contents_end()))
972 dumpEntry(SubEntry.get(), NumSpaces+2);
973 }
974 }
975#endif
976
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000977};
978
979/// \brief A helper class to hold the common YAML parsing state.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000980class RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000981 yaml::Stream &Stream;
982
983 void error(yaml::Node *N, const Twine &Msg) {
984 Stream.printError(N, Msg);
985 }
986
987 // false on error
988 bool parseScalarString(yaml::Node *N, StringRef &Result,
989 SmallVectorImpl<char> &Storage) {
990 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
991 if (!S) {
992 error(N, "expected string");
993 return false;
994 }
995 Result = S->getValue(Storage);
996 return true;
997 }
998
999 // false on error
1000 bool parseScalarBool(yaml::Node *N, bool &Result) {
1001 SmallString<5> Storage;
1002 StringRef Value;
1003 if (!parseScalarString(N, Value, Storage))
1004 return false;
1005
1006 if (Value.equals_lower("true") || Value.equals_lower("on") ||
1007 Value.equals_lower("yes") || Value == "1") {
1008 Result = true;
1009 return true;
1010 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
1011 Value.equals_lower("no") || Value == "0") {
1012 Result = false;
1013 return true;
1014 }
1015
1016 error(N, "expected boolean value");
1017 return false;
1018 }
1019
1020 struct KeyStatus {
1021 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
1022 bool Required;
1023 bool Seen;
1024 };
1025 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
1026
1027 // false on error
1028 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1029 DenseMap<StringRef, KeyStatus> &Keys) {
1030 if (!Keys.count(Key)) {
1031 error(KeyNode, "unknown key");
1032 return false;
1033 }
1034 KeyStatus &S = Keys[Key];
1035 if (S.Seen) {
1036 error(KeyNode, Twine("duplicate key '") + Key + "'");
1037 return false;
1038 }
1039 S.Seen = true;
1040 return true;
1041 }
1042
1043 // false on error
1044 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
1045 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
1046 E = Keys.end();
1047 I != E; ++I) {
1048 if (I->second.Required && !I->second.Seen) {
1049 error(Obj, Twine("missing key '") + I->first + "'");
1050 return false;
1051 }
1052 }
1053 return true;
1054 }
1055
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001056 Entry *lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1057 Entry *ParentEntry = nullptr) {
1058 if (!ParentEntry) { // Look for a existent root
1059 for (const std::unique_ptr<Entry> &Root : FS->Roots) {
1060 if (Name.equals(Root->getName())) {
1061 ParentEntry = Root.get();
1062 return ParentEntry;
1063 }
1064 }
1065 } else { // Advance to the next component
1066 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1067 for (std::unique_ptr<Entry> &Content :
1068 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1069 auto *DirContent = dyn_cast<RedirectingDirectoryEntry>(Content.get());
1070 if (DirContent && Name.equals(Content->getName()))
1071 return DirContent;
1072 }
1073 }
1074
1075 // ... or create a new one
1076 std::unique_ptr<Entry> E = llvm::make_unique<RedirectingDirectoryEntry>(
Pavel Labathac71c8e2016-11-09 10:52:22 +00001077 Name,
1078 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1079 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001080
1081 if (!ParentEntry) { // Add a new root to the overlay
1082 FS->Roots.push_back(std::move(E));
1083 ParentEntry = FS->Roots.back().get();
1084 return ParentEntry;
1085 }
1086
1087 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1088 DE->addContent(std::move(E));
1089 return DE->getLastContent();
1090 }
1091
1092 void uniqueOverlayTree(RedirectingFileSystem *FS, Entry *SrcE,
1093 Entry *NewParentE = nullptr) {
1094 StringRef Name = SrcE->getName();
1095 switch (SrcE->getKind()) {
1096 case EK_Directory: {
1097 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1098 assert(DE && "Must be a directory");
1099 // Empty directories could be present in the YAML as a way to
1100 // describe a file for a current directory after some of its subdir
1101 // is parsed. This only leads to redundant walks, ignore it.
1102 if (!Name.empty())
1103 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1104 for (std::unique_ptr<Entry> &SubEntry :
1105 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1106 uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1107 break;
1108 }
1109 case EK_File: {
1110 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1111 assert(FE && "Must be a file");
1112 assert(NewParentE && "Parent entry must exist");
1113 auto *DE = dyn_cast<RedirectingDirectoryEntry>(NewParentE);
1114 DE->addContent(llvm::make_unique<RedirectingFileEntry>(
1115 Name, FE->getExternalContentsPath(), FE->getUseName()));
1116 break;
1117 }
1118 }
1119 }
1120
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001121 std::unique_ptr<Entry> parseEntry(yaml::Node *N, RedirectingFileSystem *FS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001122 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
1123 if (!M) {
1124 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +00001125 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001126 }
1127
1128 KeyStatusPair Fields[] = {
1129 KeyStatusPair("name", true),
1130 KeyStatusPair("type", true),
1131 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001132 KeyStatusPair("external-contents", false),
1133 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001134 };
1135
Craig Topperac67c052015-11-30 03:11:10 +00001136 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001137
1138 bool HasContents = false; // external or otherwise
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001139 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001140 std::string ExternalContentsPath;
1141 std::string Name;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001142 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001143 EntryKind Kind;
1144
1145 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
1146 ++I) {
1147 StringRef Key;
1148 // Reuse the buffer for key and value, since we don't look at key after
1149 // parsing value.
1150 SmallString<256> Buffer;
1151 if (!parseScalarString(I->getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001152 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001153
1154 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001155 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001156
1157 StringRef Value;
1158 if (Key == "name") {
1159 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001160 return nullptr;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001161
1162 if (FS->UseCanonicalizedPaths) {
1163 SmallString<256> Path(Value);
1164 // Guarantee that old YAML files containing paths with ".." and "."
1165 // are properly canonicalized before read into the VFS.
1166 Path = sys::path::remove_leading_dotslash(Path);
1167 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1168 Name = Path.str();
1169 } else {
1170 Name = Value;
1171 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001172 } else if (Key == "type") {
1173 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001174 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001175 if (Value == "file")
1176 Kind = EK_File;
1177 else if (Value == "directory")
1178 Kind = EK_Directory;
1179 else {
1180 error(I->getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +00001181 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001182 }
1183 } else if (Key == "contents") {
1184 if (HasContents) {
1185 error(I->getKey(),
1186 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001187 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001188 }
1189 HasContents = true;
1190 yaml::SequenceNode *Contents =
1191 dyn_cast<yaml::SequenceNode>(I->getValue());
1192 if (!Contents) {
1193 // FIXME: this is only for directories, what about files?
1194 error(I->getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +00001195 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001196 }
1197
1198 for (yaml::SequenceNode::iterator I = Contents->begin(),
1199 E = Contents->end();
1200 I != E; ++I) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001201 if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001202 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001203 else
Craig Topperf1186c52014-05-08 06:41:40 +00001204 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001205 }
1206 } else if (Key == "external-contents") {
1207 if (HasContents) {
1208 error(I->getKey(),
1209 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001210 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001211 }
1212 HasContents = true;
1213 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001214 return nullptr;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001215
1216 SmallString<256> FullPath;
1217 if (FS->IsRelativeOverlay) {
1218 FullPath = FS->getExternalContentsPrefixDir();
1219 assert(!FullPath.empty() &&
1220 "External contents prefix directory must exist");
1221 llvm::sys::path::append(FullPath, Value);
1222 } else {
1223 FullPath = Value;
1224 }
1225
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001226 if (FS->UseCanonicalizedPaths) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001227 // Guarantee that old YAML files containing paths with ".." and "."
1228 // are properly canonicalized before read into the VFS.
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001229 FullPath = sys::path::remove_leading_dotslash(FullPath);
1230 sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001231 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001232 ExternalContentsPath = FullPath.str();
Ben Langmuirb59cf672014-02-27 00:25:12 +00001233 } else if (Key == "use-external-name") {
1234 bool Val;
1235 if (!parseScalarBool(I->getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001236 return nullptr;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001237 UseExternalName = Val ? RedirectingFileEntry::NK_External
1238 : RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001239 } else {
1240 llvm_unreachable("key missing from Keys");
1241 }
1242 }
1243
1244 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001245 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001246
1247 // check for missing keys
1248 if (!HasContents) {
1249 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001250 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001251 }
1252 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001253 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001254
Ben Langmuirb59cf672014-02-27 00:25:12 +00001255 // check invalid configuration
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001256 if (Kind == EK_Directory &&
1257 UseExternalName != RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001258 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001259 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001260 }
1261
Ben Langmuir93853232014-03-05 21:32:20 +00001262 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001263 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001264 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1265 while (Trimmed.size() > RootPathLen &&
1266 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001267 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1268 // Get the last component
1269 StringRef LastComponent = sys::path::filename(Trimmed);
1270
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001271 std::unique_ptr<Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001272 switch (Kind) {
1273 case EK_File:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001274 Result = llvm::make_unique<RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001275 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001276 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001277 case EK_Directory:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001278 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001279 LastComponent, std::move(EntryArrayContents),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001280 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1281 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001282 break;
1283 }
1284
1285 StringRef Parent = sys::path::parent_path(Trimmed);
1286 if (Parent.empty())
1287 return Result;
1288
1289 // if 'name' contains multiple components, create implicit directory entries
1290 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1291 E = sys::path::rend(Parent);
1292 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001293 std::vector<std::unique_ptr<Entry>> Entries;
1294 Entries.push_back(std::move(Result));
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001295 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001296 *I, std::move(Entries),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001297 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1298 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001299 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001300 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001301 }
1302
1303public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001304 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001305
1306 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001307 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001308 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
1309 if (!Top) {
1310 error(Root, "expected mapping node");
1311 return false;
1312 }
1313
1314 KeyStatusPair Fields[] = {
1315 KeyStatusPair("version", true),
1316 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001317 KeyStatusPair("use-external-names", false),
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001318 KeyStatusPair("overlay-relative", false),
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001319 KeyStatusPair("ignore-non-existent-contents", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001320 KeyStatusPair("roots", true),
1321 };
1322
Craig Topperac67c052015-11-30 03:11:10 +00001323 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001324 std::vector<std::unique_ptr<Entry>> RootEntries;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001325
1326 // Parse configuration and 'roots'
1327 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
1328 ++I) {
1329 SmallString<10> KeyBuffer;
1330 StringRef Key;
1331 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
1332 return false;
1333
1334 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1335 return false;
1336
1337 if (Key == "roots") {
1338 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
1339 if (!Roots) {
1340 error(I->getValue(), "expected array");
1341 return false;
1342 }
1343
1344 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
1345 I != E; ++I) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001346 if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001347 RootEntries.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001348 else
1349 return false;
1350 }
1351 } else if (Key == "version") {
1352 StringRef VersionString;
1353 SmallString<4> Storage;
1354 if (!parseScalarString(I->getValue(), VersionString, Storage))
1355 return false;
1356 int Version;
1357 if (VersionString.getAsInteger<int>(10, Version)) {
1358 error(I->getValue(), "expected integer");
1359 return false;
1360 }
1361 if (Version < 0) {
1362 error(I->getValue(), "invalid version number");
1363 return false;
1364 }
1365 if (Version != 0) {
1366 error(I->getValue(), "version mismatch, expected 0");
1367 return false;
1368 }
1369 } else if (Key == "case-sensitive") {
1370 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
1371 return false;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001372 } else if (Key == "overlay-relative") {
1373 if (!parseScalarBool(I->getValue(), FS->IsRelativeOverlay))
1374 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001375 } else if (Key == "use-external-names") {
1376 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
1377 return false;
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001378 } else if (Key == "ignore-non-existent-contents") {
1379 if (!parseScalarBool(I->getValue(), FS->IgnoreNonExistentContents))
1380 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001381 } else {
1382 llvm_unreachable("key missing from Keys");
1383 }
1384 }
1385
1386 if (Stream.failed())
1387 return false;
1388
1389 if (!checkMissingKeys(Top, Keys))
1390 return false;
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001391
1392 // Now that we sucessefully parsed the YAML file, canonicalize the internal
1393 // representation to a proper directory tree so that we can search faster
1394 // inside the VFS.
1395 for (std::unique_ptr<Entry> &E : RootEntries)
1396 uniqueOverlayTree(FS, E.get());
1397
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001398 return true;
1399 }
1400};
1401} // end of anonymous namespace
1402
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001403Entry::~Entry() = default;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001404
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001405RedirectingFileSystem *
1406RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1407 SourceMgr::DiagHandlerTy DiagHandler,
1408 StringRef YAMLFilePath, void *DiagContext,
1409 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001410
1411 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001412 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001413
Ben Langmuir97882e72014-02-24 20:56:37 +00001414 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001415 yaml::document_iterator DI = Stream.begin();
1416 yaml::Node *Root = DI->getRoot();
1417 if (DI == Stream.end() || !Root) {
1418 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001419 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001420 }
1421
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001422 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001423
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001424 std::unique_ptr<RedirectingFileSystem> FS(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001425 new RedirectingFileSystem(std::move(ExternalFS)));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001426
1427 if (!YAMLFilePath.empty()) {
1428 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1429 // to each 'external-contents' path.
1430 //
1431 // Example:
1432 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
1433 // yields:
1434 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1435 //
1436 SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1437 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1438 assert(!EC && "Overlay dir final path must be absolute");
1439 (void)EC;
1440 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1441 }
1442
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001443 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001444 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001445
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001446 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001447}
1448
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001449ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001450 SmallString<256> Path;
1451 Path_.toVector(Path);
1452
1453 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001454 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001455 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001456
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001457 // Canonicalize path by removing ".", "..", "./", etc components. This is
1458 // a VFS request, do bot bother about symlinks in the path components
1459 // but canonicalize in order to perform the correct entry search.
1460 if (UseCanonicalizedPaths) {
1461 Path = sys::path::remove_leading_dotslash(Path);
1462 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1463 }
1464
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001465 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001466 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001467
1468 sys::path::const_iterator Start = sys::path::begin(Path);
1469 sys::path::const_iterator End = sys::path::end(Path);
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001470 for (const std::unique_ptr<Entry> &Root : Roots) {
1471 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001472 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001473 return Result;
1474 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001475 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001476}
1477
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001478ErrorOr<Entry *>
1479RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1480 sys::path::const_iterator End, Entry *From) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001481#ifndef LLVM_ON_WIN32
1482 assert(!isTraversalComponent(*Start) &&
1483 !isTraversalComponent(From->getName()) &&
1484 "Paths should not contain traversal components");
1485#else
1486 // FIXME: this is here to support windows, remove it once canonicalized
1487 // paths become globally default.
Bruno Cardoso Lopesbe056b12016-02-23 17:06:50 +00001488 if (Start->equals("."))
1489 ++Start;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001490#endif
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001491
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001492 StringRef FromName = From->getName();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001493
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001494 // Forward the search to the next component in case this is an empty one.
1495 if (!FromName.empty()) {
1496 if (CaseSensitive ? !Start->equals(FromName)
1497 : !Start->equals_lower(FromName))
1498 // failure to match
1499 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001500
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001501 ++Start;
1502
1503 if (Start == End) {
1504 // Match!
1505 return From;
1506 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001507 }
1508
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001509 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001510 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001511 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001512
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001513 for (const std::unique_ptr<Entry> &DirEntry :
1514 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1515 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001516 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001517 return Result;
1518 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001519 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001520}
1521
Ben Langmuirf13302e2015-12-10 23:41:39 +00001522static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1523 Status ExternalStatus) {
1524 Status S = ExternalStatus;
1525 if (!UseExternalNames)
1526 S = Status::copyWithNewName(S, Path.str());
1527 S.IsVFSMapped = true;
1528 return S;
1529}
1530
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001531ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001532 assert(E != nullptr);
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001533 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001534 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001535 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuir5de00f32014-05-23 18:15:47 +00001536 if (S)
Ben Langmuirf13302e2015-12-10 23:41:39 +00001537 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1538 *S);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001539 return S;
1540 } else { // directory
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001541 auto *DE = cast<RedirectingDirectoryEntry>(E);
Ben Langmuirf13302e2015-12-10 23:41:39 +00001542 return Status::copyWithNewName(DE->getStatus(), Path.str());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001543 }
1544}
1545
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001546ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001547 ErrorOr<Entry *> Result = lookupPath(Path);
1548 if (!Result)
1549 return Result.getError();
1550 return status(Path, *Result);
1551}
1552
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001553namespace {
Ben Langmuirf13302e2015-12-10 23:41:39 +00001554/// Provide a file wrapper with an overriden status.
1555class FileWithFixedStatus : public File {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001556 std::unique_ptr<File> InnerFile;
Ben Langmuirf13302e2015-12-10 23:41:39 +00001557 Status S;
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001558
1559public:
Ben Langmuirf13302e2015-12-10 23:41:39 +00001560 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
Benjamin Kramercfeacf52016-05-27 14:27:13 +00001561 : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001562
Ben Langmuirf13302e2015-12-10 23:41:39 +00001563 ErrorOr<Status> status() override { return S; }
1564 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +00001565 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1566 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001567 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1568 IsVolatile);
1569 }
1570 std::error_code close() override { return InnerFile->close(); }
1571};
1572} // end anonymous namespace
1573
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001574ErrorOr<std::unique_ptr<File>>
1575RedirectingFileSystem::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001576 ErrorOr<Entry *> E = lookupPath(Path);
1577 if (!E)
1578 return E.getError();
1579
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001580 auto *F = dyn_cast<RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001581 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001582 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001583
Benjamin Kramera8857962014-10-26 22:44:13 +00001584 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1585 if (!Result)
1586 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001587
Ben Langmuirf13302e2015-12-10 23:41:39 +00001588 auto ExternalStatus = (*Result)->status();
1589 if (!ExternalStatus)
1590 return ExternalStatus.getError();
Ben Langmuird066d4c2014-02-28 21:16:07 +00001591
Ben Langmuirf13302e2015-12-10 23:41:39 +00001592 // FIXME: Update the status with the name and VFSMapped.
1593 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1594 *ExternalStatus);
1595 return std::unique_ptr<File>(
1596 llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001597}
1598
1599IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001600vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001601 SourceMgr::DiagHandlerTy DiagHandler,
1602 StringRef YAMLFilePath,
1603 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001604 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001605 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001606 YAMLFilePath, DiagContext,
1607 std::move(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001608}
1609
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001610static void getVFSEntries(Entry *SrcE, SmallVectorImpl<StringRef> &Path,
1611 SmallVectorImpl<YAMLVFSEntry> &Entries) {
1612 auto Kind = SrcE->getKind();
1613 if (Kind == EK_Directory) {
1614 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1615 assert(DE && "Must be a directory");
1616 for (std::unique_ptr<Entry> &SubEntry :
1617 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1618 Path.push_back(SubEntry->getName());
1619 getVFSEntries(SubEntry.get(), Path, Entries);
1620 Path.pop_back();
1621 }
1622 return;
1623 }
1624
1625 assert(Kind == EK_File && "Must be a EK_File");
1626 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1627 assert(FE && "Must be a file");
1628 SmallString<128> VPath;
1629 for (auto &Comp : Path)
1630 llvm::sys::path::append(VPath, Comp);
1631 Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
1632}
1633
1634void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1635 SourceMgr::DiagHandlerTy DiagHandler,
1636 StringRef YAMLFilePath,
1637 SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
1638 void *DiagContext,
1639 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1640 RedirectingFileSystem *VFS = RedirectingFileSystem::create(
1641 std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
1642 std::move(ExternalFS));
1643 ErrorOr<Entry *> RootE = VFS->lookupPath("/");
1644 if (!RootE)
1645 return;
1646 SmallVector<StringRef, 8> Components;
1647 Components.push_back("/");
1648 getVFSEntries(*RootE, Components, CollectedEntries);
1649}
1650
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001651UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001652 static std::atomic<unsigned> UID;
1653 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001654 // The following assumes that uint64_t max will never collide with a real
1655 // dev_t value from the OS.
1656 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1657}
Justin Bogner9c785292014-05-20 21:43:27 +00001658
Justin Bogner9c785292014-05-20 21:43:27 +00001659void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1660 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1661 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1662 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1663 Mappings.emplace_back(VirtualPath, RealPath);
1664}
1665
Justin Bogner44fa450342014-05-21 22:46:51 +00001666namespace {
1667class JSONWriter {
1668 llvm::raw_ostream &OS;
1669 SmallVector<StringRef, 16> DirStack;
1670 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
1671 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1672 bool containedIn(StringRef Parent, StringRef Path);
1673 StringRef containedPart(StringRef Parent, StringRef Path);
1674 void startDirectory(StringRef Path);
1675 void endDirectory();
1676 void writeEntry(StringRef VPath, StringRef RPath);
1677
1678public:
1679 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001680 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
1681 Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001682 Optional<bool> IgnoreNonExistentContents, StringRef OverlayDir);
Justin Bogner44fa450342014-05-21 22:46:51 +00001683};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001684}
Justin Bogner9c785292014-05-20 21:43:27 +00001685
Justin Bogner44fa450342014-05-21 22:46:51 +00001686bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001687 using namespace llvm::sys;
1688 // Compare each path component.
1689 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1690 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1691 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1692 if (*IParent != *IChild)
1693 return false;
1694 }
1695 // Have we exhausted the parent path?
1696 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001697}
1698
Justin Bogner44fa450342014-05-21 22:46:51 +00001699StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1700 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001701 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001702 return Path.slice(Parent.size() + 1, StringRef::npos);
1703}
1704
Justin Bogner44fa450342014-05-21 22:46:51 +00001705void JSONWriter::startDirectory(StringRef Path) {
1706 StringRef Name =
1707 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1708 DirStack.push_back(Path);
1709 unsigned Indent = getDirIndent();
1710 OS.indent(Indent) << "{\n";
1711 OS.indent(Indent + 2) << "'type': 'directory',\n";
1712 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1713 OS.indent(Indent + 2) << "'contents': [\n";
1714}
1715
1716void JSONWriter::endDirectory() {
1717 unsigned Indent = getDirIndent();
1718 OS.indent(Indent + 2) << "]\n";
1719 OS.indent(Indent) << "}";
1720
1721 DirStack.pop_back();
1722}
1723
1724void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1725 unsigned Indent = getFileIndent();
1726 OS.indent(Indent) << "{\n";
1727 OS.indent(Indent + 2) << "'type': 'file',\n";
1728 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1729 OS.indent(Indent + 2) << "'external-contents': \""
1730 << llvm::yaml::escape(RPath) << "\"\n";
1731 OS.indent(Indent) << "}";
1732}
1733
1734void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001735 Optional<bool> UseExternalNames,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001736 Optional<bool> IsCaseSensitive,
1737 Optional<bool> IsOverlayRelative,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001738 Optional<bool> IgnoreNonExistentContents,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001739 StringRef OverlayDir) {
Justin Bogner44fa450342014-05-21 22:46:51 +00001740 using namespace llvm::sys;
1741
1742 OS << "{\n"
1743 " 'version': 0,\n";
1744 if (IsCaseSensitive.hasValue())
1745 OS << " 'case-sensitive': '"
1746 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001747 if (UseExternalNames.hasValue())
1748 OS << " 'use-external-names': '"
1749 << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001750 bool UseOverlayRelative = false;
1751 if (IsOverlayRelative.hasValue()) {
1752 UseOverlayRelative = IsOverlayRelative.getValue();
1753 OS << " 'overlay-relative': '"
1754 << (UseOverlayRelative ? "true" : "false") << "',\n";
1755 }
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001756 if (IgnoreNonExistentContents.hasValue())
1757 OS << " 'ignore-non-existent-contents': '"
1758 << (IgnoreNonExistentContents.getValue() ? "true" : "false") << "',\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001759 OS << " 'roots': [\n";
1760
Justin Bogner73466402014-07-15 01:24:35 +00001761 if (!Entries.empty()) {
1762 const YAMLVFSEntry &Entry = Entries.front();
1763 startDirectory(path::parent_path(Entry.VPath));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001764
1765 StringRef RPath = Entry.RPath;
1766 if (UseOverlayRelative) {
1767 unsigned OverlayDirLen = OverlayDir.size();
1768 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1769 "Overlay dir must be contained in RPath");
1770 RPath = RPath.slice(OverlayDirLen, RPath.size());
1771 }
1772
1773 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001774
Justin Bogner73466402014-07-15 01:24:35 +00001775 for (const auto &Entry : Entries.slice(1)) {
1776 StringRef Dir = path::parent_path(Entry.VPath);
1777 if (Dir == DirStack.back())
1778 OS << ",\n";
1779 else {
1780 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1781 OS << "\n";
1782 endDirectory();
1783 }
1784 OS << ",\n";
1785 startDirectory(Dir);
1786 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001787 StringRef RPath = Entry.RPath;
1788 if (UseOverlayRelative) {
1789 unsigned OverlayDirLen = OverlayDir.size();
1790 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1791 "Overlay dir must be contained in RPath");
1792 RPath = RPath.slice(OverlayDirLen, RPath.size());
1793 }
1794 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner73466402014-07-15 01:24:35 +00001795 }
1796
1797 while (!DirStack.empty()) {
1798 OS << "\n";
1799 endDirectory();
1800 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001801 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001802 }
1803
Justin Bogner73466402014-07-15 01:24:35 +00001804 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001805 << "}\n";
1806}
1807
Justin Bogner9c785292014-05-20 21:43:27 +00001808void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1809 std::sort(Mappings.begin(), Mappings.end(),
Justin Bogner44fa450342014-05-21 22:46:51 +00001810 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001811 return LHS.VPath < RHS.VPath;
1812 });
1813
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001814 JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001815 IsOverlayRelative, IgnoreNonExistentContents,
1816 OverlayDir);
Justin Bogner9c785292014-05-20 21:43:27 +00001817}
Ben Langmuir740812b2014-06-24 19:37:16 +00001818
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001819VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1820 const Twine &_Path, RedirectingFileSystem &FS,
1821 RedirectingDirectoryEntry::iterator Begin,
1822 RedirectingDirectoryEntry::iterator End, std::error_code &EC)
Ben Langmuir740812b2014-06-24 19:37:16 +00001823 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001824 while (Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001825 SmallString<128> PathStr(Dir);
1826 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001827 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001828 if (S) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001829 CurrentEntry = *S;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001830 return;
1831 }
1832 // Skip entries which do not map to a reliable external content.
1833 if (FS.ignoreNonExistentContents() &&
1834 S.getError() == llvm::errc::no_such_file_or_directory) {
1835 ++Current;
1836 continue;
1837 } else {
Ben Langmuir740812b2014-06-24 19:37:16 +00001838 EC = S.getError();
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001839 break;
1840 }
Ben Langmuir740812b2014-06-24 19:37:16 +00001841 }
1842}
1843
1844std::error_code VFSFromYamlDirIterImpl::increment() {
1845 assert(Current != End && "cannot iterate past end");
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001846 while (++Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001847 SmallString<128> PathStr(Dir);
1848 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001849 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001850 if (!S) {
1851 // Skip entries which do not map to a reliable external content.
1852 if (FS.ignoreNonExistentContents() &&
1853 S.getError() == llvm::errc::no_such_file_or_directory) {
1854 continue;
1855 } else {
1856 return S.getError();
1857 }
1858 }
Ben Langmuir740812b2014-06-24 19:37:16 +00001859 CurrentEntry = *S;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001860 break;
Bruno Cardoso Lopese43e2632016-08-12 02:17:26 +00001861 }
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001862
1863 if (Current == End)
1864 CurrentEntry = Status();
Ben Langmuir740812b2014-06-24 19:37:16 +00001865 return std::error_code();
1866}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001867
1868vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1869 const Twine &Path,
1870 std::error_code &EC)
1871 : FS(&FS_) {
1872 directory_iterator I = FS->dir_begin(Path, EC);
Juergen Ributzkaf9787432017-03-14 00:14:40 +00001873 if (I != directory_iterator()) {
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001874 State = std::make_shared<IterState>();
1875 State->push(I);
1876 }
1877}
1878
1879vfs::recursive_directory_iterator &
1880recursive_directory_iterator::increment(std::error_code &EC) {
1881 assert(FS && State && !State->empty() && "incrementing past end");
1882 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1883 vfs::directory_iterator End;
1884 if (State->top()->isDirectory()) {
1885 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001886 if (I != End) {
1887 State->push(I);
1888 return *this;
1889 }
1890 }
1891
1892 while (!State->empty() && State->top().increment(EC) == End)
1893 State->pop();
1894
1895 if (State->empty())
1896 State.reset(); // end iterator
1897
1898 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001899}