blob: 34d1b0592ddbfc89486f9b8f516c8684334fc089 [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"
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +000019#include "llvm/Support/Debug.h"
Rafael Espindola71de0b62014-06-13 17:20:50 +000020#include "llvm/Support/Errc.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000021#include "llvm/Support/MemoryBuffer.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000022#include "llvm/Support/Path.h"
David Majnemer6a6206d2016-03-04 05:26:14 +000023#include "llvm/Support/Process.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000024#include "llvm/Support/YAMLParser.h"
Benjamin Kramerd6bbee72015-10-05 14:06:36 +000025#include "llvm/Config/llvm-config.h"
Benjamin Kramer4527fb22014-03-02 17:08:31 +000026#include <atomic>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000027#include <memory>
Ben Langmuirc8130a72014-02-20 21:59:23 +000028
Benjamin Kramerd6bbee72015-10-05 14:06:36 +000029// For chdir.
30#ifdef LLVM_ON_WIN32
31# include <direct.h>
32#else
33# include <unistd.h>
34#endif
35
Ben Langmuirc8130a72014-02-20 21:59:23 +000036using namespace clang;
37using namespace clang::vfs;
38using namespace llvm;
39using llvm::sys::fs::file_status;
40using llvm::sys::fs::file_type;
41using llvm::sys::fs::perms;
42using llvm::sys::fs::UniqueID;
43
44Status::Status(const file_status &Status)
45 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
46 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
Ben Langmuir5de00f32014-05-23 18:15:47 +000047 Type(Status.type()), Perms(Status.permissions()), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000048
Benjamin Kramer268b51a2015-10-05 13:15:33 +000049Status::Status(StringRef Name, UniqueID UID, sys::TimeValue MTime,
50 uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
51 perms Perms)
Ben Langmuirb59cf672014-02-27 00:25:12 +000052 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
Ben Langmuir5de00f32014-05-23 18:15:47 +000053 Type(Type), Perms(Perms), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000054
Benjamin Kramer268b51a2015-10-05 13:15:33 +000055Status Status::copyWithNewName(const Status &In, StringRef NewName) {
56 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
57 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
58 In.getPermissions());
59}
60
61Status Status::copyWithNewName(const file_status &In, StringRef NewName) {
62 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
63 In.getUser(), In.getGroup(), In.getSize(), In.type(),
64 In.permissions());
65}
66
Ben Langmuirc8130a72014-02-20 21:59:23 +000067bool Status::equivalent(const Status &Other) const {
68 return getUniqueID() == Other.getUniqueID();
69}
70bool Status::isDirectory() const {
71 return Type == file_type::directory_file;
72}
73bool Status::isRegularFile() const {
74 return Type == file_type::regular_file;
75}
76bool Status::isOther() const {
77 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
78}
79bool Status::isSymlink() const {
80 return Type == file_type::symlink_file;
81}
82bool Status::isStatusKnown() const {
83 return Type != file_type::status_error;
84}
85bool Status::exists() const {
86 return isStatusKnown() && Type != file_type::file_not_found;
87}
88
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000089File::~File() {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000090
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000091FileSystem::~FileSystem() {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000092
Benjamin Kramera8857962014-10-26 22:44:13 +000093ErrorOr<std::unique_ptr<MemoryBuffer>>
94FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
95 bool RequiresNullTerminator, bool IsVolatile) {
96 auto F = openFileForRead(Name);
97 if (!F)
98 return F.getError();
Ben Langmuirc8130a72014-02-20 21:59:23 +000099
Benjamin Kramera8857962014-10-26 22:44:13 +0000100 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000101}
102
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000103std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
Bob Wilsonf43354f2016-03-26 18:55:13 +0000104 if (llvm::sys::path::is_absolute(Path))
105 return std::error_code();
106
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000107 auto WorkingDir = getCurrentWorkingDirectory();
108 if (!WorkingDir)
109 return WorkingDir.getError();
110
111 return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
112}
113
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000114bool FileSystem::exists(const Twine &Path) {
115 auto Status = status(Path);
116 return Status && Status->exists();
117}
118
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000119#ifndef NDEBUG
120static bool isTraversalComponent(StringRef Component) {
121 return Component.equals("..") || Component.equals(".");
122}
123
124static bool pathHasTraversal(StringRef Path) {
125 using namespace llvm::sys;
126 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
127 if (isTraversalComponent(Comp))
128 return true;
129 return false;
130}
131#endif
132
Ben Langmuirc8130a72014-02-20 21:59:23 +0000133//===-----------------------------------------------------------------------===/
134// RealFileSystem implementation
135//===-----------------------------------------------------------------------===/
136
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000137namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000138/// \brief Wrapper around a raw file descriptor.
139class RealFile : public File {
140 int FD;
Ben Langmuird066d4c2014-02-28 21:16:07 +0000141 Status S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000142 friend class RealFileSystem;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000143 RealFile(int FD, StringRef NewName)
144 : FD(FD), S(NewName, {}, {}, {}, {}, {},
145 llvm::sys::fs::file_type::status_error, {}) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000146 assert(FD >= 0 && "Invalid or inactive file descriptor");
147 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000148
Ben Langmuirc8130a72014-02-20 21:59:23 +0000149public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000150 ~RealFile() override;
Craig Toppera798a9d2014-03-02 09:32:10 +0000151 ErrorOr<Status> status() override;
Benjamin Kramer737501c2015-10-05 21:20:19 +0000152 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
153 int64_t FileSize,
154 bool RequiresNullTerminator,
155 bool IsVolatile) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000156 std::error_code close() override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000157};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000158} // end anonymous namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000159RealFile::~RealFile() { close(); }
Ben Langmuirc8130a72014-02-20 21:59:23 +0000160
161ErrorOr<Status> RealFile::status() {
162 assert(FD != -1 && "cannot stat closed file");
Ben Langmuird066d4c2014-02-28 21:16:07 +0000163 if (!S.isStatusKnown()) {
164 file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000165 if (std::error_code EC = sys::fs::status(FD, RealStatus))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000166 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000167 S = Status::copyWithNewName(RealStatus, S.getName());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000168 }
169 return S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000170}
171
Benjamin Kramera8857962014-10-26 22:44:13 +0000172ErrorOr<std::unique_ptr<MemoryBuffer>>
173RealFile::getBuffer(const Twine &Name, int64_t FileSize,
174 bool RequiresNullTerminator, bool IsVolatile) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000175 assert(FD != -1 && "cannot get buffer for closed file");
Benjamin Kramera8857962014-10-26 22:44:13 +0000176 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
177 IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000178}
179
Rafael Espindola8e650d72014-06-12 20:37:59 +0000180std::error_code RealFile::close() {
David Majnemer6a6206d2016-03-04 05:26:14 +0000181 std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000182 FD = -1;
David Majnemer6a6206d2016-03-04 05:26:14 +0000183 return EC;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000184}
185
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000186namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000187/// \brief The file system according to your operating system.
188class RealFileSystem : public FileSystem {
189public:
Craig Toppera798a9d2014-03-02 09:32:10 +0000190 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000191 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000192 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000193
194 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
195 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000196};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000197} // end anonymous namespace
Ben Langmuirc8130a72014-02-20 21:59:23 +0000198
199ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
200 sys::fs::file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000201 if (std::error_code EC = sys::fs::status(Path, RealStatus))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000202 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000203 return Status::copyWithNewName(RealStatus, Path.str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000204}
205
Benjamin Kramera8857962014-10-26 22:44:13 +0000206ErrorOr<std::unique_ptr<File>>
207RealFileSystem::openFileForRead(const Twine &Name) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000208 int FD;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000209 if (std::error_code EC = sys::fs::openFileForRead(Name, FD))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000210 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000211 return std::unique_ptr<File>(new RealFile(FD, Name.str()));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000212}
213
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000214llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
215 SmallString<256> Dir;
216 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
217 return EC;
218 return Dir.str().str();
219}
220
221std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
222 // FIXME: chdir is thread hostile; on the other hand, creating the same
223 // behavior as chdir is complex: chdir resolves the path once, thus
224 // guaranteeing that all subsequent relative path operations work
225 // on the same path the original chdir resulted in. This makes a
226 // difference for example on network filesystems, where symlinks might be
227 // switched during runtime of the tool. Fixing this depends on having a
228 // file system abstraction that allows openat() style interactions.
229 SmallString<256> Storage;
230 StringRef Dir = Path.toNullTerminatedStringRef(Storage);
231 if (int Err = ::chdir(Dir.data()))
232 return std::error_code(Err, std::generic_category());
233 return std::error_code();
234}
235
Ben Langmuirc8130a72014-02-20 21:59:23 +0000236IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
237 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
238 return FS;
239}
240
Ben Langmuir740812b2014-06-24 19:37:16 +0000241namespace {
242class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
243 std::string Path;
244 llvm::sys::fs::directory_iterator Iter;
245public:
246 RealFSDirIter(const Twine &_Path, std::error_code &EC)
247 : Path(_Path.str()), Iter(Path, EC) {
248 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
249 llvm::sys::fs::file_status S;
250 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000251 if (!EC)
252 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000253 }
254 }
255
256 std::error_code increment() override {
257 std::error_code EC;
258 Iter.increment(EC);
259 if (EC) {
260 return EC;
261 } else if (Iter == llvm::sys::fs::directory_iterator()) {
262 CurrentEntry = Status();
263 } else {
264 llvm::sys::fs::file_status S;
265 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000266 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000267 }
268 return EC;
269 }
270};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000271}
Ben Langmuir740812b2014-06-24 19:37:16 +0000272
273directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
274 std::error_code &EC) {
275 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
276}
277
Ben Langmuirc8130a72014-02-20 21:59:23 +0000278//===-----------------------------------------------------------------------===/
279// OverlayFileSystem implementation
280//===-----------------------------------------------------------------------===/
281OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000282 FSList.push_back(BaseFS);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000283}
284
285void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
286 FSList.push_back(FS);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000287 // Synchronize added file systems by duplicating the working directory from
288 // the first one in the list.
289 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000290}
291
292ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
293 // FIXME: handle symlinks that cross file systems
294 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
295 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000296 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000297 return Status;
298 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000299 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000300}
301
Benjamin Kramera8857962014-10-26 22:44:13 +0000302ErrorOr<std::unique_ptr<File>>
303OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000304 // FIXME: handle symlinks that cross file systems
305 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000306 auto Result = (*I)->openFileForRead(Path);
307 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
308 return Result;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000309 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000310 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000311}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000312
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000313llvm::ErrorOr<std::string>
314OverlayFileSystem::getCurrentWorkingDirectory() const {
315 // All file systems are synchronized, just take the first working directory.
316 return FSList.front()->getCurrentWorkingDirectory();
317}
318std::error_code
319OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
320 for (auto &FS : FSList)
321 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
322 return EC;
323 return std::error_code();
324}
325
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000326clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
Ben Langmuir740812b2014-06-24 19:37:16 +0000327
328namespace {
329class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
330 OverlayFileSystem &Overlays;
331 std::string Path;
332 OverlayFileSystem::iterator CurrentFS;
333 directory_iterator CurrentDirIter;
334 llvm::StringSet<> SeenNames;
335
336 std::error_code incrementFS() {
337 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
338 ++CurrentFS;
339 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
340 std::error_code EC;
341 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
342 if (EC && EC != errc::no_such_file_or_directory)
343 return EC;
344 if (CurrentDirIter != directory_iterator())
345 break; // found
346 }
347 return std::error_code();
348 }
349
350 std::error_code incrementDirIter(bool IsFirstTime) {
351 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
352 "incrementing past end");
353 std::error_code EC;
354 if (!IsFirstTime)
355 CurrentDirIter.increment(EC);
356 if (!EC && CurrentDirIter == directory_iterator())
357 EC = incrementFS();
358 return EC;
359 }
360
361 std::error_code incrementImpl(bool IsFirstTime) {
362 while (true) {
363 std::error_code EC = incrementDirIter(IsFirstTime);
364 if (EC || CurrentDirIter == directory_iterator()) {
365 CurrentEntry = Status();
366 return EC;
367 }
368 CurrentEntry = *CurrentDirIter;
369 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
David Blaikie61b86d42014-11-19 02:56:13 +0000370 if (SeenNames.insert(Name).second)
Ben Langmuir740812b2014-06-24 19:37:16 +0000371 return EC; // name not seen before
372 }
373 llvm_unreachable("returned above");
374 }
375
376public:
377 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
378 std::error_code &EC)
379 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
380 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
381 EC = incrementImpl(true);
382 }
383
384 std::error_code increment() override { return incrementImpl(false); }
385};
386} // end anonymous namespace
387
388directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
389 std::error_code &EC) {
390 return directory_iterator(
391 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
392}
393
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000394namespace clang {
395namespace vfs {
396namespace detail {
397
398enum InMemoryNodeKind { IME_File, IME_Directory };
399
400/// The in memory file system is a tree of Nodes. Every node can either be a
401/// file or a directory.
402class InMemoryNode {
403 Status Stat;
404 InMemoryNodeKind Kind;
405
406public:
407 InMemoryNode(Status Stat, InMemoryNodeKind Kind)
408 : Stat(std::move(Stat)), Kind(Kind) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000409 virtual ~InMemoryNode() {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000410 const Status &getStatus() const { return Stat; }
411 InMemoryNodeKind getKind() const { return Kind; }
412 virtual std::string toString(unsigned Indent) const = 0;
413};
414
415namespace {
416class InMemoryFile : public InMemoryNode {
417 std::unique_ptr<llvm::MemoryBuffer> Buffer;
418
419public:
420 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
421 : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
422
423 llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
424 std::string toString(unsigned Indent) const override {
425 return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
426 }
427 static bool classof(const InMemoryNode *N) {
428 return N->getKind() == IME_File;
429 }
430};
431
432/// Adapt a InMemoryFile for VFS' File interface.
433class InMemoryFileAdaptor : public File {
434 InMemoryFile &Node;
435
436public:
437 explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
438
439 llvm::ErrorOr<Status> status() override { return Node.getStatus(); }
440 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +0000441 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
442 bool IsVolatile) override {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000443 llvm::MemoryBuffer *Buf = Node.getBuffer();
444 return llvm::MemoryBuffer::getMemBuffer(
445 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
446 }
447 std::error_code close() override { return std::error_code(); }
448};
449} // end anonymous namespace
450
451class InMemoryDirectory : public InMemoryNode {
452 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
453
454public:
455 InMemoryDirectory(Status Stat)
456 : InMemoryNode(std::move(Stat), IME_Directory) {}
457 InMemoryNode *getChild(StringRef Name) {
458 auto I = Entries.find(Name);
459 if (I != Entries.end())
460 return I->second.get();
461 return nullptr;
462 }
463 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
464 return Entries.insert(make_pair(Name, std::move(Child)))
465 .first->second.get();
466 }
467
468 typedef decltype(Entries)::const_iterator const_iterator;
469 const_iterator begin() const { return Entries.begin(); }
470 const_iterator end() const { return Entries.end(); }
471
472 std::string toString(unsigned Indent) const override {
473 std::string Result =
474 (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
475 for (const auto &Entry : Entries) {
476 Result += Entry.second->toString(Indent + 2);
477 }
478 return Result;
479 }
480 static bool classof(const InMemoryNode *N) {
481 return N->getKind() == IME_Directory;
482 }
483};
484}
485
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000486InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000487 : Root(new detail::InMemoryDirectory(
488 Status("", getNextVirtualUniqueID(), llvm::sys::TimeValue::MinTime(),
489 0, 0, 0, llvm::sys::fs::file_type::directory_file,
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000490 llvm::sys::fs::perms::all_all))),
491 UseNormalizedPaths(UseNormalizedPaths) {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000492
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000493InMemoryFileSystem::~InMemoryFileSystem() {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000494
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000495std::string InMemoryFileSystem::toString() const {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000496 return Root->toString(/*Indent=*/0);
497}
498
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000499bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000500 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
501 SmallString<128> Path;
502 P.toVector(Path);
503
504 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000505 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000506 assert(!EC);
507 (void)EC;
508
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000509 if (useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000510 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000511
512 if (Path.empty())
513 return false;
514
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000515 detail::InMemoryDirectory *Dir = Root.get();
516 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
517 while (true) {
518 StringRef Name = *I;
519 detail::InMemoryNode *Node = Dir->getChild(Name);
520 ++I;
521 if (!Node) {
522 if (I == E) {
523 // End of the path, create a new file.
524 // FIXME: expose the status details in the interface.
Benjamin Kramer1b8dbe32015-10-06 14:45:16 +0000525 Status Stat(P.str(), getNextVirtualUniqueID(),
Benjamin Kramer6b618052015-10-05 14:02:15 +0000526 llvm::sys::TimeValue(ModificationTime, 0), 0, 0,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000527 Buffer->getBufferSize(),
528 llvm::sys::fs::file_type::regular_file,
529 llvm::sys::fs::all_all);
530 Dir->addChild(Name, llvm::make_unique<detail::InMemoryFile>(
531 std::move(Stat), std::move(Buffer)));
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000532 return true;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000533 }
534
535 // Create a new directory. Use the path up to here.
536 // FIXME: expose the status details in the interface.
537 Status Stat(
538 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Benjamin Kramer6b618052015-10-05 14:02:15 +0000539 getNextVirtualUniqueID(), llvm::sys::TimeValue(ModificationTime, 0),
540 0, 0, Buffer->getBufferSize(),
541 llvm::sys::fs::file_type::directory_file, llvm::sys::fs::all_all);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000542 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
543 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
544 continue;
545 }
546
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000547 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000548 Dir = NewDir;
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000549 } else {
550 assert(isa<detail::InMemoryFile>(Node) &&
551 "Must be either file or directory!");
552
553 // Trying to insert a directory in place of a file.
554 if (I != E)
555 return false;
556
557 // Return false only if the new file is different from the existing one.
558 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
559 Buffer->getBuffer();
560 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000561 }
562}
563
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000564bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000565 llvm::MemoryBuffer *Buffer) {
566 return addFile(P, ModificationTime,
567 llvm::MemoryBuffer::getMemBuffer(
568 Buffer->getBuffer(), Buffer->getBufferIdentifier()));
569}
570
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000571static ErrorOr<detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000572lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
573 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000574 SmallString<128> Path;
575 P.toVector(Path);
576
577 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000578 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000579 assert(!EC);
580 (void)EC;
581
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000582 if (FS.useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000583 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer4ad1c432015-10-12 13:30:38 +0000584
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000585 if (Path.empty())
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000586 return Dir;
587
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000588 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000589 while (true) {
590 detail::InMemoryNode *Node = Dir->getChild(*I);
591 ++I;
592 if (!Node)
593 return errc::no_such_file_or_directory;
594
595 // Return the file if it's at the end of the path.
596 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
597 if (I == E)
598 return File;
599 return errc::no_such_file_or_directory;
600 }
601
602 // Traverse directories.
603 Dir = cast<detail::InMemoryDirectory>(Node);
604 if (I == E)
605 return Dir;
606 }
607}
608
609llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000610 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000611 if (Node)
612 return (*Node)->getStatus();
613 return Node.getError();
614}
615
616llvm::ErrorOr<std::unique_ptr<File>>
617InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000618 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000619 if (!Node)
620 return Node.getError();
621
622 // When we have a file provide a heap-allocated wrapper for the memory buffer
623 // to match the ownership semantics for File.
624 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
625 return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
626
627 // FIXME: errc::not_a_file?
628 return make_error_code(llvm::errc::invalid_argument);
629}
630
631namespace {
632/// Adaptor from InMemoryDir::iterator to directory_iterator.
633class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
634 detail::InMemoryDirectory::const_iterator I;
635 detail::InMemoryDirectory::const_iterator E;
636
637public:
638 InMemoryDirIterator() {}
639 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
640 : I(Dir.begin()), E(Dir.end()) {
641 if (I != E)
642 CurrentEntry = I->second->getStatus();
643 }
644
645 std::error_code increment() override {
646 ++I;
647 // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
648 // the rest.
649 CurrentEntry = I != E ? I->second->getStatus() : Status();
650 return std::error_code();
651 }
652};
653} // end anonymous namespace
654
655directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
656 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000657 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000658 if (!Node) {
659 EC = Node.getError();
660 return directory_iterator(std::make_shared<InMemoryDirIterator>());
661 }
662
663 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
664 return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
665
666 EC = make_error_code(llvm::errc::not_a_directory);
667 return directory_iterator(std::make_shared<InMemoryDirIterator>());
668}
Benjamin Kramere9e76072016-01-09 16:33:16 +0000669
670std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
671 SmallString<128> Path;
672 P.toVector(Path);
673
674 // Fix up relative paths. This just prepends the current working directory.
675 std::error_code EC = makeAbsolute(Path);
676 assert(!EC);
677 (void)EC;
678
679 if (useNormalizedPaths())
680 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
681
682 if (!Path.empty())
683 WorkingDirectory = Path.str();
684 return std::error_code();
685}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000686}
687}
688
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000689//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000690// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000691//===-----------------------------------------------------------------------===/
692
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000693namespace {
694
695enum EntryKind {
696 EK_Directory,
697 EK_File
698};
699
700/// \brief A single file or directory in the VFS.
701class Entry {
702 EntryKind Kind;
703 std::string Name;
704
705public:
706 virtual ~Entry();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000707 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
708 StringRef getName() const { return Name; }
709 EntryKind getKind() const { return Kind; }
710};
711
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000712class RedirectingDirectoryEntry : public Entry {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000713 std::vector<std::unique_ptr<Entry>> Contents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000714 Status S;
715
716public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000717 RedirectingDirectoryEntry(StringRef Name,
718 std::vector<std::unique_ptr<Entry>> Contents,
719 Status S)
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000720 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000721 S(std::move(S)) {}
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000722 RedirectingDirectoryEntry(StringRef Name, Status S)
723 : Entry(EK_Directory, Name), S(std::move(S)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000724 Status getStatus() { return S; }
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000725 void addContent(std::unique_ptr<Entry> Content) {
726 Contents.push_back(std::move(Content));
727 }
728 Entry *getLastContent() const { return Contents.back().get(); }
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000729 typedef decltype(Contents)::iterator iterator;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000730 iterator contents_begin() { return Contents.begin(); }
731 iterator contents_end() { return Contents.end(); }
732 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
733};
734
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000735class RedirectingFileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000736public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000737 enum NameKind {
738 NK_NotSet,
739 NK_External,
740 NK_Virtual
741 };
742private:
743 std::string ExternalContentsPath;
744 NameKind UseName;
745public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000746 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
747 NameKind UseName)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000748 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
749 UseName(UseName) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000750 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Ben Langmuirb59cf672014-02-27 00:25:12 +0000751 /// \brief whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000752 bool useExternalName(bool GlobalUseExternalName) const {
753 return UseName == NK_NotSet ? GlobalUseExternalName
754 : (UseName == NK_External);
755 }
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000756 NameKind getUseName() const { return UseName; }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000757 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
758};
759
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000760class RedirectingFileSystem;
Ben Langmuir740812b2014-06-24 19:37:16 +0000761
762class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
763 std::string Dir;
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000764 RedirectingFileSystem &FS;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000765 RedirectingDirectoryEntry::iterator Current, End;
766
Ben Langmuir740812b2014-06-24 19:37:16 +0000767public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000768 VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000769 RedirectingDirectoryEntry::iterator Begin,
770 RedirectingDirectoryEntry::iterator End,
771 std::error_code &EC);
Ben Langmuir740812b2014-06-24 19:37:16 +0000772 std::error_code increment() override;
773};
774
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000775/// \brief A virtual file system parsed from a YAML file.
776///
777/// Currently, this class allows creating virtual directories and mapping
778/// virtual file paths to existing external files, available in \c ExternalFS.
779///
780/// The basic structure of the parsed file is:
781/// \verbatim
782/// {
783/// 'version': <version number>,
784/// <optional configuration>
785/// 'roots': [
786/// <directory entries>
787/// ]
788/// }
789/// \endverbatim
790///
791/// All configuration options are optional.
792/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000793/// 'use-external-names': <boolean, default=true>
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000794/// 'overlay-relative': <boolean, default=false>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000795///
796/// Virtual directories are represented as
797/// \verbatim
798/// {
799/// 'type': 'directory',
800/// 'name': <string>,
801/// 'contents': [ <file or directory entries> ]
802/// }
803/// \endverbatim
804///
805/// The default attributes for virtual directories are:
806/// \verbatim
807/// MTime = now() when created
808/// Perms = 0777
809/// User = Group = 0
810/// Size = 0
811/// UniqueID = unspecified unique value
812/// \endverbatim
813///
814/// Re-mapped files are represented as
815/// \verbatim
816/// {
817/// 'type': 'file',
818/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000819/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000820/// 'external-contents': <path to external file>)
821/// }
822/// \endverbatim
823///
824/// and inherit their attributes from the external contents.
825///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000826/// In both cases, the 'name' field may contain multiple path components (e.g.
827/// /path/to/file). However, any directory that contains more than one child
828/// must be uniquely represented by a directory entry.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000829class RedirectingFileSystem : public vfs::FileSystem {
830 /// The root(s) of the virtual file system.
831 std::vector<std::unique_ptr<Entry>> Roots;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000832 /// \brief The file system to use for external references.
833 IntrusiveRefCntPtr<FileSystem> ExternalFS;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000834 /// If IsRelativeOverlay is set, this represents the directory
835 /// path that should be prefixed to each 'external-contents' entry
836 /// when reading from YAML files.
837 std::string ExternalContentsPrefixDir;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000838
839 /// @name Configuration
840 /// @{
841
842 /// \brief Whether to perform case-sensitive comparisons.
843 ///
844 /// Currently, case-insensitive matching only works correctly with ASCII.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000845 bool CaseSensitive = true;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000846
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000847 /// IsRelativeOverlay marks whether a IsExternalContentsPrefixDir path must
848 /// be prefixed in every 'external-contents' when reading from YAML files.
849 bool IsRelativeOverlay = false;
850
Ben Langmuirb59cf672014-02-27 00:25:12 +0000851 /// \brief Whether to use to use the value of 'external-contents' for the
852 /// names of files. This global value is overridable on a per-file basis.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000853 bool UseExternalNames = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000854 /// @}
855
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000856 /// Virtual file paths and external files could be canonicalized without "..",
857 /// "." and "./" in their paths. FIXME: some unittests currently fail on
858 /// win32 when using remove_dots and remove_leading_dotslash on paths.
859 bool UseCanonicalizedPaths =
860#ifdef LLVM_ON_WIN32
861 false;
862#else
863 true;
864#endif
865
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000866 friend class RedirectingFileSystemParser;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000867
868private:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000869 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000870 : ExternalFS(ExternalFS) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000871
872 /// \brief Looks up \p Path in \c Roots.
873 ErrorOr<Entry *> lookupPath(const Twine &Path);
874
875 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
876 /// recursing into the contents of \p From if it is a directory.
877 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
878 sys::path::const_iterator End, Entry *From);
879
Ben Langmuir740812b2014-06-24 19:37:16 +0000880 /// \brief Get the status of a given an \c Entry.
881 ErrorOr<Status> status(const Twine &Path, Entry *E);
882
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000883public:
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000884 /// \brief Parses \p Buffer, which is expected to be in YAML format and
885 /// returns a virtual file system representing its contents.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000886 static RedirectingFileSystem *
887 create(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000888 SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
889 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000890
Craig Toppera798a9d2014-03-02 09:32:10 +0000891 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000892 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000893
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000894 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
895 return ExternalFS->getCurrentWorkingDirectory();
896 }
897 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
898 return ExternalFS->setCurrentWorkingDirectory(Path);
899 }
900
Ben Langmuir740812b2014-06-24 19:37:16 +0000901 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
902 ErrorOr<Entry *> E = lookupPath(Dir);
903 if (!E) {
904 EC = E.getError();
905 return directory_iterator();
906 }
907 ErrorOr<Status> S = status(Dir, *E);
908 if (!S) {
909 EC = S.getError();
910 return directory_iterator();
911 }
912 if (!S->isDirectory()) {
913 EC = std::error_code(static_cast<int>(errc::not_a_directory),
914 std::system_category());
915 return directory_iterator();
916 }
917
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000918 auto *D = cast<RedirectingDirectoryEntry>(*E);
Ben Langmuir740812b2014-06-24 19:37:16 +0000919 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
920 *this, D->contents_begin(), D->contents_end(), EC));
921 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000922
923 void setExternalContentsPrefixDir(StringRef PrefixDir) {
924 ExternalContentsPrefixDir = PrefixDir.str();
925 }
926
927 StringRef getExternalContentsPrefixDir() const {
928 return ExternalContentsPrefixDir;
929 }
930
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +0000931#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
932LLVM_DUMP_METHOD void dump() const {
933 for (const std::unique_ptr<Entry> &Root : Roots)
934 dumpEntry(Root.get());
935 }
936
937LLVM_DUMP_METHOD void dumpEntry(Entry *E, int NumSpaces = 0) const {
938 StringRef Name = E->getName();
939 for (int i = 0, e = NumSpaces; i < e; ++i)
940 dbgs() << " ";
941 dbgs() << "'" << Name.str().c_str() << "'" << "\n";
942
943 if (E->getKind() == EK_Directory) {
944 auto *DE = dyn_cast<RedirectingDirectoryEntry>(E);
945 assert(DE && "Should be a directory");
946
947 for (std::unique_ptr<Entry> &SubEntry :
948 llvm::make_range(DE->contents_begin(), DE->contents_end()))
949 dumpEntry(SubEntry.get(), NumSpaces+2);
950 }
951 }
952#endif
953
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000954};
955
956/// \brief A helper class to hold the common YAML parsing state.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000957class RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000958 yaml::Stream &Stream;
959
960 void error(yaml::Node *N, const Twine &Msg) {
961 Stream.printError(N, Msg);
962 }
963
964 // false on error
965 bool parseScalarString(yaml::Node *N, StringRef &Result,
966 SmallVectorImpl<char> &Storage) {
967 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
968 if (!S) {
969 error(N, "expected string");
970 return false;
971 }
972 Result = S->getValue(Storage);
973 return true;
974 }
975
976 // false on error
977 bool parseScalarBool(yaml::Node *N, bool &Result) {
978 SmallString<5> Storage;
979 StringRef Value;
980 if (!parseScalarString(N, Value, Storage))
981 return false;
982
983 if (Value.equals_lower("true") || Value.equals_lower("on") ||
984 Value.equals_lower("yes") || Value == "1") {
985 Result = true;
986 return true;
987 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
988 Value.equals_lower("no") || Value == "0") {
989 Result = false;
990 return true;
991 }
992
993 error(N, "expected boolean value");
994 return false;
995 }
996
997 struct KeyStatus {
998 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
999 bool Required;
1000 bool Seen;
1001 };
1002 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
1003
1004 // false on error
1005 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1006 DenseMap<StringRef, KeyStatus> &Keys) {
1007 if (!Keys.count(Key)) {
1008 error(KeyNode, "unknown key");
1009 return false;
1010 }
1011 KeyStatus &S = Keys[Key];
1012 if (S.Seen) {
1013 error(KeyNode, Twine("duplicate key '") + Key + "'");
1014 return false;
1015 }
1016 S.Seen = true;
1017 return true;
1018 }
1019
1020 // false on error
1021 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
1022 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
1023 E = Keys.end();
1024 I != E; ++I) {
1025 if (I->second.Required && !I->second.Seen) {
1026 error(Obj, Twine("missing key '") + I->first + "'");
1027 return false;
1028 }
1029 }
1030 return true;
1031 }
1032
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001033 Entry *lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1034 Entry *ParentEntry = nullptr) {
1035 if (!ParentEntry) { // Look for a existent root
1036 for (const std::unique_ptr<Entry> &Root : FS->Roots) {
1037 if (Name.equals(Root->getName())) {
1038 ParentEntry = Root.get();
1039 return ParentEntry;
1040 }
1041 }
1042 } else { // Advance to the next component
1043 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1044 for (std::unique_ptr<Entry> &Content :
1045 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1046 auto *DirContent = dyn_cast<RedirectingDirectoryEntry>(Content.get());
1047 if (DirContent && Name.equals(Content->getName()))
1048 return DirContent;
1049 }
1050 }
1051
1052 // ... or create a new one
1053 std::unique_ptr<Entry> E = llvm::make_unique<RedirectingDirectoryEntry>(
1054 Name, Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0,
1055 0, file_type::directory_file, sys::fs::all_all));
1056
1057 if (!ParentEntry) { // Add a new root to the overlay
1058 FS->Roots.push_back(std::move(E));
1059 ParentEntry = FS->Roots.back().get();
1060 return ParentEntry;
1061 }
1062
1063 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1064 DE->addContent(std::move(E));
1065 return DE->getLastContent();
1066 }
1067
1068 void uniqueOverlayTree(RedirectingFileSystem *FS, Entry *SrcE,
1069 Entry *NewParentE = nullptr) {
1070 StringRef Name = SrcE->getName();
1071 switch (SrcE->getKind()) {
1072 case EK_Directory: {
1073 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1074 assert(DE && "Must be a directory");
1075 // Empty directories could be present in the YAML as a way to
1076 // describe a file for a current directory after some of its subdir
1077 // is parsed. This only leads to redundant walks, ignore it.
1078 if (!Name.empty())
1079 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1080 for (std::unique_ptr<Entry> &SubEntry :
1081 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1082 uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1083 break;
1084 }
1085 case EK_File: {
1086 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1087 assert(FE && "Must be a file");
1088 assert(NewParentE && "Parent entry must exist");
1089 auto *DE = dyn_cast<RedirectingDirectoryEntry>(NewParentE);
1090 DE->addContent(llvm::make_unique<RedirectingFileEntry>(
1091 Name, FE->getExternalContentsPath(), FE->getUseName()));
1092 break;
1093 }
1094 }
1095 }
1096
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001097 std::unique_ptr<Entry> parseEntry(yaml::Node *N, RedirectingFileSystem *FS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001098 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
1099 if (!M) {
1100 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +00001101 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001102 }
1103
1104 KeyStatusPair Fields[] = {
1105 KeyStatusPair("name", true),
1106 KeyStatusPair("type", true),
1107 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001108 KeyStatusPair("external-contents", false),
1109 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001110 };
1111
Craig Topperac67c052015-11-30 03:11:10 +00001112 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001113
1114 bool HasContents = false; // external or otherwise
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001115 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001116 std::string ExternalContentsPath;
1117 std::string Name;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001118 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001119 EntryKind Kind;
1120
1121 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
1122 ++I) {
1123 StringRef Key;
1124 // Reuse the buffer for key and value, since we don't look at key after
1125 // parsing value.
1126 SmallString<256> Buffer;
1127 if (!parseScalarString(I->getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001128 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001129
1130 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001131 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001132
1133 StringRef Value;
1134 if (Key == "name") {
1135 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001136 return nullptr;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001137
1138 if (FS->UseCanonicalizedPaths) {
1139 SmallString<256> Path(Value);
1140 // Guarantee that old YAML files containing paths with ".." and "."
1141 // are properly canonicalized before read into the VFS.
1142 Path = sys::path::remove_leading_dotslash(Path);
1143 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1144 Name = Path.str();
1145 } else {
1146 Name = Value;
1147 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001148 } else if (Key == "type") {
1149 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001150 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001151 if (Value == "file")
1152 Kind = EK_File;
1153 else if (Value == "directory")
1154 Kind = EK_Directory;
1155 else {
1156 error(I->getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +00001157 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001158 }
1159 } else if (Key == "contents") {
1160 if (HasContents) {
1161 error(I->getKey(),
1162 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001163 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001164 }
1165 HasContents = true;
1166 yaml::SequenceNode *Contents =
1167 dyn_cast<yaml::SequenceNode>(I->getValue());
1168 if (!Contents) {
1169 // FIXME: this is only for directories, what about files?
1170 error(I->getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +00001171 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001172 }
1173
1174 for (yaml::SequenceNode::iterator I = Contents->begin(),
1175 E = Contents->end();
1176 I != E; ++I) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001177 if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001178 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001179 else
Craig Topperf1186c52014-05-08 06:41:40 +00001180 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001181 }
1182 } else if (Key == "external-contents") {
1183 if (HasContents) {
1184 error(I->getKey(),
1185 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001186 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001187 }
1188 HasContents = true;
1189 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001190 return nullptr;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001191
1192 SmallString<256> FullPath;
1193 if (FS->IsRelativeOverlay) {
1194 FullPath = FS->getExternalContentsPrefixDir();
1195 assert(!FullPath.empty() &&
1196 "External contents prefix directory must exist");
1197 llvm::sys::path::append(FullPath, Value);
1198 } else {
1199 FullPath = Value;
1200 }
1201
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001202 if (FS->UseCanonicalizedPaths) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001203 // Guarantee that old YAML files containing paths with ".." and "."
1204 // are properly canonicalized before read into the VFS.
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001205 FullPath = sys::path::remove_leading_dotslash(FullPath);
1206 sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001207 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001208 ExternalContentsPath = FullPath.str();
Ben Langmuirb59cf672014-02-27 00:25:12 +00001209 } else if (Key == "use-external-name") {
1210 bool Val;
1211 if (!parseScalarBool(I->getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001212 return nullptr;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001213 UseExternalName = Val ? RedirectingFileEntry::NK_External
1214 : RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001215 } else {
1216 llvm_unreachable("key missing from Keys");
1217 }
1218 }
1219
1220 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001221 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001222
1223 // check for missing keys
1224 if (!HasContents) {
1225 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001226 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001227 }
1228 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001229 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001230
Ben Langmuirb59cf672014-02-27 00:25:12 +00001231 // check invalid configuration
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001232 if (Kind == EK_Directory &&
1233 UseExternalName != RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001234 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001235 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001236 }
1237
Ben Langmuir93853232014-03-05 21:32:20 +00001238 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001239 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001240 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1241 while (Trimmed.size() > RootPathLen &&
1242 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001243 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1244 // Get the last component
1245 StringRef LastComponent = sys::path::filename(Trimmed);
1246
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001247 std::unique_ptr<Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001248 switch (Kind) {
1249 case EK_File:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001250 Result = llvm::make_unique<RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001251 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001252 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001253 case EK_Directory:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001254 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001255 LastComponent, std::move(EntryArrayContents),
1256 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1257 file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001258 break;
1259 }
1260
1261 StringRef Parent = sys::path::parent_path(Trimmed);
1262 if (Parent.empty())
1263 return Result;
1264
1265 // if 'name' contains multiple components, create implicit directory entries
1266 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1267 E = sys::path::rend(Parent);
1268 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001269 std::vector<std::unique_ptr<Entry>> Entries;
1270 Entries.push_back(std::move(Result));
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001271 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001272 *I, std::move(Entries),
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001273 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1274 file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001275 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001276 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001277 }
1278
1279public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001280 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001281
1282 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001283 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001284 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
1285 if (!Top) {
1286 error(Root, "expected mapping node");
1287 return false;
1288 }
1289
1290 KeyStatusPair Fields[] = {
1291 KeyStatusPair("version", true),
1292 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001293 KeyStatusPair("use-external-names", false),
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001294 KeyStatusPair("overlay-relative", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001295 KeyStatusPair("roots", true),
1296 };
1297
Craig Topperac67c052015-11-30 03:11:10 +00001298 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001299 std::vector<std::unique_ptr<Entry>> RootEntries;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001300
1301 // Parse configuration and 'roots'
1302 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
1303 ++I) {
1304 SmallString<10> KeyBuffer;
1305 StringRef Key;
1306 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
1307 return false;
1308
1309 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1310 return false;
1311
1312 if (Key == "roots") {
1313 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
1314 if (!Roots) {
1315 error(I->getValue(), "expected array");
1316 return false;
1317 }
1318
1319 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
1320 I != E; ++I) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001321 if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001322 RootEntries.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001323 else
1324 return false;
1325 }
1326 } else if (Key == "version") {
1327 StringRef VersionString;
1328 SmallString<4> Storage;
1329 if (!parseScalarString(I->getValue(), VersionString, Storage))
1330 return false;
1331 int Version;
1332 if (VersionString.getAsInteger<int>(10, Version)) {
1333 error(I->getValue(), "expected integer");
1334 return false;
1335 }
1336 if (Version < 0) {
1337 error(I->getValue(), "invalid version number");
1338 return false;
1339 }
1340 if (Version != 0) {
1341 error(I->getValue(), "version mismatch, expected 0");
1342 return false;
1343 }
1344 } else if (Key == "case-sensitive") {
1345 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
1346 return false;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001347 } else if (Key == "overlay-relative") {
1348 if (!parseScalarBool(I->getValue(), FS->IsRelativeOverlay))
1349 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001350 } else if (Key == "use-external-names") {
1351 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
1352 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001353 } else {
1354 llvm_unreachable("key missing from Keys");
1355 }
1356 }
1357
1358 if (Stream.failed())
1359 return false;
1360
1361 if (!checkMissingKeys(Top, Keys))
1362 return false;
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001363
1364 // Now that we sucessefully parsed the YAML file, canonicalize the internal
1365 // representation to a proper directory tree so that we can search faster
1366 // inside the VFS.
1367 for (std::unique_ptr<Entry> &E : RootEntries)
1368 uniqueOverlayTree(FS, E.get());
1369
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001370 return true;
1371 }
1372};
1373} // end of anonymous namespace
1374
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001375Entry::~Entry() = default;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001376
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001377RedirectingFileSystem *
1378RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1379 SourceMgr::DiagHandlerTy DiagHandler,
1380 StringRef YAMLFilePath, void *DiagContext,
1381 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001382
1383 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001384 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001385
Ben Langmuir97882e72014-02-24 20:56:37 +00001386 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001387 yaml::document_iterator DI = Stream.begin();
1388 yaml::Node *Root = DI->getRoot();
1389 if (DI == Stream.end() || !Root) {
1390 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001391 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001392 }
1393
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001394 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001395
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001396 std::unique_ptr<RedirectingFileSystem> FS(
1397 new RedirectingFileSystem(ExternalFS));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001398
1399 if (!YAMLFilePath.empty()) {
1400 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1401 // to each 'external-contents' path.
1402 //
1403 // Example:
1404 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
1405 // yields:
1406 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1407 //
1408 SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1409 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1410 assert(!EC && "Overlay dir final path must be absolute");
1411 (void)EC;
1412 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1413 }
1414
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001415 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001416 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001417
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001418 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001419}
1420
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001421ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001422 SmallString<256> Path;
1423 Path_.toVector(Path);
1424
1425 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001426 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001427 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001428
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001429 // Canonicalize path by removing ".", "..", "./", etc components. This is
1430 // a VFS request, do bot bother about symlinks in the path components
1431 // but canonicalize in order to perform the correct entry search.
1432 if (UseCanonicalizedPaths) {
1433 Path = sys::path::remove_leading_dotslash(Path);
1434 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1435 }
1436
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001437 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001438 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001439
1440 sys::path::const_iterator Start = sys::path::begin(Path);
1441 sys::path::const_iterator End = sys::path::end(Path);
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001442 for (const std::unique_ptr<Entry> &Root : Roots) {
1443 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001444 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001445 return Result;
1446 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001447 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001448}
1449
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001450ErrorOr<Entry *>
1451RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1452 sys::path::const_iterator End, Entry *From) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001453#ifndef LLVM_ON_WIN32
1454 assert(!isTraversalComponent(*Start) &&
1455 !isTraversalComponent(From->getName()) &&
1456 "Paths should not contain traversal components");
1457#else
1458 // FIXME: this is here to support windows, remove it once canonicalized
1459 // paths become globally default.
Bruno Cardoso Lopesbe056b12016-02-23 17:06:50 +00001460 if (Start->equals("."))
1461 ++Start;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001462#endif
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001463
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001464 StringRef FromName = From->getName();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001465
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001466 // Forward the search to the next component in case this is an empty one.
1467 if (!FromName.empty()) {
1468 if (CaseSensitive ? !Start->equals(FromName)
1469 : !Start->equals_lower(FromName))
1470 // failure to match
1471 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001472
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001473 ++Start;
1474
1475 if (Start == End) {
1476 // Match!
1477 return From;
1478 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001479 }
1480
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001481 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001482 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001483 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001484
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001485 for (const std::unique_ptr<Entry> &DirEntry :
1486 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1487 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001488 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001489 return Result;
1490 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001491 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001492}
1493
Ben Langmuirf13302e2015-12-10 23:41:39 +00001494static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1495 Status ExternalStatus) {
1496 Status S = ExternalStatus;
1497 if (!UseExternalNames)
1498 S = Status::copyWithNewName(S, Path.str());
1499 S.IsVFSMapped = true;
1500 return S;
1501}
1502
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001503ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001504 assert(E != nullptr);
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001505 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001506 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001507 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuir5de00f32014-05-23 18:15:47 +00001508 if (S)
Ben Langmuirf13302e2015-12-10 23:41:39 +00001509 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1510 *S);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001511 return S;
1512 } else { // directory
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001513 auto *DE = cast<RedirectingDirectoryEntry>(E);
Ben Langmuirf13302e2015-12-10 23:41:39 +00001514 return Status::copyWithNewName(DE->getStatus(), Path.str());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001515 }
1516}
1517
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001518ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001519 ErrorOr<Entry *> Result = lookupPath(Path);
1520 if (!Result)
1521 return Result.getError();
1522 return status(Path, *Result);
1523}
1524
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001525namespace {
Ben Langmuirf13302e2015-12-10 23:41:39 +00001526/// Provide a file wrapper with an overriden status.
1527class FileWithFixedStatus : public File {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001528 std::unique_ptr<File> InnerFile;
Ben Langmuirf13302e2015-12-10 23:41:39 +00001529 Status S;
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001530
1531public:
Ben Langmuirf13302e2015-12-10 23:41:39 +00001532 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
1533 : InnerFile(std::move(InnerFile)), S(S) {}
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001534
Ben Langmuirf13302e2015-12-10 23:41:39 +00001535 ErrorOr<Status> status() override { return S; }
1536 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +00001537 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1538 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001539 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1540 IsVolatile);
1541 }
1542 std::error_code close() override { return InnerFile->close(); }
1543};
1544} // end anonymous namespace
1545
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001546ErrorOr<std::unique_ptr<File>>
1547RedirectingFileSystem::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001548 ErrorOr<Entry *> E = lookupPath(Path);
1549 if (!E)
1550 return E.getError();
1551
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001552 auto *F = dyn_cast<RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001553 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001554 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001555
Benjamin Kramera8857962014-10-26 22:44:13 +00001556 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1557 if (!Result)
1558 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001559
Ben Langmuirf13302e2015-12-10 23:41:39 +00001560 auto ExternalStatus = (*Result)->status();
1561 if (!ExternalStatus)
1562 return ExternalStatus.getError();
Ben Langmuird066d4c2014-02-28 21:16:07 +00001563
Ben Langmuirf13302e2015-12-10 23:41:39 +00001564 // FIXME: Update the status with the name and VFSMapped.
1565 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1566 *ExternalStatus);
1567 return std::unique_ptr<File>(
1568 llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001569}
1570
1571IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001572vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001573 SourceMgr::DiagHandlerTy DiagHandler,
1574 StringRef YAMLFilePath,
1575 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001576 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001577 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001578 YAMLFilePath, DiagContext, ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001579}
1580
1581UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001582 static std::atomic<unsigned> UID;
1583 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001584 // The following assumes that uint64_t max will never collide with a real
1585 // dev_t value from the OS.
1586 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1587}
Justin Bogner9c785292014-05-20 21:43:27 +00001588
Justin Bogner9c785292014-05-20 21:43:27 +00001589void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1590 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1591 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1592 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1593 Mappings.emplace_back(VirtualPath, RealPath);
1594}
1595
Justin Bogner44fa450342014-05-21 22:46:51 +00001596namespace {
1597class JSONWriter {
1598 llvm::raw_ostream &OS;
1599 SmallVector<StringRef, 16> DirStack;
1600 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
1601 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1602 bool containedIn(StringRef Parent, StringRef Path);
1603 StringRef containedPart(StringRef Parent, StringRef Path);
1604 void startDirectory(StringRef Path);
1605 void endDirectory();
1606 void writeEntry(StringRef VPath, StringRef RPath);
1607
1608public:
1609 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001610 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
1611 Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
1612 StringRef OverlayDir);
Justin Bogner44fa450342014-05-21 22:46:51 +00001613};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001614}
Justin Bogner9c785292014-05-20 21:43:27 +00001615
Justin Bogner44fa450342014-05-21 22:46:51 +00001616bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001617 using namespace llvm::sys;
1618 // Compare each path component.
1619 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1620 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1621 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1622 if (*IParent != *IChild)
1623 return false;
1624 }
1625 // Have we exhausted the parent path?
1626 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001627}
1628
Justin Bogner44fa450342014-05-21 22:46:51 +00001629StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1630 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001631 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001632 return Path.slice(Parent.size() + 1, StringRef::npos);
1633}
1634
Justin Bogner44fa450342014-05-21 22:46:51 +00001635void JSONWriter::startDirectory(StringRef Path) {
1636 StringRef Name =
1637 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1638 DirStack.push_back(Path);
1639 unsigned Indent = getDirIndent();
1640 OS.indent(Indent) << "{\n";
1641 OS.indent(Indent + 2) << "'type': 'directory',\n";
1642 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1643 OS.indent(Indent + 2) << "'contents': [\n";
1644}
1645
1646void JSONWriter::endDirectory() {
1647 unsigned Indent = getDirIndent();
1648 OS.indent(Indent + 2) << "]\n";
1649 OS.indent(Indent) << "}";
1650
1651 DirStack.pop_back();
1652}
1653
1654void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1655 unsigned Indent = getFileIndent();
1656 OS.indent(Indent) << "{\n";
1657 OS.indent(Indent + 2) << "'type': 'file',\n";
1658 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1659 OS.indent(Indent + 2) << "'external-contents': \""
1660 << llvm::yaml::escape(RPath) << "\"\n";
1661 OS.indent(Indent) << "}";
1662}
1663
1664void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001665 Optional<bool> UseExternalNames,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001666 Optional<bool> IsCaseSensitive,
1667 Optional<bool> IsOverlayRelative,
1668 StringRef OverlayDir) {
Justin Bogner44fa450342014-05-21 22:46:51 +00001669 using namespace llvm::sys;
1670
1671 OS << "{\n"
1672 " 'version': 0,\n";
1673 if (IsCaseSensitive.hasValue())
1674 OS << " 'case-sensitive': '"
1675 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001676 if (UseExternalNames.hasValue())
1677 OS << " 'use-external-names': '"
1678 << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001679 bool UseOverlayRelative = false;
1680 if (IsOverlayRelative.hasValue()) {
1681 UseOverlayRelative = IsOverlayRelative.getValue();
1682 OS << " 'overlay-relative': '"
1683 << (UseOverlayRelative ? "true" : "false") << "',\n";
1684 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001685 OS << " 'roots': [\n";
1686
Justin Bogner73466402014-07-15 01:24:35 +00001687 if (!Entries.empty()) {
1688 const YAMLVFSEntry &Entry = Entries.front();
1689 startDirectory(path::parent_path(Entry.VPath));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001690
1691 StringRef RPath = Entry.RPath;
1692 if (UseOverlayRelative) {
1693 unsigned OverlayDirLen = OverlayDir.size();
1694 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1695 "Overlay dir must be contained in RPath");
1696 RPath = RPath.slice(OverlayDirLen, RPath.size());
1697 }
1698
1699 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001700
Justin Bogner73466402014-07-15 01:24:35 +00001701 for (const auto &Entry : Entries.slice(1)) {
1702 StringRef Dir = path::parent_path(Entry.VPath);
1703 if (Dir == DirStack.back())
1704 OS << ",\n";
1705 else {
1706 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1707 OS << "\n";
1708 endDirectory();
1709 }
1710 OS << ",\n";
1711 startDirectory(Dir);
1712 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001713 StringRef RPath = Entry.RPath;
1714 if (UseOverlayRelative) {
1715 unsigned OverlayDirLen = OverlayDir.size();
1716 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1717 "Overlay dir must be contained in RPath");
1718 RPath = RPath.slice(OverlayDirLen, RPath.size());
1719 }
1720 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner73466402014-07-15 01:24:35 +00001721 }
1722
1723 while (!DirStack.empty()) {
1724 OS << "\n";
1725 endDirectory();
1726 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001727 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001728 }
1729
Justin Bogner73466402014-07-15 01:24:35 +00001730 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001731 << "}\n";
1732}
1733
Justin Bogner9c785292014-05-20 21:43:27 +00001734void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1735 std::sort(Mappings.begin(), Mappings.end(),
Justin Bogner44fa450342014-05-21 22:46:51 +00001736 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001737 return LHS.VPath < RHS.VPath;
1738 });
1739
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001740 JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
1741 IsOverlayRelative, OverlayDir);
Justin Bogner9c785292014-05-20 21:43:27 +00001742}
Ben Langmuir740812b2014-06-24 19:37:16 +00001743
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001744VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1745 const Twine &_Path, RedirectingFileSystem &FS,
1746 RedirectingDirectoryEntry::iterator Begin,
1747 RedirectingDirectoryEntry::iterator End, std::error_code &EC)
Ben Langmuir740812b2014-06-24 19:37:16 +00001748 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
1749 if (Current != End) {
1750 SmallString<128> PathStr(Dir);
1751 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001752 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001753 if (S)
1754 CurrentEntry = *S;
1755 else
1756 EC = S.getError();
1757 }
1758}
1759
1760std::error_code VFSFromYamlDirIterImpl::increment() {
1761 assert(Current != End && "cannot iterate past end");
1762 if (++Current != End) {
1763 SmallString<128> PathStr(Dir);
1764 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001765 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001766 if (!S)
1767 return S.getError();
1768 CurrentEntry = *S;
1769 } else {
1770 CurrentEntry = Status();
1771 }
1772 return std::error_code();
1773}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001774
1775vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1776 const Twine &Path,
1777 std::error_code &EC)
1778 : FS(&FS_) {
1779 directory_iterator I = FS->dir_begin(Path, EC);
1780 if (!EC && I != directory_iterator()) {
1781 State = std::make_shared<IterState>();
1782 State->push(I);
1783 }
1784}
1785
1786vfs::recursive_directory_iterator &
1787recursive_directory_iterator::increment(std::error_code &EC) {
1788 assert(FS && State && !State->empty() && "incrementing past end");
1789 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1790 vfs::directory_iterator End;
1791 if (State->top()->isDirectory()) {
1792 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
1793 if (EC)
1794 return *this;
1795 if (I != End) {
1796 State->push(I);
1797 return *this;
1798 }
1799 }
1800
1801 while (!State->empty() && State->top().increment(EC) == End)
1802 State->pop();
1803
1804 if (State->empty())
1805 State.reset(); // end iterator
1806
1807 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001808}