blob: 47c7fa4ba77f38ba630ed30568ecbfa55c44e87b [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;
247 EC = Iter->status(S);
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;
261 EC = Iter->status(S);
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,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000496 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
497 SmallString<128> Path;
498 P.toVector(Path);
499
500 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000501 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000502 assert(!EC);
503 (void)EC;
504
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000505 if (useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000506 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000507
508 if (Path.empty())
509 return false;
510
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000511 detail::InMemoryDirectory *Dir = Root.get();
512 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
513 while (true) {
514 StringRef Name = *I;
515 detail::InMemoryNode *Node = Dir->getChild(Name);
516 ++I;
517 if (!Node) {
518 if (I == E) {
519 // End of the path, create a new file.
520 // FIXME: expose the status details in the interface.
Benjamin Kramer1b8dbe32015-10-06 14:45:16 +0000521 Status Stat(P.str(), getNextVirtualUniqueID(),
Pavel Labathac71c8e2016-11-09 10:52:22 +0000522 llvm::sys::toTimePoint(ModificationTime), 0, 0,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000523 Buffer->getBufferSize(),
524 llvm::sys::fs::file_type::regular_file,
525 llvm::sys::fs::all_all);
526 Dir->addChild(Name, llvm::make_unique<detail::InMemoryFile>(
527 std::move(Stat), std::move(Buffer)));
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000528 return true;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000529 }
530
531 // Create a new directory. Use the path up to here.
532 // FIXME: expose the status details in the interface.
533 Status Stat(
534 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Pavel Labathac71c8e2016-11-09 10:52:22 +0000535 getNextVirtualUniqueID(), llvm::sys::toTimePoint(ModificationTime), 0,
536 0, Buffer->getBufferSize(), llvm::sys::fs::file_type::directory_file,
537 llvm::sys::fs::all_all);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000538 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
539 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
540 continue;
541 }
542
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000543 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000544 Dir = NewDir;
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000545 } else {
546 assert(isa<detail::InMemoryFile>(Node) &&
547 "Must be either file or directory!");
548
549 // Trying to insert a directory in place of a file.
550 if (I != E)
551 return false;
552
553 // Return false only if the new file is different from the existing one.
554 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
555 Buffer->getBuffer();
556 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000557 }
558}
559
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000560bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000561 llvm::MemoryBuffer *Buffer) {
562 return addFile(P, ModificationTime,
563 llvm::MemoryBuffer::getMemBuffer(
564 Buffer->getBuffer(), Buffer->getBufferIdentifier()));
565}
566
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000567static ErrorOr<detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000568lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
569 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000570 SmallString<128> Path;
571 P.toVector(Path);
572
573 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000574 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000575 assert(!EC);
576 (void)EC;
577
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000578 if (FS.useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000579 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer4ad1c432015-10-12 13:30:38 +0000580
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000581 if (Path.empty())
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000582 return Dir;
583
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000584 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000585 while (true) {
586 detail::InMemoryNode *Node = Dir->getChild(*I);
587 ++I;
588 if (!Node)
589 return errc::no_such_file_or_directory;
590
591 // Return the file if it's at the end of the path.
592 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
593 if (I == E)
594 return File;
595 return errc::no_such_file_or_directory;
596 }
597
598 // Traverse directories.
599 Dir = cast<detail::InMemoryDirectory>(Node);
600 if (I == E)
601 return Dir;
602 }
603}
604
605llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000606 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000607 if (Node)
608 return (*Node)->getStatus();
609 return Node.getError();
610}
611
612llvm::ErrorOr<std::unique_ptr<File>>
613InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000614 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000615 if (!Node)
616 return Node.getError();
617
618 // When we have a file provide a heap-allocated wrapper for the memory buffer
619 // to match the ownership semantics for File.
620 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
621 return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
622
623 // FIXME: errc::not_a_file?
624 return make_error_code(llvm::errc::invalid_argument);
625}
626
627namespace {
628/// Adaptor from InMemoryDir::iterator to directory_iterator.
629class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
630 detail::InMemoryDirectory::const_iterator I;
631 detail::InMemoryDirectory::const_iterator E;
632
633public:
634 InMemoryDirIterator() {}
635 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
636 : I(Dir.begin()), E(Dir.end()) {
637 if (I != E)
638 CurrentEntry = I->second->getStatus();
639 }
640
641 std::error_code increment() override {
642 ++I;
643 // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
644 // the rest.
645 CurrentEntry = I != E ? I->second->getStatus() : Status();
646 return std::error_code();
647 }
648};
649} // end anonymous namespace
650
651directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
652 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000653 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000654 if (!Node) {
655 EC = Node.getError();
656 return directory_iterator(std::make_shared<InMemoryDirIterator>());
657 }
658
659 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
660 return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
661
662 EC = make_error_code(llvm::errc::not_a_directory);
663 return directory_iterator(std::make_shared<InMemoryDirIterator>());
664}
Benjamin Kramere9e76072016-01-09 16:33:16 +0000665
666std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
667 SmallString<128> Path;
668 P.toVector(Path);
669
670 // Fix up relative paths. This just prepends the current working directory.
671 std::error_code EC = makeAbsolute(Path);
672 assert(!EC);
673 (void)EC;
674
675 if (useNormalizedPaths())
676 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
677
678 if (!Path.empty())
679 WorkingDirectory = Path.str();
680 return std::error_code();
681}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000682}
683}
684
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000685//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000686// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000687//===-----------------------------------------------------------------------===/
688
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000689namespace {
690
691enum EntryKind {
692 EK_Directory,
693 EK_File
694};
695
696/// \brief A single file or directory in the VFS.
697class Entry {
698 EntryKind Kind;
699 std::string Name;
700
701public:
702 virtual ~Entry();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000703 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
704 StringRef getName() const { return Name; }
705 EntryKind getKind() const { return Kind; }
706};
707
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000708class RedirectingDirectoryEntry : public Entry {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000709 std::vector<std::unique_ptr<Entry>> Contents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000710 Status S;
711
712public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000713 RedirectingDirectoryEntry(StringRef Name,
714 std::vector<std::unique_ptr<Entry>> Contents,
715 Status S)
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000716 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000717 S(std::move(S)) {}
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000718 RedirectingDirectoryEntry(StringRef Name, Status S)
719 : Entry(EK_Directory, Name), S(std::move(S)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000720 Status getStatus() { return S; }
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000721 void addContent(std::unique_ptr<Entry> Content) {
722 Contents.push_back(std::move(Content));
723 }
724 Entry *getLastContent() const { return Contents.back().get(); }
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000725 typedef decltype(Contents)::iterator iterator;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000726 iterator contents_begin() { return Contents.begin(); }
727 iterator contents_end() { return Contents.end(); }
728 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
729};
730
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000731class RedirectingFileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000732public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000733 enum NameKind {
734 NK_NotSet,
735 NK_External,
736 NK_Virtual
737 };
738private:
739 std::string ExternalContentsPath;
740 NameKind UseName;
741public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000742 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
743 NameKind UseName)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000744 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
745 UseName(UseName) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000746 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Ben Langmuirb59cf672014-02-27 00:25:12 +0000747 /// \brief whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000748 bool useExternalName(bool GlobalUseExternalName) const {
749 return UseName == NK_NotSet ? GlobalUseExternalName
750 : (UseName == NK_External);
751 }
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000752 NameKind getUseName() const { return UseName; }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000753 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
754};
755
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000756class RedirectingFileSystem;
Ben Langmuir740812b2014-06-24 19:37:16 +0000757
758class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
759 std::string Dir;
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000760 RedirectingFileSystem &FS;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000761 RedirectingDirectoryEntry::iterator Current, End;
762
Ben Langmuir740812b2014-06-24 19:37:16 +0000763public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000764 VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000765 RedirectingDirectoryEntry::iterator Begin,
766 RedirectingDirectoryEntry::iterator End,
767 std::error_code &EC);
Ben Langmuir740812b2014-06-24 19:37:16 +0000768 std::error_code increment() override;
769};
770
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000771/// \brief A virtual file system parsed from a YAML file.
772///
773/// Currently, this class allows creating virtual directories and mapping
774/// virtual file paths to existing external files, available in \c ExternalFS.
775///
776/// The basic structure of the parsed file is:
777/// \verbatim
778/// {
779/// 'version': <version number>,
780/// <optional configuration>
781/// 'roots': [
782/// <directory entries>
783/// ]
784/// }
785/// \endverbatim
786///
787/// All configuration options are optional.
788/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000789/// 'use-external-names': <boolean, default=true>
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000790/// 'overlay-relative': <boolean, default=false>
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000791/// 'ignore-non-existent-contents': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000792///
793/// Virtual directories are represented as
794/// \verbatim
795/// {
796/// 'type': 'directory',
797/// 'name': <string>,
798/// 'contents': [ <file or directory entries> ]
799/// }
800/// \endverbatim
801///
802/// The default attributes for virtual directories are:
803/// \verbatim
804/// MTime = now() when created
805/// Perms = 0777
806/// User = Group = 0
807/// Size = 0
808/// UniqueID = unspecified unique value
809/// \endverbatim
810///
811/// Re-mapped files are represented as
812/// \verbatim
813/// {
814/// 'type': 'file',
815/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000816/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000817/// 'external-contents': <path to external file>)
818/// }
819/// \endverbatim
820///
821/// and inherit their attributes from the external contents.
822///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000823/// In both cases, the 'name' field may contain multiple path components (e.g.
824/// /path/to/file). However, any directory that contains more than one child
825/// must be uniquely represented by a directory entry.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000826class RedirectingFileSystem : public vfs::FileSystem {
827 /// The root(s) of the virtual file system.
828 std::vector<std::unique_ptr<Entry>> Roots;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000829 /// \brief The file system to use for external references.
830 IntrusiveRefCntPtr<FileSystem> ExternalFS;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000831 /// If IsRelativeOverlay is set, this represents the directory
832 /// path that should be prefixed to each 'external-contents' entry
833 /// when reading from YAML files.
834 std::string ExternalContentsPrefixDir;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000835
836 /// @name Configuration
837 /// @{
838
839 /// \brief Whether to perform case-sensitive comparisons.
840 ///
841 /// Currently, case-insensitive matching only works correctly with ASCII.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000842 bool CaseSensitive = true;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000843
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000844 /// IsRelativeOverlay marks whether a IsExternalContentsPrefixDir path must
845 /// be prefixed in every 'external-contents' when reading from YAML files.
846 bool IsRelativeOverlay = false;
847
Ben Langmuirb59cf672014-02-27 00:25:12 +0000848 /// \brief Whether to use to use the value of 'external-contents' for the
849 /// names of files. This global value is overridable on a per-file basis.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000850 bool UseExternalNames = true;
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000851
852 /// \brief Whether an invalid path obtained via 'external-contents' should
853 /// cause iteration on the VFS to stop. If 'true', the VFS should ignore
854 /// the entry and continue with the next. Allows YAML files to be shared
855 /// across multiple compiler invocations regardless of prior existent
856 /// paths in 'external-contents'. This global value is overridable on a
857 /// per-file basis.
858 bool IgnoreNonExistentContents = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000859 /// @}
860
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000861 /// Virtual file paths and external files could be canonicalized without "..",
862 /// "." and "./" in their paths. FIXME: some unittests currently fail on
863 /// win32 when using remove_dots and remove_leading_dotslash on paths.
864 bool UseCanonicalizedPaths =
865#ifdef LLVM_ON_WIN32
866 false;
867#else
868 true;
869#endif
870
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000871 friend class RedirectingFileSystemParser;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000872
873private:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000874 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000875 : ExternalFS(std::move(ExternalFS)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000876
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000877 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
878 /// recursing into the contents of \p From if it is a directory.
879 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
880 sys::path::const_iterator End, Entry *From);
881
Ben Langmuir740812b2014-06-24 19:37:16 +0000882 /// \brief Get the status of a given an \c Entry.
883 ErrorOr<Status> status(const Twine &Path, Entry *E);
884
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000885public:
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +0000886 /// \brief Looks up \p Path in \c Roots.
887 ErrorOr<Entry *> lookupPath(const Twine &Path);
888
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000889 /// \brief Parses \p Buffer, which is expected to be in YAML format and
890 /// returns a virtual file system representing its contents.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000891 static RedirectingFileSystem *
892 create(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000893 SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
894 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000895
Craig Toppera798a9d2014-03-02 09:32:10 +0000896 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000897 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000898
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000899 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
900 return ExternalFS->getCurrentWorkingDirectory();
901 }
902 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
903 return ExternalFS->setCurrentWorkingDirectory(Path);
904 }
905
Ben Langmuir740812b2014-06-24 19:37:16 +0000906 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
907 ErrorOr<Entry *> E = lookupPath(Dir);
908 if (!E) {
909 EC = E.getError();
910 return directory_iterator();
911 }
912 ErrorOr<Status> S = status(Dir, *E);
913 if (!S) {
914 EC = S.getError();
915 return directory_iterator();
916 }
917 if (!S->isDirectory()) {
918 EC = std::error_code(static_cast<int>(errc::not_a_directory),
919 std::system_category());
920 return directory_iterator();
921 }
922
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000923 auto *D = cast<RedirectingDirectoryEntry>(*E);
Ben Langmuir740812b2014-06-24 19:37:16 +0000924 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
925 *this, D->contents_begin(), D->contents_end(), EC));
926 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000927
928 void setExternalContentsPrefixDir(StringRef PrefixDir) {
929 ExternalContentsPrefixDir = PrefixDir.str();
930 }
931
932 StringRef getExternalContentsPrefixDir() const {
933 return ExternalContentsPrefixDir;
934 }
935
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000936 bool ignoreNonExistentContents() const {
937 return IgnoreNonExistentContents;
938 }
939
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +0000940#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
941LLVM_DUMP_METHOD void dump() const {
942 for (const std::unique_ptr<Entry> &Root : Roots)
943 dumpEntry(Root.get());
944 }
945
946LLVM_DUMP_METHOD void dumpEntry(Entry *E, int NumSpaces = 0) const {
947 StringRef Name = E->getName();
948 for (int i = 0, e = NumSpaces; i < e; ++i)
949 dbgs() << " ";
950 dbgs() << "'" << Name.str().c_str() << "'" << "\n";
951
952 if (E->getKind() == EK_Directory) {
953 auto *DE = dyn_cast<RedirectingDirectoryEntry>(E);
954 assert(DE && "Should be a directory");
955
956 for (std::unique_ptr<Entry> &SubEntry :
957 llvm::make_range(DE->contents_begin(), DE->contents_end()))
958 dumpEntry(SubEntry.get(), NumSpaces+2);
959 }
960 }
961#endif
962
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000963};
964
965/// \brief A helper class to hold the common YAML parsing state.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000966class RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000967 yaml::Stream &Stream;
968
969 void error(yaml::Node *N, const Twine &Msg) {
970 Stream.printError(N, Msg);
971 }
972
973 // false on error
974 bool parseScalarString(yaml::Node *N, StringRef &Result,
975 SmallVectorImpl<char> &Storage) {
976 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
977 if (!S) {
978 error(N, "expected string");
979 return false;
980 }
981 Result = S->getValue(Storage);
982 return true;
983 }
984
985 // false on error
986 bool parseScalarBool(yaml::Node *N, bool &Result) {
987 SmallString<5> Storage;
988 StringRef Value;
989 if (!parseScalarString(N, Value, Storage))
990 return false;
991
992 if (Value.equals_lower("true") || Value.equals_lower("on") ||
993 Value.equals_lower("yes") || Value == "1") {
994 Result = true;
995 return true;
996 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
997 Value.equals_lower("no") || Value == "0") {
998 Result = false;
999 return true;
1000 }
1001
1002 error(N, "expected boolean value");
1003 return false;
1004 }
1005
1006 struct KeyStatus {
1007 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
1008 bool Required;
1009 bool Seen;
1010 };
1011 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
1012
1013 // false on error
1014 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1015 DenseMap<StringRef, KeyStatus> &Keys) {
1016 if (!Keys.count(Key)) {
1017 error(KeyNode, "unknown key");
1018 return false;
1019 }
1020 KeyStatus &S = Keys[Key];
1021 if (S.Seen) {
1022 error(KeyNode, Twine("duplicate key '") + Key + "'");
1023 return false;
1024 }
1025 S.Seen = true;
1026 return true;
1027 }
1028
1029 // false on error
1030 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
1031 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
1032 E = Keys.end();
1033 I != E; ++I) {
1034 if (I->second.Required && !I->second.Seen) {
1035 error(Obj, Twine("missing key '") + I->first + "'");
1036 return false;
1037 }
1038 }
1039 return true;
1040 }
1041
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001042 Entry *lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1043 Entry *ParentEntry = nullptr) {
1044 if (!ParentEntry) { // Look for a existent root
1045 for (const std::unique_ptr<Entry> &Root : FS->Roots) {
1046 if (Name.equals(Root->getName())) {
1047 ParentEntry = Root.get();
1048 return ParentEntry;
1049 }
1050 }
1051 } else { // Advance to the next component
1052 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1053 for (std::unique_ptr<Entry> &Content :
1054 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1055 auto *DirContent = dyn_cast<RedirectingDirectoryEntry>(Content.get());
1056 if (DirContent && Name.equals(Content->getName()))
1057 return DirContent;
1058 }
1059 }
1060
1061 // ... or create a new one
1062 std::unique_ptr<Entry> E = llvm::make_unique<RedirectingDirectoryEntry>(
Pavel Labathac71c8e2016-11-09 10:52:22 +00001063 Name,
1064 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1065 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001066
1067 if (!ParentEntry) { // Add a new root to the overlay
1068 FS->Roots.push_back(std::move(E));
1069 ParentEntry = FS->Roots.back().get();
1070 return ParentEntry;
1071 }
1072
1073 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1074 DE->addContent(std::move(E));
1075 return DE->getLastContent();
1076 }
1077
1078 void uniqueOverlayTree(RedirectingFileSystem *FS, Entry *SrcE,
1079 Entry *NewParentE = nullptr) {
1080 StringRef Name = SrcE->getName();
1081 switch (SrcE->getKind()) {
1082 case EK_Directory: {
1083 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1084 assert(DE && "Must be a directory");
1085 // Empty directories could be present in the YAML as a way to
1086 // describe a file for a current directory after some of its subdir
1087 // is parsed. This only leads to redundant walks, ignore it.
1088 if (!Name.empty())
1089 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1090 for (std::unique_ptr<Entry> &SubEntry :
1091 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1092 uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1093 break;
1094 }
1095 case EK_File: {
1096 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1097 assert(FE && "Must be a file");
1098 assert(NewParentE && "Parent entry must exist");
1099 auto *DE = dyn_cast<RedirectingDirectoryEntry>(NewParentE);
1100 DE->addContent(llvm::make_unique<RedirectingFileEntry>(
1101 Name, FE->getExternalContentsPath(), FE->getUseName()));
1102 break;
1103 }
1104 }
1105 }
1106
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001107 std::unique_ptr<Entry> parseEntry(yaml::Node *N, RedirectingFileSystem *FS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001108 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
1109 if (!M) {
1110 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +00001111 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001112 }
1113
1114 KeyStatusPair Fields[] = {
1115 KeyStatusPair("name", true),
1116 KeyStatusPair("type", true),
1117 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001118 KeyStatusPair("external-contents", false),
1119 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001120 };
1121
Craig Topperac67c052015-11-30 03:11:10 +00001122 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001123
1124 bool HasContents = false; // external or otherwise
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001125 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001126 std::string ExternalContentsPath;
1127 std::string Name;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001128 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001129 EntryKind Kind;
1130
1131 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
1132 ++I) {
1133 StringRef Key;
1134 // Reuse the buffer for key and value, since we don't look at key after
1135 // parsing value.
1136 SmallString<256> Buffer;
1137 if (!parseScalarString(I->getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001138 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001139
1140 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001141 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001142
1143 StringRef Value;
1144 if (Key == "name") {
1145 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001146 return nullptr;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001147
1148 if (FS->UseCanonicalizedPaths) {
1149 SmallString<256> Path(Value);
1150 // Guarantee that old YAML files containing paths with ".." and "."
1151 // are properly canonicalized before read into the VFS.
1152 Path = sys::path::remove_leading_dotslash(Path);
1153 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1154 Name = Path.str();
1155 } else {
1156 Name = Value;
1157 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001158 } else if (Key == "type") {
1159 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001160 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001161 if (Value == "file")
1162 Kind = EK_File;
1163 else if (Value == "directory")
1164 Kind = EK_Directory;
1165 else {
1166 error(I->getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +00001167 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001168 }
1169 } else if (Key == "contents") {
1170 if (HasContents) {
1171 error(I->getKey(),
1172 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001173 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001174 }
1175 HasContents = true;
1176 yaml::SequenceNode *Contents =
1177 dyn_cast<yaml::SequenceNode>(I->getValue());
1178 if (!Contents) {
1179 // FIXME: this is only for directories, what about files?
1180 error(I->getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +00001181 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001182 }
1183
1184 for (yaml::SequenceNode::iterator I = Contents->begin(),
1185 E = Contents->end();
1186 I != E; ++I) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001187 if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001188 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001189 else
Craig Topperf1186c52014-05-08 06:41:40 +00001190 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001191 }
1192 } else if (Key == "external-contents") {
1193 if (HasContents) {
1194 error(I->getKey(),
1195 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001196 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001197 }
1198 HasContents = true;
1199 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001200 return nullptr;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001201
1202 SmallString<256> FullPath;
1203 if (FS->IsRelativeOverlay) {
1204 FullPath = FS->getExternalContentsPrefixDir();
1205 assert(!FullPath.empty() &&
1206 "External contents prefix directory must exist");
1207 llvm::sys::path::append(FullPath, Value);
1208 } else {
1209 FullPath = Value;
1210 }
1211
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001212 if (FS->UseCanonicalizedPaths) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001213 // Guarantee that old YAML files containing paths with ".." and "."
1214 // are properly canonicalized before read into the VFS.
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001215 FullPath = sys::path::remove_leading_dotslash(FullPath);
1216 sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001217 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001218 ExternalContentsPath = FullPath.str();
Ben Langmuirb59cf672014-02-27 00:25:12 +00001219 } else if (Key == "use-external-name") {
1220 bool Val;
1221 if (!parseScalarBool(I->getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001222 return nullptr;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001223 UseExternalName = Val ? RedirectingFileEntry::NK_External
1224 : RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001225 } else {
1226 llvm_unreachable("key missing from Keys");
1227 }
1228 }
1229
1230 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001231 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001232
1233 // check for missing keys
1234 if (!HasContents) {
1235 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001236 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001237 }
1238 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001239 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001240
Ben Langmuirb59cf672014-02-27 00:25:12 +00001241 // check invalid configuration
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001242 if (Kind == EK_Directory &&
1243 UseExternalName != RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001244 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001245 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001246 }
1247
Ben Langmuir93853232014-03-05 21:32:20 +00001248 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001249 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001250 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1251 while (Trimmed.size() > RootPathLen &&
1252 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001253 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1254 // Get the last component
1255 StringRef LastComponent = sys::path::filename(Trimmed);
1256
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001257 std::unique_ptr<Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001258 switch (Kind) {
1259 case EK_File:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001260 Result = llvm::make_unique<RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001261 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001262 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001263 case EK_Directory:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001264 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001265 LastComponent, std::move(EntryArrayContents),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001266 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1267 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001268 break;
1269 }
1270
1271 StringRef Parent = sys::path::parent_path(Trimmed);
1272 if (Parent.empty())
1273 return Result;
1274
1275 // if 'name' contains multiple components, create implicit directory entries
1276 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1277 E = sys::path::rend(Parent);
1278 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001279 std::vector<std::unique_ptr<Entry>> Entries;
1280 Entries.push_back(std::move(Result));
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001281 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001282 *I, std::move(Entries),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001283 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1284 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001285 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001286 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001287 }
1288
1289public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001290 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001291
1292 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001293 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001294 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
1295 if (!Top) {
1296 error(Root, "expected mapping node");
1297 return false;
1298 }
1299
1300 KeyStatusPair Fields[] = {
1301 KeyStatusPair("version", true),
1302 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001303 KeyStatusPair("use-external-names", false),
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001304 KeyStatusPair("overlay-relative", false),
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001305 KeyStatusPair("ignore-non-existent-contents", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001306 KeyStatusPair("roots", true),
1307 };
1308
Craig Topperac67c052015-11-30 03:11:10 +00001309 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001310 std::vector<std::unique_ptr<Entry>> RootEntries;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001311
1312 // Parse configuration and 'roots'
1313 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
1314 ++I) {
1315 SmallString<10> KeyBuffer;
1316 StringRef Key;
1317 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
1318 return false;
1319
1320 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1321 return false;
1322
1323 if (Key == "roots") {
1324 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
1325 if (!Roots) {
1326 error(I->getValue(), "expected array");
1327 return false;
1328 }
1329
1330 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
1331 I != E; ++I) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001332 if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001333 RootEntries.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001334 else
1335 return false;
1336 }
1337 } else if (Key == "version") {
1338 StringRef VersionString;
1339 SmallString<4> Storage;
1340 if (!parseScalarString(I->getValue(), VersionString, Storage))
1341 return false;
1342 int Version;
1343 if (VersionString.getAsInteger<int>(10, Version)) {
1344 error(I->getValue(), "expected integer");
1345 return false;
1346 }
1347 if (Version < 0) {
1348 error(I->getValue(), "invalid version number");
1349 return false;
1350 }
1351 if (Version != 0) {
1352 error(I->getValue(), "version mismatch, expected 0");
1353 return false;
1354 }
1355 } else if (Key == "case-sensitive") {
1356 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
1357 return false;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001358 } else if (Key == "overlay-relative") {
1359 if (!parseScalarBool(I->getValue(), FS->IsRelativeOverlay))
1360 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001361 } else if (Key == "use-external-names") {
1362 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
1363 return false;
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001364 } else if (Key == "ignore-non-existent-contents") {
1365 if (!parseScalarBool(I->getValue(), FS->IgnoreNonExistentContents))
1366 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001367 } else {
1368 llvm_unreachable("key missing from Keys");
1369 }
1370 }
1371
1372 if (Stream.failed())
1373 return false;
1374
1375 if (!checkMissingKeys(Top, Keys))
1376 return false;
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001377
1378 // Now that we sucessefully parsed the YAML file, canonicalize the internal
1379 // representation to a proper directory tree so that we can search faster
1380 // inside the VFS.
1381 for (std::unique_ptr<Entry> &E : RootEntries)
1382 uniqueOverlayTree(FS, E.get());
1383
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001384 return true;
1385 }
1386};
1387} // end of anonymous namespace
1388
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001389Entry::~Entry() = default;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001390
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001391RedirectingFileSystem *
1392RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1393 SourceMgr::DiagHandlerTy DiagHandler,
1394 StringRef YAMLFilePath, void *DiagContext,
1395 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001396
1397 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001398 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001399
Ben Langmuir97882e72014-02-24 20:56:37 +00001400 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001401 yaml::document_iterator DI = Stream.begin();
1402 yaml::Node *Root = DI->getRoot();
1403 if (DI == Stream.end() || !Root) {
1404 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001405 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001406 }
1407
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001408 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001409
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001410 std::unique_ptr<RedirectingFileSystem> FS(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001411 new RedirectingFileSystem(std::move(ExternalFS)));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001412
1413 if (!YAMLFilePath.empty()) {
1414 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1415 // to each 'external-contents' path.
1416 //
1417 // Example:
1418 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
1419 // yields:
1420 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1421 //
1422 SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1423 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1424 assert(!EC && "Overlay dir final path must be absolute");
1425 (void)EC;
1426 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1427 }
1428
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001429 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001430 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001431
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001432 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001433}
1434
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001435ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001436 SmallString<256> Path;
1437 Path_.toVector(Path);
1438
1439 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001440 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001441 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001442
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001443 // Canonicalize path by removing ".", "..", "./", etc components. This is
1444 // a VFS request, do bot bother about symlinks in the path components
1445 // but canonicalize in order to perform the correct entry search.
1446 if (UseCanonicalizedPaths) {
1447 Path = sys::path::remove_leading_dotslash(Path);
1448 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1449 }
1450
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001451 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001452 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001453
1454 sys::path::const_iterator Start = sys::path::begin(Path);
1455 sys::path::const_iterator End = sys::path::end(Path);
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001456 for (const std::unique_ptr<Entry> &Root : Roots) {
1457 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001458 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001459 return Result;
1460 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001461 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001462}
1463
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001464ErrorOr<Entry *>
1465RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1466 sys::path::const_iterator End, Entry *From) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001467#ifndef LLVM_ON_WIN32
1468 assert(!isTraversalComponent(*Start) &&
1469 !isTraversalComponent(From->getName()) &&
1470 "Paths should not contain traversal components");
1471#else
1472 // FIXME: this is here to support windows, remove it once canonicalized
1473 // paths become globally default.
Bruno Cardoso Lopesbe056b12016-02-23 17:06:50 +00001474 if (Start->equals("."))
1475 ++Start;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001476#endif
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001477
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001478 StringRef FromName = From->getName();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001479
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001480 // Forward the search to the next component in case this is an empty one.
1481 if (!FromName.empty()) {
1482 if (CaseSensitive ? !Start->equals(FromName)
1483 : !Start->equals_lower(FromName))
1484 // failure to match
1485 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001486
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001487 ++Start;
1488
1489 if (Start == End) {
1490 // Match!
1491 return From;
1492 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001493 }
1494
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001495 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001496 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001497 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001498
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001499 for (const std::unique_ptr<Entry> &DirEntry :
1500 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1501 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001502 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001503 return Result;
1504 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001505 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001506}
1507
Ben Langmuirf13302e2015-12-10 23:41:39 +00001508static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1509 Status ExternalStatus) {
1510 Status S = ExternalStatus;
1511 if (!UseExternalNames)
1512 S = Status::copyWithNewName(S, Path.str());
1513 S.IsVFSMapped = true;
1514 return S;
1515}
1516
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001517ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001518 assert(E != nullptr);
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001519 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001520 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001521 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuir5de00f32014-05-23 18:15:47 +00001522 if (S)
Ben Langmuirf13302e2015-12-10 23:41:39 +00001523 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1524 *S);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001525 return S;
1526 } else { // directory
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001527 auto *DE = cast<RedirectingDirectoryEntry>(E);
Ben Langmuirf13302e2015-12-10 23:41:39 +00001528 return Status::copyWithNewName(DE->getStatus(), Path.str());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001529 }
1530}
1531
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001532ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001533 ErrorOr<Entry *> Result = lookupPath(Path);
1534 if (!Result)
1535 return Result.getError();
1536 return status(Path, *Result);
1537}
1538
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001539namespace {
Ben Langmuirf13302e2015-12-10 23:41:39 +00001540/// Provide a file wrapper with an overriden status.
1541class FileWithFixedStatus : public File {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001542 std::unique_ptr<File> InnerFile;
Ben Langmuirf13302e2015-12-10 23:41:39 +00001543 Status S;
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001544
1545public:
Ben Langmuirf13302e2015-12-10 23:41:39 +00001546 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
Benjamin Kramercfeacf52016-05-27 14:27:13 +00001547 : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001548
Ben Langmuirf13302e2015-12-10 23:41:39 +00001549 ErrorOr<Status> status() override { return S; }
1550 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +00001551 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1552 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001553 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1554 IsVolatile);
1555 }
1556 std::error_code close() override { return InnerFile->close(); }
1557};
1558} // end anonymous namespace
1559
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001560ErrorOr<std::unique_ptr<File>>
1561RedirectingFileSystem::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001562 ErrorOr<Entry *> E = lookupPath(Path);
1563 if (!E)
1564 return E.getError();
1565
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001566 auto *F = dyn_cast<RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001567 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001568 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001569
Benjamin Kramera8857962014-10-26 22:44:13 +00001570 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1571 if (!Result)
1572 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001573
Ben Langmuirf13302e2015-12-10 23:41:39 +00001574 auto ExternalStatus = (*Result)->status();
1575 if (!ExternalStatus)
1576 return ExternalStatus.getError();
Ben Langmuird066d4c2014-02-28 21:16:07 +00001577
Ben Langmuirf13302e2015-12-10 23:41:39 +00001578 // FIXME: Update the status with the name and VFSMapped.
1579 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1580 *ExternalStatus);
1581 return std::unique_ptr<File>(
1582 llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001583}
1584
1585IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001586vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001587 SourceMgr::DiagHandlerTy DiagHandler,
1588 StringRef YAMLFilePath,
1589 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001590 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001591 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001592 YAMLFilePath, DiagContext,
1593 std::move(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001594}
1595
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001596static void getVFSEntries(Entry *SrcE, SmallVectorImpl<StringRef> &Path,
1597 SmallVectorImpl<YAMLVFSEntry> &Entries) {
1598 auto Kind = SrcE->getKind();
1599 if (Kind == EK_Directory) {
1600 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1601 assert(DE && "Must be a directory");
1602 for (std::unique_ptr<Entry> &SubEntry :
1603 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1604 Path.push_back(SubEntry->getName());
1605 getVFSEntries(SubEntry.get(), Path, Entries);
1606 Path.pop_back();
1607 }
1608 return;
1609 }
1610
1611 assert(Kind == EK_File && "Must be a EK_File");
1612 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1613 assert(FE && "Must be a file");
1614 SmallString<128> VPath;
1615 for (auto &Comp : Path)
1616 llvm::sys::path::append(VPath, Comp);
1617 Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
1618}
1619
1620void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1621 SourceMgr::DiagHandlerTy DiagHandler,
1622 StringRef YAMLFilePath,
1623 SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
1624 void *DiagContext,
1625 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1626 RedirectingFileSystem *VFS = RedirectingFileSystem::create(
1627 std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
1628 std::move(ExternalFS));
1629 ErrorOr<Entry *> RootE = VFS->lookupPath("/");
1630 if (!RootE)
1631 return;
1632 SmallVector<StringRef, 8> Components;
1633 Components.push_back("/");
1634 getVFSEntries(*RootE, Components, CollectedEntries);
1635}
1636
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001637UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001638 static std::atomic<unsigned> UID;
1639 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001640 // The following assumes that uint64_t max will never collide with a real
1641 // dev_t value from the OS.
1642 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1643}
Justin Bogner9c785292014-05-20 21:43:27 +00001644
Justin Bogner9c785292014-05-20 21:43:27 +00001645void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1646 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1647 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1648 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1649 Mappings.emplace_back(VirtualPath, RealPath);
1650}
1651
Justin Bogner44fa450342014-05-21 22:46:51 +00001652namespace {
1653class JSONWriter {
1654 llvm::raw_ostream &OS;
1655 SmallVector<StringRef, 16> DirStack;
1656 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
1657 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1658 bool containedIn(StringRef Parent, StringRef Path);
1659 StringRef containedPart(StringRef Parent, StringRef Path);
1660 void startDirectory(StringRef Path);
1661 void endDirectory();
1662 void writeEntry(StringRef VPath, StringRef RPath);
1663
1664public:
1665 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001666 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
1667 Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001668 Optional<bool> IgnoreNonExistentContents, StringRef OverlayDir);
Justin Bogner44fa450342014-05-21 22:46:51 +00001669};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001670}
Justin Bogner9c785292014-05-20 21:43:27 +00001671
Justin Bogner44fa450342014-05-21 22:46:51 +00001672bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001673 using namespace llvm::sys;
1674 // Compare each path component.
1675 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1676 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1677 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1678 if (*IParent != *IChild)
1679 return false;
1680 }
1681 // Have we exhausted the parent path?
1682 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001683}
1684
Justin Bogner44fa450342014-05-21 22:46:51 +00001685StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1686 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001687 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001688 return Path.slice(Parent.size() + 1, StringRef::npos);
1689}
1690
Justin Bogner44fa450342014-05-21 22:46:51 +00001691void JSONWriter::startDirectory(StringRef Path) {
1692 StringRef Name =
1693 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1694 DirStack.push_back(Path);
1695 unsigned Indent = getDirIndent();
1696 OS.indent(Indent) << "{\n";
1697 OS.indent(Indent + 2) << "'type': 'directory',\n";
1698 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1699 OS.indent(Indent + 2) << "'contents': [\n";
1700}
1701
1702void JSONWriter::endDirectory() {
1703 unsigned Indent = getDirIndent();
1704 OS.indent(Indent + 2) << "]\n";
1705 OS.indent(Indent) << "}";
1706
1707 DirStack.pop_back();
1708}
1709
1710void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1711 unsigned Indent = getFileIndent();
1712 OS.indent(Indent) << "{\n";
1713 OS.indent(Indent + 2) << "'type': 'file',\n";
1714 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1715 OS.indent(Indent + 2) << "'external-contents': \""
1716 << llvm::yaml::escape(RPath) << "\"\n";
1717 OS.indent(Indent) << "}";
1718}
1719
1720void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001721 Optional<bool> UseExternalNames,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001722 Optional<bool> IsCaseSensitive,
1723 Optional<bool> IsOverlayRelative,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001724 Optional<bool> IgnoreNonExistentContents,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001725 StringRef OverlayDir) {
Justin Bogner44fa450342014-05-21 22:46:51 +00001726 using namespace llvm::sys;
1727
1728 OS << "{\n"
1729 " 'version': 0,\n";
1730 if (IsCaseSensitive.hasValue())
1731 OS << " 'case-sensitive': '"
1732 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001733 if (UseExternalNames.hasValue())
1734 OS << " 'use-external-names': '"
1735 << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001736 bool UseOverlayRelative = false;
1737 if (IsOverlayRelative.hasValue()) {
1738 UseOverlayRelative = IsOverlayRelative.getValue();
1739 OS << " 'overlay-relative': '"
1740 << (UseOverlayRelative ? "true" : "false") << "',\n";
1741 }
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001742 if (IgnoreNonExistentContents.hasValue())
1743 OS << " 'ignore-non-existent-contents': '"
1744 << (IgnoreNonExistentContents.getValue() ? "true" : "false") << "',\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001745 OS << " 'roots': [\n";
1746
Justin Bogner73466402014-07-15 01:24:35 +00001747 if (!Entries.empty()) {
1748 const YAMLVFSEntry &Entry = Entries.front();
1749 startDirectory(path::parent_path(Entry.VPath));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001750
1751 StringRef RPath = Entry.RPath;
1752 if (UseOverlayRelative) {
1753 unsigned OverlayDirLen = OverlayDir.size();
1754 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1755 "Overlay dir must be contained in RPath");
1756 RPath = RPath.slice(OverlayDirLen, RPath.size());
1757 }
1758
1759 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001760
Justin Bogner73466402014-07-15 01:24:35 +00001761 for (const auto &Entry : Entries.slice(1)) {
1762 StringRef Dir = path::parent_path(Entry.VPath);
1763 if (Dir == DirStack.back())
1764 OS << ",\n";
1765 else {
1766 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1767 OS << "\n";
1768 endDirectory();
1769 }
1770 OS << ",\n";
1771 startDirectory(Dir);
1772 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001773 StringRef RPath = Entry.RPath;
1774 if (UseOverlayRelative) {
1775 unsigned OverlayDirLen = OverlayDir.size();
1776 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1777 "Overlay dir must be contained in RPath");
1778 RPath = RPath.slice(OverlayDirLen, RPath.size());
1779 }
1780 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner73466402014-07-15 01:24:35 +00001781 }
1782
1783 while (!DirStack.empty()) {
1784 OS << "\n";
1785 endDirectory();
1786 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001787 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001788 }
1789
Justin Bogner73466402014-07-15 01:24:35 +00001790 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001791 << "}\n";
1792}
1793
Justin Bogner9c785292014-05-20 21:43:27 +00001794void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1795 std::sort(Mappings.begin(), Mappings.end(),
Justin Bogner44fa450342014-05-21 22:46:51 +00001796 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001797 return LHS.VPath < RHS.VPath;
1798 });
1799
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001800 JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001801 IsOverlayRelative, IgnoreNonExistentContents,
1802 OverlayDir);
Justin Bogner9c785292014-05-20 21:43:27 +00001803}
Ben Langmuir740812b2014-06-24 19:37:16 +00001804
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001805VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1806 const Twine &_Path, RedirectingFileSystem &FS,
1807 RedirectingDirectoryEntry::iterator Begin,
1808 RedirectingDirectoryEntry::iterator End, std::error_code &EC)
Ben Langmuir740812b2014-06-24 19:37:16 +00001809 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001810 while (Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001811 SmallString<128> PathStr(Dir);
1812 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001813 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001814 if (S) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001815 CurrentEntry = *S;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001816 return;
1817 }
1818 // Skip entries which do not map to a reliable external content.
1819 if (FS.ignoreNonExistentContents() &&
1820 S.getError() == llvm::errc::no_such_file_or_directory) {
1821 ++Current;
1822 continue;
1823 } else {
Ben Langmuir740812b2014-06-24 19:37:16 +00001824 EC = S.getError();
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001825 break;
1826 }
Ben Langmuir740812b2014-06-24 19:37:16 +00001827 }
1828}
1829
1830std::error_code VFSFromYamlDirIterImpl::increment() {
1831 assert(Current != End && "cannot iterate past end");
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001832 while (++Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001833 SmallString<128> PathStr(Dir);
1834 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001835 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001836 if (!S) {
1837 // Skip entries which do not map to a reliable external content.
1838 if (FS.ignoreNonExistentContents() &&
1839 S.getError() == llvm::errc::no_such_file_or_directory) {
1840 continue;
1841 } else {
1842 return S.getError();
1843 }
1844 }
Ben Langmuir740812b2014-06-24 19:37:16 +00001845 CurrentEntry = *S;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001846 break;
Bruno Cardoso Lopese43e2632016-08-12 02:17:26 +00001847 }
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001848
1849 if (Current == End)
1850 CurrentEntry = Status();
Ben Langmuir740812b2014-06-24 19:37:16 +00001851 return std::error_code();
1852}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001853
1854vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1855 const Twine &Path,
1856 std::error_code &EC)
1857 : FS(&FS_) {
1858 directory_iterator I = FS->dir_begin(Path, EC);
Juergen Ributzkaf9787432017-03-14 00:14:40 +00001859 if (I != directory_iterator()) {
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001860 State = std::make_shared<IterState>();
1861 State->push(I);
1862 }
1863}
1864
1865vfs::recursive_directory_iterator &
1866recursive_directory_iterator::increment(std::error_code &EC) {
1867 assert(FS && State && !State->empty() && "incrementing past end");
1868 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1869 vfs::directory_iterator End;
1870 if (State->top()->isDirectory()) {
1871 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001872 if (I != End) {
1873 State->push(I);
1874 return *this;
1875 }
1876 }
1877
1878 while (!State->empty() && State->top().increment(EC) == End)
1879 State->pop();
1880
1881 if (State->empty())
1882 State.reset(); // end iterator
1883
1884 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001885}