blob: b3805b2ff9203a904a0f806e39904f8b7b4ad5ab [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"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000013#include "llvm/ADT/DenseMap.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000014#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/StringExtras.h"
Ben Langmuir740812b2014-06-24 19:37:16 +000016#include "llvm/ADT/StringSet.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000017#include "llvm/ADT/iterator_range.h"
Rafael Espindola71de0b62014-06-13 17:20:50 +000018#include "llvm/Support/Errc.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000019#include "llvm/Support/MemoryBuffer.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000020#include "llvm/Support/Path.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000021#include "llvm/Support/YAMLParser.h"
Benjamin Kramerd6bbee72015-10-05 14:06:36 +000022#include "llvm/Config/llvm-config.h"
Benjamin Kramer4527fb22014-03-02 17:08:31 +000023#include <atomic>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000024#include <memory>
Ben Langmuirc8130a72014-02-20 21:59:23 +000025
Benjamin Kramerd6bbee72015-10-05 14:06:36 +000026// For chdir.
27#ifdef LLVM_ON_WIN32
28# include <direct.h>
29#else
30# include <unistd.h>
31#endif
32
Ben Langmuirc8130a72014-02-20 21:59:23 +000033using namespace clang;
34using namespace clang::vfs;
35using namespace llvm;
36using llvm::sys::fs::file_status;
37using llvm::sys::fs::file_type;
38using llvm::sys::fs::perms;
39using llvm::sys::fs::UniqueID;
40
41Status::Status(const file_status &Status)
42 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
43 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
Ben Langmuir5de00f32014-05-23 18:15:47 +000044 Type(Status.type()), Perms(Status.permissions()), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000045
Benjamin Kramer268b51a2015-10-05 13:15:33 +000046Status::Status(StringRef Name, UniqueID UID, sys::TimeValue MTime,
47 uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
48 perms Perms)
Ben Langmuirb59cf672014-02-27 00:25:12 +000049 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
Ben Langmuir5de00f32014-05-23 18:15:47 +000050 Type(Type), Perms(Perms), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000051
Benjamin Kramer268b51a2015-10-05 13:15:33 +000052Status Status::copyWithNewName(const Status &In, StringRef NewName) {
53 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
54 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
55 In.getPermissions());
56}
57
58Status Status::copyWithNewName(const file_status &In, StringRef NewName) {
59 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
60 In.getUser(), In.getGroup(), In.getSize(), In.type(),
61 In.permissions());
62}
63
Ben Langmuirc8130a72014-02-20 21:59:23 +000064bool Status::equivalent(const Status &Other) const {
65 return getUniqueID() == Other.getUniqueID();
66}
67bool Status::isDirectory() const {
68 return Type == file_type::directory_file;
69}
70bool Status::isRegularFile() const {
71 return Type == file_type::regular_file;
72}
73bool Status::isOther() const {
74 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
75}
76bool Status::isSymlink() const {
77 return Type == file_type::symlink_file;
78}
79bool Status::isStatusKnown() const {
80 return Type != file_type::status_error;
81}
82bool Status::exists() const {
83 return isStatusKnown() && Type != file_type::file_not_found;
84}
85
86File::~File() {}
87
88FileSystem::~FileSystem() {}
89
Benjamin Kramera8857962014-10-26 22:44:13 +000090ErrorOr<std::unique_ptr<MemoryBuffer>>
91FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
92 bool RequiresNullTerminator, bool IsVolatile) {
93 auto F = openFileForRead(Name);
94 if (!F)
95 return F.getError();
Ben Langmuirc8130a72014-02-20 21:59:23 +000096
Benjamin Kramera8857962014-10-26 22:44:13 +000097 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +000098}
99
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000100std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
101 auto WorkingDir = getCurrentWorkingDirectory();
102 if (!WorkingDir)
103 return WorkingDir.getError();
104
105 return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
106}
107
Ben Langmuirc8130a72014-02-20 21:59:23 +0000108//===-----------------------------------------------------------------------===/
109// RealFileSystem implementation
110//===-----------------------------------------------------------------------===/
111
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000112namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000113/// \brief Wrapper around a raw file descriptor.
114class RealFile : public File {
115 int FD;
Ben Langmuird066d4c2014-02-28 21:16:07 +0000116 Status S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000117 friend class RealFileSystem;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000118 RealFile(int FD, StringRef NewName)
119 : FD(FD), S(NewName, {}, {}, {}, {}, {},
120 llvm::sys::fs::file_type::status_error, {}) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000121 assert(FD >= 0 && "Invalid or inactive file descriptor");
122 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000123
Ben Langmuirc8130a72014-02-20 21:59:23 +0000124public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000125 ~RealFile() override;
Craig Toppera798a9d2014-03-02 09:32:10 +0000126 ErrorOr<Status> status() override;
Benjamin Kramer737501c2015-10-05 21:20:19 +0000127 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
128 int64_t FileSize,
129 bool RequiresNullTerminator,
130 bool IsVolatile) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000131 std::error_code close() override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000132};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000133} // end anonymous namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000134RealFile::~RealFile() { close(); }
Ben Langmuirc8130a72014-02-20 21:59:23 +0000135
136ErrorOr<Status> RealFile::status() {
137 assert(FD != -1 && "cannot stat closed file");
Ben Langmuird066d4c2014-02-28 21:16:07 +0000138 if (!S.isStatusKnown()) {
139 file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000140 if (std::error_code EC = sys::fs::status(FD, RealStatus))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000141 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000142 S = Status::copyWithNewName(RealStatus, S.getName());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000143 }
144 return S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000145}
146
Benjamin Kramera8857962014-10-26 22:44:13 +0000147ErrorOr<std::unique_ptr<MemoryBuffer>>
148RealFile::getBuffer(const Twine &Name, int64_t FileSize,
149 bool RequiresNullTerminator, bool IsVolatile) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000150 assert(FD != -1 && "cannot get buffer for closed file");
Benjamin Kramera8857962014-10-26 22:44:13 +0000151 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
152 IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000153}
154
155// FIXME: This is terrible, we need this for ::close.
156#if !defined(_MSC_VER) && !defined(__MINGW32__)
157#include <unistd.h>
158#include <sys/uio.h>
159#else
160#include <io.h>
161#ifndef S_ISFIFO
162#define S_ISFIFO(x) (0)
163#endif
164#endif
Rafael Espindola8e650d72014-06-12 20:37:59 +0000165std::error_code RealFile::close() {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000166 if (::close(FD))
Rafael Espindola8e650d72014-06-12 20:37:59 +0000167 return std::error_code(errno, std::generic_category());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000168 FD = -1;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000169 return std::error_code();
Ben Langmuirc8130a72014-02-20 21:59:23 +0000170}
171
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000172namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000173/// \brief The file system according to your operating system.
174class RealFileSystem : public FileSystem {
175public:
Craig Toppera798a9d2014-03-02 09:32:10 +0000176 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000177 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000178 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000179
180 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
181 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000182};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000183} // end anonymous namespace
Ben Langmuirc8130a72014-02-20 21:59:23 +0000184
185ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
186 sys::fs::file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000187 if (std::error_code EC = sys::fs::status(Path, RealStatus))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000188 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000189 return Status::copyWithNewName(RealStatus, Path.str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000190}
191
Benjamin Kramera8857962014-10-26 22:44:13 +0000192ErrorOr<std::unique_ptr<File>>
193RealFileSystem::openFileForRead(const Twine &Name) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000194 int FD;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000195 if (std::error_code EC = sys::fs::openFileForRead(Name, FD))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000196 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000197 return std::unique_ptr<File>(new RealFile(FD, Name.str()));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000198}
199
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000200llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
201 SmallString<256> Dir;
202 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
203 return EC;
204 return Dir.str().str();
205}
206
207std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
208 // FIXME: chdir is thread hostile; on the other hand, creating the same
209 // behavior as chdir is complex: chdir resolves the path once, thus
210 // guaranteeing that all subsequent relative path operations work
211 // on the same path the original chdir resulted in. This makes a
212 // difference for example on network filesystems, where symlinks might be
213 // switched during runtime of the tool. Fixing this depends on having a
214 // file system abstraction that allows openat() style interactions.
215 SmallString<256> Storage;
216 StringRef Dir = Path.toNullTerminatedStringRef(Storage);
217 if (int Err = ::chdir(Dir.data()))
218 return std::error_code(Err, std::generic_category());
219 return std::error_code();
220}
221
Ben Langmuirc8130a72014-02-20 21:59:23 +0000222IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
223 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
224 return FS;
225}
226
Ben Langmuir740812b2014-06-24 19:37:16 +0000227namespace {
228class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
229 std::string Path;
230 llvm::sys::fs::directory_iterator Iter;
231public:
232 RealFSDirIter(const Twine &_Path, std::error_code &EC)
233 : Path(_Path.str()), Iter(Path, EC) {
234 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
235 llvm::sys::fs::file_status S;
236 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000237 if (!EC)
238 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000239 }
240 }
241
242 std::error_code increment() override {
243 std::error_code EC;
244 Iter.increment(EC);
245 if (EC) {
246 return EC;
247 } else if (Iter == llvm::sys::fs::directory_iterator()) {
248 CurrentEntry = Status();
249 } else {
250 llvm::sys::fs::file_status S;
251 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000252 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000253 }
254 return EC;
255 }
256};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000257}
Ben Langmuir740812b2014-06-24 19:37:16 +0000258
259directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
260 std::error_code &EC) {
261 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
262}
263
Ben Langmuirc8130a72014-02-20 21:59:23 +0000264//===-----------------------------------------------------------------------===/
265// OverlayFileSystem implementation
266//===-----------------------------------------------------------------------===/
267OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000268 FSList.push_back(BaseFS);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000269}
270
271void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
272 FSList.push_back(FS);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000273 // Synchronize added file systems by duplicating the working directory from
274 // the first one in the list.
275 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000276}
277
278ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
279 // FIXME: handle symlinks that cross file systems
280 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
281 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000282 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000283 return Status;
284 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000285 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000286}
287
Benjamin Kramera8857962014-10-26 22:44:13 +0000288ErrorOr<std::unique_ptr<File>>
289OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000290 // FIXME: handle symlinks that cross file systems
291 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000292 auto Result = (*I)->openFileForRead(Path);
293 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
294 return Result;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000295 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000296 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000297}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000298
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000299llvm::ErrorOr<std::string>
300OverlayFileSystem::getCurrentWorkingDirectory() const {
301 // All file systems are synchronized, just take the first working directory.
302 return FSList.front()->getCurrentWorkingDirectory();
303}
304std::error_code
305OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
306 for (auto &FS : FSList)
307 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
308 return EC;
309 return std::error_code();
310}
311
Ben Langmuir740812b2014-06-24 19:37:16 +0000312clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
313
314namespace {
315class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
316 OverlayFileSystem &Overlays;
317 std::string Path;
318 OverlayFileSystem::iterator CurrentFS;
319 directory_iterator CurrentDirIter;
320 llvm::StringSet<> SeenNames;
321
322 std::error_code incrementFS() {
323 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
324 ++CurrentFS;
325 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
326 std::error_code EC;
327 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
328 if (EC && EC != errc::no_such_file_or_directory)
329 return EC;
330 if (CurrentDirIter != directory_iterator())
331 break; // found
332 }
333 return std::error_code();
334 }
335
336 std::error_code incrementDirIter(bool IsFirstTime) {
337 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
338 "incrementing past end");
339 std::error_code EC;
340 if (!IsFirstTime)
341 CurrentDirIter.increment(EC);
342 if (!EC && CurrentDirIter == directory_iterator())
343 EC = incrementFS();
344 return EC;
345 }
346
347 std::error_code incrementImpl(bool IsFirstTime) {
348 while (true) {
349 std::error_code EC = incrementDirIter(IsFirstTime);
350 if (EC || CurrentDirIter == directory_iterator()) {
351 CurrentEntry = Status();
352 return EC;
353 }
354 CurrentEntry = *CurrentDirIter;
355 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
David Blaikie61b86d42014-11-19 02:56:13 +0000356 if (SeenNames.insert(Name).second)
Ben Langmuir740812b2014-06-24 19:37:16 +0000357 return EC; // name not seen before
358 }
359 llvm_unreachable("returned above");
360 }
361
362public:
363 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
364 std::error_code &EC)
365 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
366 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
367 EC = incrementImpl(true);
368 }
369
370 std::error_code increment() override { return incrementImpl(false); }
371};
372} // end anonymous namespace
373
374directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
375 std::error_code &EC) {
376 return directory_iterator(
377 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
378}
379
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000380namespace clang {
381namespace vfs {
382namespace detail {
383
384enum InMemoryNodeKind { IME_File, IME_Directory };
385
386/// The in memory file system is a tree of Nodes. Every node can either be a
387/// file or a directory.
388class InMemoryNode {
389 Status Stat;
390 InMemoryNodeKind Kind;
391
392public:
393 InMemoryNode(Status Stat, InMemoryNodeKind Kind)
394 : Stat(std::move(Stat)), Kind(Kind) {}
395 virtual ~InMemoryNode() {}
396 const Status &getStatus() const { return Stat; }
397 InMemoryNodeKind getKind() const { return Kind; }
398 virtual std::string toString(unsigned Indent) const = 0;
399};
400
401namespace {
402class InMemoryFile : public InMemoryNode {
403 std::unique_ptr<llvm::MemoryBuffer> Buffer;
404
405public:
406 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
407 : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
408
409 llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
410 std::string toString(unsigned Indent) const override {
411 return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
412 }
413 static bool classof(const InMemoryNode *N) {
414 return N->getKind() == IME_File;
415 }
416};
417
418/// Adapt a InMemoryFile for VFS' File interface.
419class InMemoryFileAdaptor : public File {
420 InMemoryFile &Node;
421
422public:
423 explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
424
425 llvm::ErrorOr<Status> status() override { return Node.getStatus(); }
426 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +0000427 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
428 bool IsVolatile) override {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000429 llvm::MemoryBuffer *Buf = Node.getBuffer();
430 return llvm::MemoryBuffer::getMemBuffer(
431 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
432 }
433 std::error_code close() override { return std::error_code(); }
434};
435} // end anonymous namespace
436
437class InMemoryDirectory : public InMemoryNode {
438 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
439
440public:
441 InMemoryDirectory(Status Stat)
442 : InMemoryNode(std::move(Stat), IME_Directory) {}
443 InMemoryNode *getChild(StringRef Name) {
444 auto I = Entries.find(Name);
445 if (I != Entries.end())
446 return I->second.get();
447 return nullptr;
448 }
449 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
450 return Entries.insert(make_pair(Name, std::move(Child)))
451 .first->second.get();
452 }
453
454 typedef decltype(Entries)::const_iterator const_iterator;
455 const_iterator begin() const { return Entries.begin(); }
456 const_iterator end() const { return Entries.end(); }
457
458 std::string toString(unsigned Indent) const override {
459 std::string Result =
460 (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
461 for (const auto &Entry : Entries) {
462 Result += Entry.second->toString(Indent + 2);
463 }
464 return Result;
465 }
466 static bool classof(const InMemoryNode *N) {
467 return N->getKind() == IME_Directory;
468 }
469};
470}
471
472InMemoryFileSystem::InMemoryFileSystem()
473 : Root(new detail::InMemoryDirectory(
474 Status("", getNextVirtualUniqueID(), llvm::sys::TimeValue::MinTime(),
475 0, 0, 0, llvm::sys::fs::file_type::directory_file,
476 llvm::sys::fs::perms::all_all))) {}
477
478InMemoryFileSystem::~InMemoryFileSystem() {}
479
480StringRef InMemoryFileSystem::toString() const {
481 return Root->toString(/*Indent=*/0);
482}
483
484void InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
485 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
486 SmallString<128> Path;
487 P.toVector(Path);
488
489 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000490 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000491 assert(!EC);
492 (void)EC;
493
494 detail::InMemoryDirectory *Dir = Root.get();
495 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
496 while (true) {
497 StringRef Name = *I;
498 detail::InMemoryNode *Node = Dir->getChild(Name);
499 ++I;
500 if (!Node) {
501 if (I == E) {
502 // End of the path, create a new file.
503 // FIXME: expose the status details in the interface.
Benjamin Kramer1b8dbe32015-10-06 14:45:16 +0000504 Status Stat(P.str(), getNextVirtualUniqueID(),
Benjamin Kramer6b618052015-10-05 14:02:15 +0000505 llvm::sys::TimeValue(ModificationTime, 0), 0, 0,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000506 Buffer->getBufferSize(),
507 llvm::sys::fs::file_type::regular_file,
508 llvm::sys::fs::all_all);
509 Dir->addChild(Name, llvm::make_unique<detail::InMemoryFile>(
510 std::move(Stat), std::move(Buffer)));
511 return;
512 }
513
514 // Create a new directory. Use the path up to here.
515 // FIXME: expose the status details in the interface.
516 Status Stat(
517 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Benjamin Kramer6b618052015-10-05 14:02:15 +0000518 getNextVirtualUniqueID(), llvm::sys::TimeValue(ModificationTime, 0),
519 0, 0, Buffer->getBufferSize(),
520 llvm::sys::fs::file_type::directory_file, llvm::sys::fs::all_all);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000521 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
522 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
523 continue;
524 }
525
526 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node))
527 Dir = NewDir;
528 }
529}
530
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000531void InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
532 llvm::MemoryBuffer *Buffer) {
533 return addFile(P, ModificationTime,
534 llvm::MemoryBuffer::getMemBuffer(
535 Buffer->getBuffer(), Buffer->getBufferIdentifier()));
536}
537
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000538static ErrorOr<detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000539lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
540 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000541 SmallString<128> Path;
542 P.toVector(Path);
543
544 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000545 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000546 assert(!EC);
547 (void)EC;
548
549 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
550 while (true) {
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000551 // Skip over ".".
552 // FIXME: Also handle "..".
553 if (*I == ".") {
554 ++I;
555 if (I == E)
556 return Dir;
557 continue;
558 }
559
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000560 detail::InMemoryNode *Node = Dir->getChild(*I);
561 ++I;
562 if (!Node)
563 return errc::no_such_file_or_directory;
564
565 // Return the file if it's at the end of the path.
566 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
567 if (I == E)
568 return File;
569 return errc::no_such_file_or_directory;
570 }
571
572 // Traverse directories.
573 Dir = cast<detail::InMemoryDirectory>(Node);
574 if (I == E)
575 return Dir;
576 }
577}
578
579llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000580 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000581 if (Node)
582 return (*Node)->getStatus();
583 return Node.getError();
584}
585
586llvm::ErrorOr<std::unique_ptr<File>>
587InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000588 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000589 if (!Node)
590 return Node.getError();
591
592 // When we have a file provide a heap-allocated wrapper for the memory buffer
593 // to match the ownership semantics for File.
594 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
595 return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
596
597 // FIXME: errc::not_a_file?
598 return make_error_code(llvm::errc::invalid_argument);
599}
600
601namespace {
602/// Adaptor from InMemoryDir::iterator to directory_iterator.
603class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
604 detail::InMemoryDirectory::const_iterator I;
605 detail::InMemoryDirectory::const_iterator E;
606
607public:
608 InMemoryDirIterator() {}
609 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
610 : I(Dir.begin()), E(Dir.end()) {
611 if (I != E)
612 CurrentEntry = I->second->getStatus();
613 }
614
615 std::error_code increment() override {
616 ++I;
617 // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
618 // the rest.
619 CurrentEntry = I != E ? I->second->getStatus() : Status();
620 return std::error_code();
621 }
622};
623} // end anonymous namespace
624
625directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
626 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000627 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000628 if (!Node) {
629 EC = Node.getError();
630 return directory_iterator(std::make_shared<InMemoryDirIterator>());
631 }
632
633 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
634 return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
635
636 EC = make_error_code(llvm::errc::not_a_directory);
637 return directory_iterator(std::make_shared<InMemoryDirIterator>());
638}
639}
640}
641
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000642//===-----------------------------------------------------------------------===/
643// VFSFromYAML implementation
644//===-----------------------------------------------------------------------===/
645
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000646namespace {
647
648enum EntryKind {
649 EK_Directory,
650 EK_File
651};
652
653/// \brief A single file or directory in the VFS.
654class Entry {
655 EntryKind Kind;
656 std::string Name;
657
658public:
659 virtual ~Entry();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000660 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
661 StringRef getName() const { return Name; }
662 EntryKind getKind() const { return Kind; }
663};
664
665class DirectoryEntry : public Entry {
666 std::vector<Entry *> Contents;
667 Status S;
668
669public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000670 ~DirectoryEntry() override;
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000671 DirectoryEntry(StringRef Name, std::vector<Entry *> Contents, Status S)
672 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000673 S(std::move(S)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000674 Status getStatus() { return S; }
675 typedef std::vector<Entry *>::iterator iterator;
676 iterator contents_begin() { return Contents.begin(); }
677 iterator contents_end() { return Contents.end(); }
678 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
679};
680
681class FileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000682public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000683 enum NameKind {
684 NK_NotSet,
685 NK_External,
686 NK_Virtual
687 };
688private:
689 std::string ExternalContentsPath;
690 NameKind UseName;
691public:
692 FileEntry(StringRef Name, StringRef ExternalContentsPath, NameKind UseName)
693 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
694 UseName(UseName) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000695 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Ben Langmuirb59cf672014-02-27 00:25:12 +0000696 /// \brief whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000697 bool useExternalName(bool GlobalUseExternalName) const {
698 return UseName == NK_NotSet ? GlobalUseExternalName
699 : (UseName == NK_External);
700 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000701 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
702};
703
Ben Langmuir740812b2014-06-24 19:37:16 +0000704class VFSFromYAML;
705
706class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
707 std::string Dir;
708 VFSFromYAML &FS;
709 DirectoryEntry::iterator Current, End;
710public:
711 VFSFromYamlDirIterImpl(const Twine &Path, VFSFromYAML &FS,
712 DirectoryEntry::iterator Begin,
713 DirectoryEntry::iterator End, std::error_code &EC);
714 std::error_code increment() override;
715};
716
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000717/// \brief A virtual file system parsed from a YAML file.
718///
719/// Currently, this class allows creating virtual directories and mapping
720/// virtual file paths to existing external files, available in \c ExternalFS.
721///
722/// The basic structure of the parsed file is:
723/// \verbatim
724/// {
725/// 'version': <version number>,
726/// <optional configuration>
727/// 'roots': [
728/// <directory entries>
729/// ]
730/// }
731/// \endverbatim
732///
733/// All configuration options are optional.
734/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000735/// 'use-external-names': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000736///
737/// Virtual directories are represented as
738/// \verbatim
739/// {
740/// 'type': 'directory',
741/// 'name': <string>,
742/// 'contents': [ <file or directory entries> ]
743/// }
744/// \endverbatim
745///
746/// The default attributes for virtual directories are:
747/// \verbatim
748/// MTime = now() when created
749/// Perms = 0777
750/// User = Group = 0
751/// Size = 0
752/// UniqueID = unspecified unique value
753/// \endverbatim
754///
755/// Re-mapped files are represented as
756/// \verbatim
757/// {
758/// 'type': 'file',
759/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000760/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000761/// 'external-contents': <path to external file>)
762/// }
763/// \endverbatim
764///
765/// and inherit their attributes from the external contents.
766///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000767/// In both cases, the 'name' field may contain multiple path components (e.g.
768/// /path/to/file). However, any directory that contains more than one child
769/// must be uniquely represented by a directory entry.
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000770class VFSFromYAML : public vfs::FileSystem {
771 std::vector<Entry *> Roots; ///< The root(s) of the virtual file system.
772 /// \brief The file system to use for external references.
773 IntrusiveRefCntPtr<FileSystem> ExternalFS;
774
775 /// @name Configuration
776 /// @{
777
778 /// \brief Whether to perform case-sensitive comparisons.
779 ///
780 /// Currently, case-insensitive matching only works correctly with ASCII.
Ben Langmuirb59cf672014-02-27 00:25:12 +0000781 bool CaseSensitive;
782
783 /// \brief Whether to use to use the value of 'external-contents' for the
784 /// names of files. This global value is overridable on a per-file basis.
785 bool UseExternalNames;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000786 /// @}
787
788 friend class VFSFromYAMLParser;
789
790private:
791 VFSFromYAML(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000792 : ExternalFS(ExternalFS), CaseSensitive(true), UseExternalNames(true) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000793
794 /// \brief Looks up \p Path in \c Roots.
795 ErrorOr<Entry *> lookupPath(const Twine &Path);
796
797 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
798 /// recursing into the contents of \p From if it is a directory.
799 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
800 sys::path::const_iterator End, Entry *From);
801
Ben Langmuir740812b2014-06-24 19:37:16 +0000802 /// \brief Get the status of a given an \c Entry.
803 ErrorOr<Status> status(const Twine &Path, Entry *E);
804
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000805public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000806 ~VFSFromYAML() override;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000807
808 /// \brief Parses \p Buffer, which is expected to be in YAML format and
809 /// returns a virtual file system representing its contents.
Rafael Espindola04ab21d72014-08-17 22:12:58 +0000810 static VFSFromYAML *create(std::unique_ptr<MemoryBuffer> Buffer,
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000811 SourceMgr::DiagHandlerTy DiagHandler,
Ben Langmuir97882e72014-02-24 20:56:37 +0000812 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000813 IntrusiveRefCntPtr<FileSystem> ExternalFS);
814
Craig Toppera798a9d2014-03-02 09:32:10 +0000815 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000816 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000817
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000818 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
819 return ExternalFS->getCurrentWorkingDirectory();
820 }
821 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
822 return ExternalFS->setCurrentWorkingDirectory(Path);
823 }
824
Ben Langmuir740812b2014-06-24 19:37:16 +0000825 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
826 ErrorOr<Entry *> E = lookupPath(Dir);
827 if (!E) {
828 EC = E.getError();
829 return directory_iterator();
830 }
831 ErrorOr<Status> S = status(Dir, *E);
832 if (!S) {
833 EC = S.getError();
834 return directory_iterator();
835 }
836 if (!S->isDirectory()) {
837 EC = std::error_code(static_cast<int>(errc::not_a_directory),
838 std::system_category());
839 return directory_iterator();
840 }
841
842 DirectoryEntry *D = cast<DirectoryEntry>(*E);
843 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
844 *this, D->contents_begin(), D->contents_end(), EC));
845 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000846};
847
848/// \brief A helper class to hold the common YAML parsing state.
849class VFSFromYAMLParser {
850 yaml::Stream &Stream;
851
852 void error(yaml::Node *N, const Twine &Msg) {
853 Stream.printError(N, Msg);
854 }
855
856 // false on error
857 bool parseScalarString(yaml::Node *N, StringRef &Result,
858 SmallVectorImpl<char> &Storage) {
859 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
860 if (!S) {
861 error(N, "expected string");
862 return false;
863 }
864 Result = S->getValue(Storage);
865 return true;
866 }
867
868 // false on error
869 bool parseScalarBool(yaml::Node *N, bool &Result) {
870 SmallString<5> Storage;
871 StringRef Value;
872 if (!parseScalarString(N, Value, Storage))
873 return false;
874
875 if (Value.equals_lower("true") || Value.equals_lower("on") ||
876 Value.equals_lower("yes") || Value == "1") {
877 Result = true;
878 return true;
879 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
880 Value.equals_lower("no") || Value == "0") {
881 Result = false;
882 return true;
883 }
884
885 error(N, "expected boolean value");
886 return false;
887 }
888
889 struct KeyStatus {
890 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
891 bool Required;
892 bool Seen;
893 };
894 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
895
896 // false on error
897 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
898 DenseMap<StringRef, KeyStatus> &Keys) {
899 if (!Keys.count(Key)) {
900 error(KeyNode, "unknown key");
901 return false;
902 }
903 KeyStatus &S = Keys[Key];
904 if (S.Seen) {
905 error(KeyNode, Twine("duplicate key '") + Key + "'");
906 return false;
907 }
908 S.Seen = true;
909 return true;
910 }
911
912 // false on error
913 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
914 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
915 E = Keys.end();
916 I != E; ++I) {
917 if (I->second.Required && !I->second.Seen) {
918 error(Obj, Twine("missing key '") + I->first + "'");
919 return false;
920 }
921 }
922 return true;
923 }
924
925 Entry *parseEntry(yaml::Node *N) {
926 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
927 if (!M) {
928 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +0000929 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000930 }
931
932 KeyStatusPair Fields[] = {
933 KeyStatusPair("name", true),
934 KeyStatusPair("type", true),
935 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +0000936 KeyStatusPair("external-contents", false),
937 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000938 };
939
940 DenseMap<StringRef, KeyStatus> Keys(
941 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
942
943 bool HasContents = false; // external or otherwise
944 std::vector<Entry *> EntryArrayContents;
945 std::string ExternalContentsPath;
946 std::string Name;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000947 FileEntry::NameKind UseExternalName = FileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000948 EntryKind Kind;
949
950 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
951 ++I) {
952 StringRef Key;
953 // Reuse the buffer for key and value, since we don't look at key after
954 // parsing value.
955 SmallString<256> Buffer;
956 if (!parseScalarString(I->getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000957 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000958
959 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +0000960 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000961
962 StringRef Value;
963 if (Key == "name") {
964 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000965 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000966 Name = Value;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000967 } else if (Key == "type") {
968 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000969 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000970 if (Value == "file")
971 Kind = EK_File;
972 else if (Value == "directory")
973 Kind = EK_Directory;
974 else {
975 error(I->getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +0000976 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000977 }
978 } else if (Key == "contents") {
979 if (HasContents) {
980 error(I->getKey(),
981 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +0000982 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000983 }
984 HasContents = true;
985 yaml::SequenceNode *Contents =
986 dyn_cast<yaml::SequenceNode>(I->getValue());
987 if (!Contents) {
988 // FIXME: this is only for directories, what about files?
989 error(I->getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +0000990 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000991 }
992
993 for (yaml::SequenceNode::iterator I = Contents->begin(),
994 E = Contents->end();
995 I != E; ++I) {
996 if (Entry *E = parseEntry(&*I))
997 EntryArrayContents.push_back(E);
998 else
Craig Topperf1186c52014-05-08 06:41:40 +0000999 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001000 }
1001 } else if (Key == "external-contents") {
1002 if (HasContents) {
1003 error(I->getKey(),
1004 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001005 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001006 }
1007 HasContents = true;
1008 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001009 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001010 ExternalContentsPath = Value;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001011 } else if (Key == "use-external-name") {
1012 bool Val;
1013 if (!parseScalarBool(I->getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001014 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001015 UseExternalName = Val ? FileEntry::NK_External : FileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001016 } else {
1017 llvm_unreachable("key missing from Keys");
1018 }
1019 }
1020
1021 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001022 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001023
1024 // check for missing keys
1025 if (!HasContents) {
1026 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001027 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001028 }
1029 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001030 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001031
Ben Langmuirb59cf672014-02-27 00:25:12 +00001032 // check invalid configuration
1033 if (Kind == EK_Directory && UseExternalName != FileEntry::NK_NotSet) {
1034 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001035 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001036 }
1037
Ben Langmuir93853232014-03-05 21:32:20 +00001038 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001039 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001040 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1041 while (Trimmed.size() > RootPathLen &&
1042 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001043 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1044 // Get the last component
1045 StringRef LastComponent = sys::path::filename(Trimmed);
1046
Craig Topperf1186c52014-05-08 06:41:40 +00001047 Entry *Result = nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001048 switch (Kind) {
1049 case EK_File:
Chandler Carruthc72d9b32014-03-02 04:02:40 +00001050 Result = new FileEntry(LastComponent, std::move(ExternalContentsPath),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001051 UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001052 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001053 case EK_Directory:
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001054 Result = new DirectoryEntry(
1055 LastComponent, std::move(EntryArrayContents),
1056 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1057 file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001058 break;
1059 }
1060
1061 StringRef Parent = sys::path::parent_path(Trimmed);
1062 if (Parent.empty())
1063 return Result;
1064
1065 // if 'name' contains multiple components, create implicit directory entries
1066 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1067 E = sys::path::rend(Parent);
1068 I != E; ++I) {
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001069 Result = new DirectoryEntry(
1070 *I, llvm::makeArrayRef(Result),
1071 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1072 file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001073 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001074 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001075 }
1076
1077public:
1078 VFSFromYAMLParser(yaml::Stream &S) : Stream(S) {}
1079
1080 // false on error
1081 bool parse(yaml::Node *Root, VFSFromYAML *FS) {
1082 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
1083 if (!Top) {
1084 error(Root, "expected mapping node");
1085 return false;
1086 }
1087
1088 KeyStatusPair Fields[] = {
1089 KeyStatusPair("version", true),
1090 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001091 KeyStatusPair("use-external-names", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001092 KeyStatusPair("roots", true),
1093 };
1094
1095 DenseMap<StringRef, KeyStatus> Keys(
1096 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
1097
1098 // Parse configuration and 'roots'
1099 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
1100 ++I) {
1101 SmallString<10> KeyBuffer;
1102 StringRef Key;
1103 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
1104 return false;
1105
1106 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1107 return false;
1108
1109 if (Key == "roots") {
1110 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
1111 if (!Roots) {
1112 error(I->getValue(), "expected array");
1113 return false;
1114 }
1115
1116 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
1117 I != E; ++I) {
1118 if (Entry *E = parseEntry(&*I))
1119 FS->Roots.push_back(E);
1120 else
1121 return false;
1122 }
1123 } else if (Key == "version") {
1124 StringRef VersionString;
1125 SmallString<4> Storage;
1126 if (!parseScalarString(I->getValue(), VersionString, Storage))
1127 return false;
1128 int Version;
1129 if (VersionString.getAsInteger<int>(10, Version)) {
1130 error(I->getValue(), "expected integer");
1131 return false;
1132 }
1133 if (Version < 0) {
1134 error(I->getValue(), "invalid version number");
1135 return false;
1136 }
1137 if (Version != 0) {
1138 error(I->getValue(), "version mismatch, expected 0");
1139 return false;
1140 }
1141 } else if (Key == "case-sensitive") {
1142 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
1143 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001144 } else if (Key == "use-external-names") {
1145 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
1146 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001147 } else {
1148 llvm_unreachable("key missing from Keys");
1149 }
1150 }
1151
1152 if (Stream.failed())
1153 return false;
1154
1155 if (!checkMissingKeys(Top, Keys))
1156 return false;
1157 return true;
1158 }
1159};
1160} // end of anonymous namespace
1161
1162Entry::~Entry() {}
1163DirectoryEntry::~DirectoryEntry() { llvm::DeleteContainerPointers(Contents); }
1164
1165VFSFromYAML::~VFSFromYAML() { llvm::DeleteContainerPointers(Roots); }
1166
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001167VFSFromYAML *VFSFromYAML::create(std::unique_ptr<MemoryBuffer> Buffer,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001168 SourceMgr::DiagHandlerTy DiagHandler,
Ben Langmuir97882e72014-02-24 20:56:37 +00001169 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001170 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1171
1172 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001173 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001174
Ben Langmuir97882e72014-02-24 20:56:37 +00001175 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001176 yaml::document_iterator DI = Stream.begin();
1177 yaml::Node *Root = DI->getRoot();
1178 if (DI == Stream.end() || !Root) {
1179 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001180 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001181 }
1182
1183 VFSFromYAMLParser P(Stream);
1184
Ahmed Charlesb8984322014-03-07 20:03:18 +00001185 std::unique_ptr<VFSFromYAML> FS(new VFSFromYAML(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001186 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001187 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001188
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001189 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001190}
1191
1192ErrorOr<Entry *> VFSFromYAML::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001193 SmallString<256> Path;
1194 Path_.toVector(Path);
1195
1196 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001197 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001198 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001199
1200 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001201 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001202
1203 sys::path::const_iterator Start = sys::path::begin(Path);
1204 sys::path::const_iterator End = sys::path::end(Path);
1205 for (std::vector<Entry *>::iterator I = Roots.begin(), E = Roots.end();
1206 I != E; ++I) {
1207 ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
Rafael Espindola71de0b62014-06-13 17:20:50 +00001208 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001209 return Result;
1210 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001211 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001212}
1213
1214ErrorOr<Entry *> VFSFromYAML::lookupPath(sys::path::const_iterator Start,
1215 sys::path::const_iterator End,
1216 Entry *From) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001217 if (Start->equals("."))
1218 ++Start;
1219
1220 // FIXME: handle ..
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001221 if (CaseSensitive ? !Start->equals(From->getName())
1222 : !Start->equals_lower(From->getName()))
1223 // failure to match
Rafael Espindola71de0b62014-06-13 17:20:50 +00001224 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001225
1226 ++Start;
1227
1228 if (Start == End) {
1229 // Match!
1230 return From;
1231 }
1232
1233 DirectoryEntry *DE = dyn_cast<DirectoryEntry>(From);
1234 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001235 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001236
1237 for (DirectoryEntry::iterator I = DE->contents_begin(),
1238 E = DE->contents_end();
1239 I != E; ++I) {
1240 ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
Rafael Espindola71de0b62014-06-13 17:20:50 +00001241 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001242 return Result;
1243 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001244 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001245}
1246
Ben Langmuir740812b2014-06-24 19:37:16 +00001247ErrorOr<Status> VFSFromYAML::status(const Twine &Path, Entry *E) {
1248 assert(E != nullptr);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001249 std::string PathStr(Path.str());
Ben Langmuir740812b2014-06-24 19:37:16 +00001250 if (FileEntry *F = dyn_cast<FileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001251 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001252 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuird066d4c2014-02-28 21:16:07 +00001253 if (S && !F->useExternalName(UseExternalNames))
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001254 *S = Status::copyWithNewName(*S, PathStr);
Ben Langmuir5de00f32014-05-23 18:15:47 +00001255 if (S)
1256 S->IsVFSMapped = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001257 return S;
1258 } else { // directory
Ben Langmuir740812b2014-06-24 19:37:16 +00001259 DirectoryEntry *DE = cast<DirectoryEntry>(E);
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001260 return Status::copyWithNewName(DE->getStatus(), PathStr);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001261 }
1262}
1263
Ben Langmuir740812b2014-06-24 19:37:16 +00001264ErrorOr<Status> VFSFromYAML::status(const Twine &Path) {
1265 ErrorOr<Entry *> Result = lookupPath(Path);
1266 if (!Result)
1267 return Result.getError();
1268 return status(Path, *Result);
1269}
1270
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001271namespace {
1272/// Provide a file wrapper that returns the external name when asked.
1273class NamedFileAdaptor : public File {
1274 std::unique_ptr<File> InnerFile;
1275 std::string NewName;
1276
1277public:
1278 NamedFileAdaptor(std::unique_ptr<File> InnerFile, std::string NewName)
1279 : InnerFile(std::move(InnerFile)), NewName(std::move(NewName)) {}
1280
1281 llvm::ErrorOr<Status> status() override {
1282 auto InnerStatus = InnerFile->status();
1283 if (InnerStatus)
1284 return Status::copyWithNewName(*InnerStatus, NewName);
1285 return InnerStatus.getError();
1286 }
1287 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +00001288 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1289 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001290 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1291 IsVolatile);
1292 }
1293 std::error_code close() override { return InnerFile->close(); }
1294};
1295} // end anonymous namespace
1296
Benjamin Kramera8857962014-10-26 22:44:13 +00001297ErrorOr<std::unique_ptr<File>> VFSFromYAML::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001298 ErrorOr<Entry *> E = lookupPath(Path);
1299 if (!E)
1300 return E.getError();
1301
1302 FileEntry *F = dyn_cast<FileEntry>(*E);
1303 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001304 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001305
Benjamin Kramera8857962014-10-26 22:44:13 +00001306 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1307 if (!Result)
1308 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001309
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001310 if (!F->useExternalName(UseExternalNames))
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001311 return std::unique_ptr<File>(
1312 new NamedFileAdaptor(std::move(*Result), Path.str()));
Ben Langmuird066d4c2014-02-28 21:16:07 +00001313
Benjamin Kramera8857962014-10-26 22:44:13 +00001314 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001315}
1316
1317IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001318vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1319 SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001320 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001321 return VFSFromYAML::create(std::move(Buffer), DiagHandler, DiagContext,
1322 ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001323}
1324
1325UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001326 static std::atomic<unsigned> UID;
1327 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001328 // The following assumes that uint64_t max will never collide with a real
1329 // dev_t value from the OS.
1330 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1331}
Justin Bogner9c785292014-05-20 21:43:27 +00001332
1333#ifndef NDEBUG
1334static bool pathHasTraversal(StringRef Path) {
1335 using namespace llvm::sys;
1336 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
1337 if (Comp == "." || Comp == "..")
1338 return true;
1339 return false;
1340}
1341#endif
1342
1343void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1344 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1345 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1346 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1347 Mappings.emplace_back(VirtualPath, RealPath);
1348}
1349
Justin Bogner44fa450342014-05-21 22:46:51 +00001350namespace {
1351class JSONWriter {
1352 llvm::raw_ostream &OS;
1353 SmallVector<StringRef, 16> DirStack;
1354 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
1355 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1356 bool containedIn(StringRef Parent, StringRef Path);
1357 StringRef containedPart(StringRef Parent, StringRef Path);
1358 void startDirectory(StringRef Path);
1359 void endDirectory();
1360 void writeEntry(StringRef VPath, StringRef RPath);
1361
1362public:
1363 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
1364 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive);
1365};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001366}
Justin Bogner9c785292014-05-20 21:43:27 +00001367
Justin Bogner44fa450342014-05-21 22:46:51 +00001368bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001369 using namespace llvm::sys;
1370 // Compare each path component.
1371 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1372 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1373 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1374 if (*IParent != *IChild)
1375 return false;
1376 }
1377 // Have we exhausted the parent path?
1378 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001379}
1380
Justin Bogner44fa450342014-05-21 22:46:51 +00001381StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1382 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001383 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001384 return Path.slice(Parent.size() + 1, StringRef::npos);
1385}
1386
Justin Bogner44fa450342014-05-21 22:46:51 +00001387void JSONWriter::startDirectory(StringRef Path) {
1388 StringRef Name =
1389 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1390 DirStack.push_back(Path);
1391 unsigned Indent = getDirIndent();
1392 OS.indent(Indent) << "{\n";
1393 OS.indent(Indent + 2) << "'type': 'directory',\n";
1394 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1395 OS.indent(Indent + 2) << "'contents': [\n";
1396}
1397
1398void JSONWriter::endDirectory() {
1399 unsigned Indent = getDirIndent();
1400 OS.indent(Indent + 2) << "]\n";
1401 OS.indent(Indent) << "}";
1402
1403 DirStack.pop_back();
1404}
1405
1406void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1407 unsigned Indent = getFileIndent();
1408 OS.indent(Indent) << "{\n";
1409 OS.indent(Indent + 2) << "'type': 'file',\n";
1410 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1411 OS.indent(Indent + 2) << "'external-contents': \""
1412 << llvm::yaml::escape(RPath) << "\"\n";
1413 OS.indent(Indent) << "}";
1414}
1415
1416void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
1417 Optional<bool> IsCaseSensitive) {
1418 using namespace llvm::sys;
1419
1420 OS << "{\n"
1421 " 'version': 0,\n";
1422 if (IsCaseSensitive.hasValue())
1423 OS << " 'case-sensitive': '"
1424 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
1425 OS << " 'roots': [\n";
1426
Justin Bogner73466402014-07-15 01:24:35 +00001427 if (!Entries.empty()) {
1428 const YAMLVFSEntry &Entry = Entries.front();
1429 startDirectory(path::parent_path(Entry.VPath));
Justin Bogner44fa450342014-05-21 22:46:51 +00001430 writeEntry(path::filename(Entry.VPath), Entry.RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001431
Justin Bogner73466402014-07-15 01:24:35 +00001432 for (const auto &Entry : Entries.slice(1)) {
1433 StringRef Dir = path::parent_path(Entry.VPath);
1434 if (Dir == DirStack.back())
1435 OS << ",\n";
1436 else {
1437 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1438 OS << "\n";
1439 endDirectory();
1440 }
1441 OS << ",\n";
1442 startDirectory(Dir);
1443 }
1444 writeEntry(path::filename(Entry.VPath), Entry.RPath);
1445 }
1446
1447 while (!DirStack.empty()) {
1448 OS << "\n";
1449 endDirectory();
1450 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001451 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001452 }
1453
Justin Bogner73466402014-07-15 01:24:35 +00001454 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001455 << "}\n";
1456}
1457
Justin Bogner9c785292014-05-20 21:43:27 +00001458void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1459 std::sort(Mappings.begin(), Mappings.end(),
Justin Bogner44fa450342014-05-21 22:46:51 +00001460 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001461 return LHS.VPath < RHS.VPath;
1462 });
1463
Justin Bogner44fa450342014-05-21 22:46:51 +00001464 JSONWriter(OS).write(Mappings, IsCaseSensitive);
Justin Bogner9c785292014-05-20 21:43:27 +00001465}
Ben Langmuir740812b2014-06-24 19:37:16 +00001466
1467VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(const Twine &_Path,
1468 VFSFromYAML &FS,
1469 DirectoryEntry::iterator Begin,
1470 DirectoryEntry::iterator End,
1471 std::error_code &EC)
1472 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
1473 if (Current != End) {
1474 SmallString<128> PathStr(Dir);
1475 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001476 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001477 if (S)
1478 CurrentEntry = *S;
1479 else
1480 EC = S.getError();
1481 }
1482}
1483
1484std::error_code VFSFromYamlDirIterImpl::increment() {
1485 assert(Current != End && "cannot iterate past end");
1486 if (++Current != End) {
1487 SmallString<128> PathStr(Dir);
1488 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001489 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001490 if (!S)
1491 return S.getError();
1492 CurrentEntry = *S;
1493 } else {
1494 CurrentEntry = Status();
1495 }
1496 return std::error_code();
1497}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001498
1499vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1500 const Twine &Path,
1501 std::error_code &EC)
1502 : FS(&FS_) {
1503 directory_iterator I = FS->dir_begin(Path, EC);
1504 if (!EC && I != directory_iterator()) {
1505 State = std::make_shared<IterState>();
1506 State->push(I);
1507 }
1508}
1509
1510vfs::recursive_directory_iterator &
1511recursive_directory_iterator::increment(std::error_code &EC) {
1512 assert(FS && State && !State->empty() && "incrementing past end");
1513 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1514 vfs::directory_iterator End;
1515 if (State->top()->isDirectory()) {
1516 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
1517 if (EC)
1518 return *this;
1519 if (I != End) {
1520 State->push(I);
1521 return *this;
1522 }
1523 }
1524
1525 while (!State->empty() && State->top().increment(EC) == End)
1526 State->pop();
1527
1528 if (State->empty())
1529 State.reset(); // end iterator
1530
1531 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001532}