blob: f5db717866a95a7914d2bbe11123fe661aa1ffd3 [file] [log] [blame]
Ben Langmuirc8130a72014-02-20 21:59:23 +00001//===- VirtualFileSystem.cpp - Virtual File System Layer --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// This file implements the VirtualFileSystem interface.
10//===----------------------------------------------------------------------===//
11
12#include "clang/Basic/VirtualFileSystem.h"
Benjamin Kramer71ce3762015-10-12 16:16:39 +000013#include "clang/Basic/FileManager.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000014#include "llvm/ADT/DenseMap.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000015#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/StringExtras.h"
Ben Langmuir740812b2014-06-24 19:37:16 +000017#include "llvm/ADT/StringSet.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "llvm/ADT/iterator_range.h"
Benjamin Kramercfeacf52016-05-27 14:27:13 +000019#include "llvm/Config/llvm-config.h"
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +000020#include "llvm/Support/Debug.h"
Rafael Espindola71de0b62014-06-13 17:20:50 +000021#include "llvm/Support/Errc.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000022#include "llvm/Support/MemoryBuffer.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000023#include "llvm/Support/Path.h"
David Majnemer6a6206d2016-03-04 05:26:14 +000024#include "llvm/Support/Process.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000025#include "llvm/Support/YAMLParser.h"
Benjamin Kramer4527fb22014-03-02 17:08:31 +000026#include <atomic>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000027#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000028#include <utility>
Ben Langmuirc8130a72014-02-20 21:59:23 +000029
30using namespace clang;
31using namespace clang::vfs;
32using namespace llvm;
33using llvm::sys::fs::file_status;
34using llvm::sys::fs::file_type;
35using llvm::sys::fs::perms;
36using llvm::sys::fs::UniqueID;
37
38Status::Status(const file_status &Status)
39 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
40 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
Ben Langmuir5de00f32014-05-23 18:15:47 +000041 Type(Status.type()), Perms(Status.permissions()), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000042
Pavel Labathac71c8e2016-11-09 10:52:22 +000043Status::Status(StringRef Name, UniqueID UID, sys::TimePoint<> MTime,
Benjamin Kramer268b51a2015-10-05 13:15:33 +000044 uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
45 perms Perms)
Ben Langmuirb59cf672014-02-27 00:25:12 +000046 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
Ben Langmuir5de00f32014-05-23 18:15:47 +000047 Type(Type), Perms(Perms), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000048
Benjamin Kramer268b51a2015-10-05 13:15:33 +000049Status Status::copyWithNewName(const Status &In, StringRef NewName) {
50 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
51 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
52 In.getPermissions());
53}
54
55Status Status::copyWithNewName(const file_status &In, StringRef NewName) {
56 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
57 In.getUser(), In.getGroup(), In.getSize(), In.type(),
58 In.permissions());
59}
60
Ben Langmuirc8130a72014-02-20 21:59:23 +000061bool Status::equivalent(const Status &Other) const {
62 return getUniqueID() == Other.getUniqueID();
63}
64bool Status::isDirectory() const {
65 return Type == file_type::directory_file;
66}
67bool Status::isRegularFile() const {
68 return Type == file_type::regular_file;
69}
70bool Status::isOther() const {
71 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
72}
73bool Status::isSymlink() const {
74 return Type == file_type::symlink_file;
75}
76bool Status::isStatusKnown() const {
77 return Type != file_type::status_error;
78}
79bool Status::exists() const {
80 return isStatusKnown() && Type != file_type::file_not_found;
81}
82
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000083File::~File() {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000084
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000085FileSystem::~FileSystem() {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000086
Benjamin Kramera8857962014-10-26 22:44:13 +000087ErrorOr<std::unique_ptr<MemoryBuffer>>
88FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
89 bool RequiresNullTerminator, bool IsVolatile) {
90 auto F = openFileForRead(Name);
91 if (!F)
92 return F.getError();
Ben Langmuirc8130a72014-02-20 21:59:23 +000093
Benjamin Kramera8857962014-10-26 22:44:13 +000094 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +000095}
96
Benjamin Kramer7708b2a2015-10-05 13:55:20 +000097std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
Bob Wilsonf43354f2016-03-26 18:55:13 +000098 if (llvm::sys::path::is_absolute(Path))
99 return std::error_code();
100
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000101 auto WorkingDir = getCurrentWorkingDirectory();
102 if (!WorkingDir)
103 return WorkingDir.getError();
104
105 return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
106}
107
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000108bool FileSystem::exists(const Twine &Path) {
109 auto Status = status(Path);
110 return Status && Status->exists();
111}
112
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000113#ifndef NDEBUG
114static bool isTraversalComponent(StringRef Component) {
115 return Component.equals("..") || Component.equals(".");
116}
117
118static bool pathHasTraversal(StringRef Path) {
119 using namespace llvm::sys;
120 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
121 if (isTraversalComponent(Comp))
122 return true;
123 return false;
124}
125#endif
126
Ben Langmuirc8130a72014-02-20 21:59:23 +0000127//===-----------------------------------------------------------------------===/
128// RealFileSystem implementation
129//===-----------------------------------------------------------------------===/
130
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000131namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000132/// \brief Wrapper around a raw file descriptor.
133class RealFile : public File {
134 int FD;
Ben Langmuird066d4c2014-02-28 21:16:07 +0000135 Status S;
Taewook Ohf42103c2016-06-13 20:40:21 +0000136 std::string RealName;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000137 friend class RealFileSystem;
Taewook Ohf42103c2016-06-13 20:40:21 +0000138 RealFile(int FD, StringRef NewName, StringRef NewRealPathName)
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000139 : FD(FD), S(NewName, {}, {}, {}, {}, {},
Taewook Ohf42103c2016-06-13 20:40:21 +0000140 llvm::sys::fs::file_type::status_error, {}),
141 RealName(NewRealPathName.str()) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000142 assert(FD >= 0 && "Invalid or inactive file descriptor");
143 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000144
Ben Langmuirc8130a72014-02-20 21:59:23 +0000145public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000146 ~RealFile() override;
Craig Toppera798a9d2014-03-02 09:32:10 +0000147 ErrorOr<Status> status() override;
Taewook Ohf42103c2016-06-13 20:40:21 +0000148 ErrorOr<std::string> getName() override;
Benjamin Kramer737501c2015-10-05 21:20:19 +0000149 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
150 int64_t FileSize,
151 bool RequiresNullTerminator,
152 bool IsVolatile) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000153 std::error_code close() override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000154};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000155} // end anonymous namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000156RealFile::~RealFile() { close(); }
Ben Langmuirc8130a72014-02-20 21:59:23 +0000157
158ErrorOr<Status> RealFile::status() {
159 assert(FD != -1 && "cannot stat closed file");
Ben Langmuird066d4c2014-02-28 21:16:07 +0000160 if (!S.isStatusKnown()) {
161 file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000162 if (std::error_code EC = sys::fs::status(FD, RealStatus))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000163 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000164 S = Status::copyWithNewName(RealStatus, S.getName());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000165 }
166 return S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000167}
168
Taewook Ohf42103c2016-06-13 20:40:21 +0000169ErrorOr<std::string> RealFile::getName() {
170 return RealName.empty() ? S.getName().str() : RealName;
171}
172
Benjamin Kramera8857962014-10-26 22:44:13 +0000173ErrorOr<std::unique_ptr<MemoryBuffer>>
174RealFile::getBuffer(const Twine &Name, int64_t FileSize,
175 bool RequiresNullTerminator, bool IsVolatile) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000176 assert(FD != -1 && "cannot get buffer for closed file");
Benjamin Kramera8857962014-10-26 22:44:13 +0000177 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
178 IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000179}
180
Rafael Espindola8e650d72014-06-12 20:37:59 +0000181std::error_code RealFile::close() {
David Majnemer6a6206d2016-03-04 05:26:14 +0000182 std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000183 FD = -1;
David Majnemer6a6206d2016-03-04 05:26:14 +0000184 return EC;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000185}
186
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000187namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000188/// \brief The file system according to your operating system.
189class RealFileSystem : public FileSystem {
190public:
Craig Toppera798a9d2014-03-02 09:32:10 +0000191 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000192 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000193 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000194
195 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
196 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000197};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000198} // end anonymous namespace
Ben Langmuirc8130a72014-02-20 21:59:23 +0000199
200ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
201 sys::fs::file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000202 if (std::error_code EC = sys::fs::status(Path, RealStatus))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000203 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000204 return Status::copyWithNewName(RealStatus, Path.str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000205}
206
Benjamin Kramera8857962014-10-26 22:44:13 +0000207ErrorOr<std::unique_ptr<File>>
208RealFileSystem::openFileForRead(const Twine &Name) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000209 int FD;
Taewook Ohf42103c2016-06-13 20:40:21 +0000210 SmallString<256> RealName;
211 if (std::error_code EC = sys::fs::openFileForRead(Name, FD, &RealName))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000212 return EC;
Taewook Ohf42103c2016-06-13 20:40:21 +0000213 return std::unique_ptr<File>(new RealFile(FD, Name.str(), RealName.str()));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000214}
215
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000216llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
217 SmallString<256> Dir;
218 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
219 return EC;
220 return Dir.str().str();
221}
222
223std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
224 // FIXME: chdir is thread hostile; on the other hand, creating the same
225 // behavior as chdir is complex: chdir resolves the path once, thus
226 // guaranteeing that all subsequent relative path operations work
227 // on the same path the original chdir resulted in. This makes a
228 // difference for example on network filesystems, where symlinks might be
229 // switched during runtime of the tool. Fixing this depends on having a
230 // file system abstraction that allows openat() style interactions.
Pavel Labathdcbd6142017-01-24 11:14:29 +0000231 return llvm::sys::fs::set_current_path(Path);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000232}
233
Ben Langmuirc8130a72014-02-20 21:59:23 +0000234IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
235 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
236 return FS;
237}
238
Ben Langmuir740812b2014-06-24 19:37:16 +0000239namespace {
240class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
Ben Langmuir740812b2014-06-24 19:37:16 +0000241 llvm::sys::fs::directory_iterator Iter;
242public:
Juergen Ributzka4a259562017-03-10 21:23:29 +0000243 RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) {
Ben Langmuir740812b2014-06-24 19:37:16 +0000244 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
245 llvm::sys::fs::file_status S;
246 EC = Iter->status(S);
Juergen Ributzkaf9787432017-03-14 00:14:40 +0000247 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000248 }
249 }
250
251 std::error_code increment() override {
252 std::error_code EC;
253 Iter.increment(EC);
254 if (EC) {
255 return EC;
256 } else if (Iter == llvm::sys::fs::directory_iterator()) {
257 CurrentEntry = Status();
258 } else {
259 llvm::sys::fs::file_status S;
260 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000261 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000262 }
263 return EC;
264 }
265};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000266}
Ben Langmuir740812b2014-06-24 19:37:16 +0000267
268directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
269 std::error_code &EC) {
270 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
271}
272
Ben Langmuirc8130a72014-02-20 21:59:23 +0000273//===-----------------------------------------------------------------------===/
274// OverlayFileSystem implementation
275//===-----------------------------------------------------------------------===/
276OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000277 FSList.push_back(std::move(BaseFS));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000278}
279
280void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
281 FSList.push_back(FS);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000282 // Synchronize added file systems by duplicating the working directory from
283 // the first one in the list.
284 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000285}
286
287ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
288 // FIXME: handle symlinks that cross file systems
289 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
290 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000291 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000292 return Status;
293 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000294 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000295}
296
Benjamin Kramera8857962014-10-26 22:44:13 +0000297ErrorOr<std::unique_ptr<File>>
298OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000299 // FIXME: handle symlinks that cross file systems
300 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000301 auto Result = (*I)->openFileForRead(Path);
302 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
303 return Result;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000304 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000305 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000306}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000307
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000308llvm::ErrorOr<std::string>
309OverlayFileSystem::getCurrentWorkingDirectory() const {
310 // All file systems are synchronized, just take the first working directory.
311 return FSList.front()->getCurrentWorkingDirectory();
312}
313std::error_code
314OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
315 for (auto &FS : FSList)
316 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
317 return EC;
318 return std::error_code();
319}
320
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000321clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
Ben Langmuir740812b2014-06-24 19:37:16 +0000322
323namespace {
324class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
325 OverlayFileSystem &Overlays;
326 std::string Path;
327 OverlayFileSystem::iterator CurrentFS;
328 directory_iterator CurrentDirIter;
329 llvm::StringSet<> SeenNames;
330
331 std::error_code incrementFS() {
332 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
333 ++CurrentFS;
334 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
335 std::error_code EC;
336 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
337 if (EC && EC != errc::no_such_file_or_directory)
338 return EC;
339 if (CurrentDirIter != directory_iterator())
340 break; // found
341 }
342 return std::error_code();
343 }
344
345 std::error_code incrementDirIter(bool IsFirstTime) {
346 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
347 "incrementing past end");
348 std::error_code EC;
349 if (!IsFirstTime)
350 CurrentDirIter.increment(EC);
351 if (!EC && CurrentDirIter == directory_iterator())
352 EC = incrementFS();
353 return EC;
354 }
355
356 std::error_code incrementImpl(bool IsFirstTime) {
357 while (true) {
358 std::error_code EC = incrementDirIter(IsFirstTime);
359 if (EC || CurrentDirIter == directory_iterator()) {
360 CurrentEntry = Status();
361 return EC;
362 }
363 CurrentEntry = *CurrentDirIter;
364 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
David Blaikie61b86d42014-11-19 02:56:13 +0000365 if (SeenNames.insert(Name).second)
Ben Langmuir740812b2014-06-24 19:37:16 +0000366 return EC; // name not seen before
367 }
368 llvm_unreachable("returned above");
369 }
370
371public:
372 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
373 std::error_code &EC)
374 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
375 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
376 EC = incrementImpl(true);
377 }
378
379 std::error_code increment() override { return incrementImpl(false); }
380};
381} // end anonymous namespace
382
383directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
384 std::error_code &EC) {
385 return directory_iterator(
386 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
387}
388
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000389namespace clang {
390namespace vfs {
391namespace detail {
392
393enum InMemoryNodeKind { IME_File, IME_Directory };
394
395/// The in memory file system is a tree of Nodes. Every node can either be a
396/// file or a directory.
397class InMemoryNode {
398 Status Stat;
399 InMemoryNodeKind Kind;
400
401public:
402 InMemoryNode(Status Stat, InMemoryNodeKind Kind)
403 : Stat(std::move(Stat)), Kind(Kind) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000404 virtual ~InMemoryNode() {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000405 const Status &getStatus() const { return Stat; }
406 InMemoryNodeKind getKind() const { return Kind; }
407 virtual std::string toString(unsigned Indent) const = 0;
408};
409
410namespace {
411class InMemoryFile : public InMemoryNode {
412 std::unique_ptr<llvm::MemoryBuffer> Buffer;
413
414public:
415 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
416 : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
417
418 llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
419 std::string toString(unsigned Indent) const override {
420 return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
421 }
422 static bool classof(const InMemoryNode *N) {
423 return N->getKind() == IME_File;
424 }
425};
426
427/// Adapt a InMemoryFile for VFS' File interface.
428class InMemoryFileAdaptor : public File {
429 InMemoryFile &Node;
430
431public:
432 explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
433
434 llvm::ErrorOr<Status> status() override { return Node.getStatus(); }
435 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +0000436 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
437 bool IsVolatile) override {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000438 llvm::MemoryBuffer *Buf = Node.getBuffer();
439 return llvm::MemoryBuffer::getMemBuffer(
440 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
441 }
442 std::error_code close() override { return std::error_code(); }
443};
444} // end anonymous namespace
445
446class InMemoryDirectory : public InMemoryNode {
447 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
448
449public:
450 InMemoryDirectory(Status Stat)
451 : InMemoryNode(std::move(Stat), IME_Directory) {}
452 InMemoryNode *getChild(StringRef Name) {
453 auto I = Entries.find(Name);
454 if (I != Entries.end())
455 return I->second.get();
456 return nullptr;
457 }
458 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
459 return Entries.insert(make_pair(Name, std::move(Child)))
460 .first->second.get();
461 }
462
463 typedef decltype(Entries)::const_iterator const_iterator;
464 const_iterator begin() const { return Entries.begin(); }
465 const_iterator end() const { return Entries.end(); }
466
467 std::string toString(unsigned Indent) const override {
468 std::string Result =
469 (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
470 for (const auto &Entry : Entries) {
471 Result += Entry.second->toString(Indent + 2);
472 }
473 return Result;
474 }
475 static bool classof(const InMemoryNode *N) {
476 return N->getKind() == IME_Directory;
477 }
478};
479}
480
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000481InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000482 : Root(new detail::InMemoryDirectory(
Pavel Labathac71c8e2016-11-09 10:52:22 +0000483 Status("", getNextVirtualUniqueID(), llvm::sys::TimePoint<>(), 0, 0,
484 0, llvm::sys::fs::file_type::directory_file,
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000485 llvm::sys::fs::perms::all_all))),
486 UseNormalizedPaths(UseNormalizedPaths) {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000487
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000488InMemoryFileSystem::~InMemoryFileSystem() {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000489
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000490std::string InMemoryFileSystem::toString() const {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000491 return Root->toString(/*Indent=*/0);
492}
493
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000494bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000495 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
496 SmallString<128> Path;
497 P.toVector(Path);
498
499 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000500 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000501 assert(!EC);
502 (void)EC;
503
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000504 if (useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000505 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000506
507 if (Path.empty())
508 return false;
509
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000510 detail::InMemoryDirectory *Dir = Root.get();
511 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
512 while (true) {
513 StringRef Name = *I;
514 detail::InMemoryNode *Node = Dir->getChild(Name);
515 ++I;
516 if (!Node) {
517 if (I == E) {
518 // End of the path, create a new file.
519 // FIXME: expose the status details in the interface.
Benjamin Kramer1b8dbe32015-10-06 14:45:16 +0000520 Status Stat(P.str(), getNextVirtualUniqueID(),
Pavel Labathac71c8e2016-11-09 10:52:22 +0000521 llvm::sys::toTimePoint(ModificationTime), 0, 0,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000522 Buffer->getBufferSize(),
523 llvm::sys::fs::file_type::regular_file,
524 llvm::sys::fs::all_all);
525 Dir->addChild(Name, llvm::make_unique<detail::InMemoryFile>(
526 std::move(Stat), std::move(Buffer)));
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000527 return true;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000528 }
529
530 // Create a new directory. Use the path up to here.
531 // FIXME: expose the status details in the interface.
532 Status Stat(
533 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Pavel Labathac71c8e2016-11-09 10:52:22 +0000534 getNextVirtualUniqueID(), llvm::sys::toTimePoint(ModificationTime), 0,
535 0, Buffer->getBufferSize(), llvm::sys::fs::file_type::directory_file,
536 llvm::sys::fs::all_all);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000537 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
538 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
539 continue;
540 }
541
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000542 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000543 Dir = NewDir;
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000544 } else {
545 assert(isa<detail::InMemoryFile>(Node) &&
546 "Must be either file or directory!");
547
548 // Trying to insert a directory in place of a file.
549 if (I != E)
550 return false;
551
552 // Return false only if the new file is different from the existing one.
553 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
554 Buffer->getBuffer();
555 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000556 }
557}
558
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000559bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000560 llvm::MemoryBuffer *Buffer) {
561 return addFile(P, ModificationTime,
562 llvm::MemoryBuffer::getMemBuffer(
563 Buffer->getBuffer(), Buffer->getBufferIdentifier()));
564}
565
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000566static ErrorOr<detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000567lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
568 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000569 SmallString<128> Path;
570 P.toVector(Path);
571
572 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000573 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000574 assert(!EC);
575 (void)EC;
576
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000577 if (FS.useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000578 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer4ad1c432015-10-12 13:30:38 +0000579
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000580 if (Path.empty())
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000581 return Dir;
582
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000583 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000584 while (true) {
585 detail::InMemoryNode *Node = Dir->getChild(*I);
586 ++I;
587 if (!Node)
588 return errc::no_such_file_or_directory;
589
590 // Return the file if it's at the end of the path.
591 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
592 if (I == E)
593 return File;
594 return errc::no_such_file_or_directory;
595 }
596
597 // Traverse directories.
598 Dir = cast<detail::InMemoryDirectory>(Node);
599 if (I == E)
600 return Dir;
601 }
602}
603
604llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000605 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000606 if (Node)
607 return (*Node)->getStatus();
608 return Node.getError();
609}
610
611llvm::ErrorOr<std::unique_ptr<File>>
612InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000613 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000614 if (!Node)
615 return Node.getError();
616
617 // When we have a file provide a heap-allocated wrapper for the memory buffer
618 // to match the ownership semantics for File.
619 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
620 return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
621
622 // FIXME: errc::not_a_file?
623 return make_error_code(llvm::errc::invalid_argument);
624}
625
626namespace {
627/// Adaptor from InMemoryDir::iterator to directory_iterator.
628class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
629 detail::InMemoryDirectory::const_iterator I;
630 detail::InMemoryDirectory::const_iterator E;
631
632public:
633 InMemoryDirIterator() {}
634 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
635 : I(Dir.begin()), E(Dir.end()) {
636 if (I != E)
637 CurrentEntry = I->second->getStatus();
638 }
639
640 std::error_code increment() override {
641 ++I;
642 // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
643 // the rest.
644 CurrentEntry = I != E ? I->second->getStatus() : Status();
645 return std::error_code();
646 }
647};
648} // end anonymous namespace
649
650directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
651 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000652 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000653 if (!Node) {
654 EC = Node.getError();
655 return directory_iterator(std::make_shared<InMemoryDirIterator>());
656 }
657
658 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
659 return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
660
661 EC = make_error_code(llvm::errc::not_a_directory);
662 return directory_iterator(std::make_shared<InMemoryDirIterator>());
663}
Benjamin Kramere9e76072016-01-09 16:33:16 +0000664
665std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
666 SmallString<128> Path;
667 P.toVector(Path);
668
669 // Fix up relative paths. This just prepends the current working directory.
670 std::error_code EC = makeAbsolute(Path);
671 assert(!EC);
672 (void)EC;
673
674 if (useNormalizedPaths())
675 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
676
677 if (!Path.empty())
678 WorkingDirectory = Path.str();
679 return std::error_code();
680}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000681}
682}
683
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000684//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000685// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000686//===-----------------------------------------------------------------------===/
687
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000688namespace {
689
690enum EntryKind {
691 EK_Directory,
692 EK_File
693};
694
695/// \brief A single file or directory in the VFS.
696class Entry {
697 EntryKind Kind;
698 std::string Name;
699
700public:
701 virtual ~Entry();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000702 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
703 StringRef getName() const { return Name; }
704 EntryKind getKind() const { return Kind; }
705};
706
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000707class RedirectingDirectoryEntry : public Entry {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000708 std::vector<std::unique_ptr<Entry>> Contents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000709 Status S;
710
711public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000712 RedirectingDirectoryEntry(StringRef Name,
713 std::vector<std::unique_ptr<Entry>> Contents,
714 Status S)
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000715 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000716 S(std::move(S)) {}
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000717 RedirectingDirectoryEntry(StringRef Name, Status S)
718 : Entry(EK_Directory, Name), S(std::move(S)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000719 Status getStatus() { return S; }
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000720 void addContent(std::unique_ptr<Entry> Content) {
721 Contents.push_back(std::move(Content));
722 }
723 Entry *getLastContent() const { return Contents.back().get(); }
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000724 typedef decltype(Contents)::iterator iterator;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000725 iterator contents_begin() { return Contents.begin(); }
726 iterator contents_end() { return Contents.end(); }
727 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
728};
729
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000730class RedirectingFileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000731public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000732 enum NameKind {
733 NK_NotSet,
734 NK_External,
735 NK_Virtual
736 };
737private:
738 std::string ExternalContentsPath;
739 NameKind UseName;
740public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000741 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
742 NameKind UseName)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000743 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
744 UseName(UseName) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000745 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Ben Langmuirb59cf672014-02-27 00:25:12 +0000746 /// \brief whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000747 bool useExternalName(bool GlobalUseExternalName) const {
748 return UseName == NK_NotSet ? GlobalUseExternalName
749 : (UseName == NK_External);
750 }
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000751 NameKind getUseName() const { return UseName; }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000752 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
753};
754
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000755class RedirectingFileSystem;
Ben Langmuir740812b2014-06-24 19:37:16 +0000756
757class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
758 std::string Dir;
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000759 RedirectingFileSystem &FS;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000760 RedirectingDirectoryEntry::iterator Current, End;
761
Ben Langmuir740812b2014-06-24 19:37:16 +0000762public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000763 VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000764 RedirectingDirectoryEntry::iterator Begin,
765 RedirectingDirectoryEntry::iterator End,
766 std::error_code &EC);
Ben Langmuir740812b2014-06-24 19:37:16 +0000767 std::error_code increment() override;
768};
769
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000770/// \brief A virtual file system parsed from a YAML file.
771///
772/// Currently, this class allows creating virtual directories and mapping
773/// virtual file paths to existing external files, available in \c ExternalFS.
774///
775/// The basic structure of the parsed file is:
776/// \verbatim
777/// {
778/// 'version': <version number>,
779/// <optional configuration>
780/// 'roots': [
781/// <directory entries>
782/// ]
783/// }
784/// \endverbatim
785///
786/// All configuration options are optional.
787/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000788/// 'use-external-names': <boolean, default=true>
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000789/// 'overlay-relative': <boolean, default=false>
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000790/// 'ignore-non-existent-contents': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000791///
792/// Virtual directories are represented as
793/// \verbatim
794/// {
795/// 'type': 'directory',
796/// 'name': <string>,
797/// 'contents': [ <file or directory entries> ]
798/// }
799/// \endverbatim
800///
801/// The default attributes for virtual directories are:
802/// \verbatim
803/// MTime = now() when created
804/// Perms = 0777
805/// User = Group = 0
806/// Size = 0
807/// UniqueID = unspecified unique value
808/// \endverbatim
809///
810/// Re-mapped files are represented as
811/// \verbatim
812/// {
813/// 'type': 'file',
814/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000815/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000816/// 'external-contents': <path to external file>)
817/// }
818/// \endverbatim
819///
820/// and inherit their attributes from the external contents.
821///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000822/// In both cases, the 'name' field may contain multiple path components (e.g.
823/// /path/to/file). However, any directory that contains more than one child
824/// must be uniquely represented by a directory entry.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000825class RedirectingFileSystem : public vfs::FileSystem {
826 /// The root(s) of the virtual file system.
827 std::vector<std::unique_ptr<Entry>> Roots;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000828 /// \brief The file system to use for external references.
829 IntrusiveRefCntPtr<FileSystem> ExternalFS;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000830 /// If IsRelativeOverlay is set, this represents the directory
831 /// path that should be prefixed to each 'external-contents' entry
832 /// when reading from YAML files.
833 std::string ExternalContentsPrefixDir;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000834
835 /// @name Configuration
836 /// @{
837
838 /// \brief Whether to perform case-sensitive comparisons.
839 ///
840 /// Currently, case-insensitive matching only works correctly with ASCII.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000841 bool CaseSensitive = true;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000842
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000843 /// IsRelativeOverlay marks whether a IsExternalContentsPrefixDir path must
844 /// be prefixed in every 'external-contents' when reading from YAML files.
845 bool IsRelativeOverlay = false;
846
Ben Langmuirb59cf672014-02-27 00:25:12 +0000847 /// \brief Whether to use to use the value of 'external-contents' for the
848 /// names of files. This global value is overridable on a per-file basis.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000849 bool UseExternalNames = true;
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000850
851 /// \brief Whether an invalid path obtained via 'external-contents' should
852 /// cause iteration on the VFS to stop. If 'true', the VFS should ignore
853 /// the entry and continue with the next. Allows YAML files to be shared
854 /// across multiple compiler invocations regardless of prior existent
855 /// paths in 'external-contents'. This global value is overridable on a
856 /// per-file basis.
857 bool IgnoreNonExistentContents = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000858 /// @}
859
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000860 /// Virtual file paths and external files could be canonicalized without "..",
861 /// "." and "./" in their paths. FIXME: some unittests currently fail on
862 /// win32 when using remove_dots and remove_leading_dotslash on paths.
863 bool UseCanonicalizedPaths =
864#ifdef LLVM_ON_WIN32
865 false;
866#else
867 true;
868#endif
869
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000870 friend class RedirectingFileSystemParser;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000871
872private:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000873 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000874 : ExternalFS(std::move(ExternalFS)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000875
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000876 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
877 /// recursing into the contents of \p From if it is a directory.
878 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
879 sys::path::const_iterator End, Entry *From);
880
Ben Langmuir740812b2014-06-24 19:37:16 +0000881 /// \brief Get the status of a given an \c Entry.
882 ErrorOr<Status> status(const Twine &Path, Entry *E);
883
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000884public:
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +0000885 /// \brief Looks up \p Path in \c Roots.
886 ErrorOr<Entry *> lookupPath(const Twine &Path);
887
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000888 /// \brief Parses \p Buffer, which is expected to be in YAML format and
889 /// returns a virtual file system representing its contents.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000890 static RedirectingFileSystem *
891 create(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000892 SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
893 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000894
Craig Toppera798a9d2014-03-02 09:32:10 +0000895 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000896 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000897
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000898 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
899 return ExternalFS->getCurrentWorkingDirectory();
900 }
901 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
902 return ExternalFS->setCurrentWorkingDirectory(Path);
903 }
904
Ben Langmuir740812b2014-06-24 19:37:16 +0000905 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
906 ErrorOr<Entry *> E = lookupPath(Dir);
907 if (!E) {
908 EC = E.getError();
909 return directory_iterator();
910 }
911 ErrorOr<Status> S = status(Dir, *E);
912 if (!S) {
913 EC = S.getError();
914 return directory_iterator();
915 }
916 if (!S->isDirectory()) {
917 EC = std::error_code(static_cast<int>(errc::not_a_directory),
918 std::system_category());
919 return directory_iterator();
920 }
921
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000922 auto *D = cast<RedirectingDirectoryEntry>(*E);
Ben Langmuir740812b2014-06-24 19:37:16 +0000923 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
924 *this, D->contents_begin(), D->contents_end(), EC));
925 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000926
927 void setExternalContentsPrefixDir(StringRef PrefixDir) {
928 ExternalContentsPrefixDir = PrefixDir.str();
929 }
930
931 StringRef getExternalContentsPrefixDir() const {
932 return ExternalContentsPrefixDir;
933 }
934
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000935 bool ignoreNonExistentContents() const {
936 return IgnoreNonExistentContents;
937 }
938
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +0000939#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
940LLVM_DUMP_METHOD void dump() const {
941 for (const std::unique_ptr<Entry> &Root : Roots)
942 dumpEntry(Root.get());
943 }
944
945LLVM_DUMP_METHOD void dumpEntry(Entry *E, int NumSpaces = 0) const {
946 StringRef Name = E->getName();
947 for (int i = 0, e = NumSpaces; i < e; ++i)
948 dbgs() << " ";
949 dbgs() << "'" << Name.str().c_str() << "'" << "\n";
950
951 if (E->getKind() == EK_Directory) {
952 auto *DE = dyn_cast<RedirectingDirectoryEntry>(E);
953 assert(DE && "Should be a directory");
954
955 for (std::unique_ptr<Entry> &SubEntry :
956 llvm::make_range(DE->contents_begin(), DE->contents_end()))
957 dumpEntry(SubEntry.get(), NumSpaces+2);
958 }
959 }
960#endif
961
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000962};
963
964/// \brief A helper class to hold the common YAML parsing state.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000965class RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000966 yaml::Stream &Stream;
967
968 void error(yaml::Node *N, const Twine &Msg) {
969 Stream.printError(N, Msg);
970 }
971
972 // false on error
973 bool parseScalarString(yaml::Node *N, StringRef &Result,
974 SmallVectorImpl<char> &Storage) {
975 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
976 if (!S) {
977 error(N, "expected string");
978 return false;
979 }
980 Result = S->getValue(Storage);
981 return true;
982 }
983
984 // false on error
985 bool parseScalarBool(yaml::Node *N, bool &Result) {
986 SmallString<5> Storage;
987 StringRef Value;
988 if (!parseScalarString(N, Value, Storage))
989 return false;
990
991 if (Value.equals_lower("true") || Value.equals_lower("on") ||
992 Value.equals_lower("yes") || Value == "1") {
993 Result = true;
994 return true;
995 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
996 Value.equals_lower("no") || Value == "0") {
997 Result = false;
998 return true;
999 }
1000
1001 error(N, "expected boolean value");
1002 return false;
1003 }
1004
1005 struct KeyStatus {
1006 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
1007 bool Required;
1008 bool Seen;
1009 };
1010 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
1011
1012 // false on error
1013 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1014 DenseMap<StringRef, KeyStatus> &Keys) {
1015 if (!Keys.count(Key)) {
1016 error(KeyNode, "unknown key");
1017 return false;
1018 }
1019 KeyStatus &S = Keys[Key];
1020 if (S.Seen) {
1021 error(KeyNode, Twine("duplicate key '") + Key + "'");
1022 return false;
1023 }
1024 S.Seen = true;
1025 return true;
1026 }
1027
1028 // false on error
1029 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
1030 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
1031 E = Keys.end();
1032 I != E; ++I) {
1033 if (I->second.Required && !I->second.Seen) {
1034 error(Obj, Twine("missing key '") + I->first + "'");
1035 return false;
1036 }
1037 }
1038 return true;
1039 }
1040
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001041 Entry *lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1042 Entry *ParentEntry = nullptr) {
1043 if (!ParentEntry) { // Look for a existent root
1044 for (const std::unique_ptr<Entry> &Root : FS->Roots) {
1045 if (Name.equals(Root->getName())) {
1046 ParentEntry = Root.get();
1047 return ParentEntry;
1048 }
1049 }
1050 } else { // Advance to the next component
1051 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1052 for (std::unique_ptr<Entry> &Content :
1053 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1054 auto *DirContent = dyn_cast<RedirectingDirectoryEntry>(Content.get());
1055 if (DirContent && Name.equals(Content->getName()))
1056 return DirContent;
1057 }
1058 }
1059
1060 // ... or create a new one
1061 std::unique_ptr<Entry> E = llvm::make_unique<RedirectingDirectoryEntry>(
Pavel Labathac71c8e2016-11-09 10:52:22 +00001062 Name,
1063 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1064 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001065
1066 if (!ParentEntry) { // Add a new root to the overlay
1067 FS->Roots.push_back(std::move(E));
1068 ParentEntry = FS->Roots.back().get();
1069 return ParentEntry;
1070 }
1071
1072 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1073 DE->addContent(std::move(E));
1074 return DE->getLastContent();
1075 }
1076
1077 void uniqueOverlayTree(RedirectingFileSystem *FS, Entry *SrcE,
1078 Entry *NewParentE = nullptr) {
1079 StringRef Name = SrcE->getName();
1080 switch (SrcE->getKind()) {
1081 case EK_Directory: {
1082 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1083 assert(DE && "Must be a directory");
1084 // Empty directories could be present in the YAML as a way to
1085 // describe a file for a current directory after some of its subdir
1086 // is parsed. This only leads to redundant walks, ignore it.
1087 if (!Name.empty())
1088 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1089 for (std::unique_ptr<Entry> &SubEntry :
1090 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1091 uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1092 break;
1093 }
1094 case EK_File: {
1095 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1096 assert(FE && "Must be a file");
1097 assert(NewParentE && "Parent entry must exist");
1098 auto *DE = dyn_cast<RedirectingDirectoryEntry>(NewParentE);
1099 DE->addContent(llvm::make_unique<RedirectingFileEntry>(
1100 Name, FE->getExternalContentsPath(), FE->getUseName()));
1101 break;
1102 }
1103 }
1104 }
1105
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001106 std::unique_ptr<Entry> parseEntry(yaml::Node *N, RedirectingFileSystem *FS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001107 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
1108 if (!M) {
1109 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +00001110 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001111 }
1112
1113 KeyStatusPair Fields[] = {
1114 KeyStatusPair("name", true),
1115 KeyStatusPair("type", true),
1116 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001117 KeyStatusPair("external-contents", false),
1118 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001119 };
1120
Craig Topperac67c052015-11-30 03:11:10 +00001121 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001122
1123 bool HasContents = false; // external or otherwise
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001124 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001125 std::string ExternalContentsPath;
1126 std::string Name;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001127 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001128 EntryKind Kind;
1129
1130 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
1131 ++I) {
1132 StringRef Key;
1133 // Reuse the buffer for key and value, since we don't look at key after
1134 // parsing value.
1135 SmallString<256> Buffer;
1136 if (!parseScalarString(I->getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001137 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001138
1139 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001140 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001141
1142 StringRef Value;
1143 if (Key == "name") {
1144 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001145 return nullptr;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001146
1147 if (FS->UseCanonicalizedPaths) {
1148 SmallString<256> Path(Value);
1149 // Guarantee that old YAML files containing paths with ".." and "."
1150 // are properly canonicalized before read into the VFS.
1151 Path = sys::path::remove_leading_dotslash(Path);
1152 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1153 Name = Path.str();
1154 } else {
1155 Name = Value;
1156 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001157 } else if (Key == "type") {
1158 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001159 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001160 if (Value == "file")
1161 Kind = EK_File;
1162 else if (Value == "directory")
1163 Kind = EK_Directory;
1164 else {
1165 error(I->getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +00001166 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001167 }
1168 } else if (Key == "contents") {
1169 if (HasContents) {
1170 error(I->getKey(),
1171 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001172 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001173 }
1174 HasContents = true;
1175 yaml::SequenceNode *Contents =
1176 dyn_cast<yaml::SequenceNode>(I->getValue());
1177 if (!Contents) {
1178 // FIXME: this is only for directories, what about files?
1179 error(I->getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +00001180 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001181 }
1182
1183 for (yaml::SequenceNode::iterator I = Contents->begin(),
1184 E = Contents->end();
1185 I != E; ++I) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001186 if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001187 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001188 else
Craig Topperf1186c52014-05-08 06:41:40 +00001189 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001190 }
1191 } else if (Key == "external-contents") {
1192 if (HasContents) {
1193 error(I->getKey(),
1194 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001195 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001196 }
1197 HasContents = true;
1198 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001199 return nullptr;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001200
1201 SmallString<256> FullPath;
1202 if (FS->IsRelativeOverlay) {
1203 FullPath = FS->getExternalContentsPrefixDir();
1204 assert(!FullPath.empty() &&
1205 "External contents prefix directory must exist");
1206 llvm::sys::path::append(FullPath, Value);
1207 } else {
1208 FullPath = Value;
1209 }
1210
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001211 if (FS->UseCanonicalizedPaths) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001212 // Guarantee that old YAML files containing paths with ".." and "."
1213 // are properly canonicalized before read into the VFS.
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001214 FullPath = sys::path::remove_leading_dotslash(FullPath);
1215 sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001216 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001217 ExternalContentsPath = FullPath.str();
Ben Langmuirb59cf672014-02-27 00:25:12 +00001218 } else if (Key == "use-external-name") {
1219 bool Val;
1220 if (!parseScalarBool(I->getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001221 return nullptr;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001222 UseExternalName = Val ? RedirectingFileEntry::NK_External
1223 : RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001224 } else {
1225 llvm_unreachable("key missing from Keys");
1226 }
1227 }
1228
1229 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001230 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001231
1232 // check for missing keys
1233 if (!HasContents) {
1234 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001235 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001236 }
1237 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001238 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001239
Ben Langmuirb59cf672014-02-27 00:25:12 +00001240 // check invalid configuration
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001241 if (Kind == EK_Directory &&
1242 UseExternalName != RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001243 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001244 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001245 }
1246
Ben Langmuir93853232014-03-05 21:32:20 +00001247 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001248 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001249 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1250 while (Trimmed.size() > RootPathLen &&
1251 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001252 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1253 // Get the last component
1254 StringRef LastComponent = sys::path::filename(Trimmed);
1255
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001256 std::unique_ptr<Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001257 switch (Kind) {
1258 case EK_File:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001259 Result = llvm::make_unique<RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001260 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001261 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001262 case EK_Directory:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001263 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001264 LastComponent, std::move(EntryArrayContents),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001265 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1266 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001267 break;
1268 }
1269
1270 StringRef Parent = sys::path::parent_path(Trimmed);
1271 if (Parent.empty())
1272 return Result;
1273
1274 // if 'name' contains multiple components, create implicit directory entries
1275 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1276 E = sys::path::rend(Parent);
1277 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001278 std::vector<std::unique_ptr<Entry>> Entries;
1279 Entries.push_back(std::move(Result));
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001280 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001281 *I, std::move(Entries),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001282 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1283 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001284 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001285 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001286 }
1287
1288public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001289 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001290
1291 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001292 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001293 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
1294 if (!Top) {
1295 error(Root, "expected mapping node");
1296 return false;
1297 }
1298
1299 KeyStatusPair Fields[] = {
1300 KeyStatusPair("version", true),
1301 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001302 KeyStatusPair("use-external-names", false),
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001303 KeyStatusPair("overlay-relative", false),
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001304 KeyStatusPair("ignore-non-existent-contents", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001305 KeyStatusPair("roots", true),
1306 };
1307
Craig Topperac67c052015-11-30 03:11:10 +00001308 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001309 std::vector<std::unique_ptr<Entry>> RootEntries;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001310
1311 // Parse configuration and 'roots'
1312 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
1313 ++I) {
1314 SmallString<10> KeyBuffer;
1315 StringRef Key;
1316 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
1317 return false;
1318
1319 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1320 return false;
1321
1322 if (Key == "roots") {
1323 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
1324 if (!Roots) {
1325 error(I->getValue(), "expected array");
1326 return false;
1327 }
1328
1329 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
1330 I != E; ++I) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001331 if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001332 RootEntries.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001333 else
1334 return false;
1335 }
1336 } else if (Key == "version") {
1337 StringRef VersionString;
1338 SmallString<4> Storage;
1339 if (!parseScalarString(I->getValue(), VersionString, Storage))
1340 return false;
1341 int Version;
1342 if (VersionString.getAsInteger<int>(10, Version)) {
1343 error(I->getValue(), "expected integer");
1344 return false;
1345 }
1346 if (Version < 0) {
1347 error(I->getValue(), "invalid version number");
1348 return false;
1349 }
1350 if (Version != 0) {
1351 error(I->getValue(), "version mismatch, expected 0");
1352 return false;
1353 }
1354 } else if (Key == "case-sensitive") {
1355 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
1356 return false;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001357 } else if (Key == "overlay-relative") {
1358 if (!parseScalarBool(I->getValue(), FS->IsRelativeOverlay))
1359 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001360 } else if (Key == "use-external-names") {
1361 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
1362 return false;
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001363 } else if (Key == "ignore-non-existent-contents") {
1364 if (!parseScalarBool(I->getValue(), FS->IgnoreNonExistentContents))
1365 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001366 } else {
1367 llvm_unreachable("key missing from Keys");
1368 }
1369 }
1370
1371 if (Stream.failed())
1372 return false;
1373
1374 if (!checkMissingKeys(Top, Keys))
1375 return false;
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001376
1377 // Now that we sucessefully parsed the YAML file, canonicalize the internal
1378 // representation to a proper directory tree so that we can search faster
1379 // inside the VFS.
1380 for (std::unique_ptr<Entry> &E : RootEntries)
1381 uniqueOverlayTree(FS, E.get());
1382
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001383 return true;
1384 }
1385};
1386} // end of anonymous namespace
1387
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001388Entry::~Entry() = default;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001389
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001390RedirectingFileSystem *
1391RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1392 SourceMgr::DiagHandlerTy DiagHandler,
1393 StringRef YAMLFilePath, void *DiagContext,
1394 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001395
1396 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001397 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001398
Ben Langmuir97882e72014-02-24 20:56:37 +00001399 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001400 yaml::document_iterator DI = Stream.begin();
1401 yaml::Node *Root = DI->getRoot();
1402 if (DI == Stream.end() || !Root) {
1403 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001404 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001405 }
1406
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001407 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001408
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001409 std::unique_ptr<RedirectingFileSystem> FS(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001410 new RedirectingFileSystem(std::move(ExternalFS)));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001411
1412 if (!YAMLFilePath.empty()) {
1413 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1414 // to each 'external-contents' path.
1415 //
1416 // Example:
1417 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
1418 // yields:
1419 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1420 //
1421 SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1422 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1423 assert(!EC && "Overlay dir final path must be absolute");
1424 (void)EC;
1425 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1426 }
1427
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001428 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001429 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001430
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001431 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001432}
1433
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001434ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001435 SmallString<256> Path;
1436 Path_.toVector(Path);
1437
1438 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001439 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001440 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001441
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001442 // Canonicalize path by removing ".", "..", "./", etc components. This is
1443 // a VFS request, do bot bother about symlinks in the path components
1444 // but canonicalize in order to perform the correct entry search.
1445 if (UseCanonicalizedPaths) {
1446 Path = sys::path::remove_leading_dotslash(Path);
1447 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1448 }
1449
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001450 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001451 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001452
1453 sys::path::const_iterator Start = sys::path::begin(Path);
1454 sys::path::const_iterator End = sys::path::end(Path);
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001455 for (const std::unique_ptr<Entry> &Root : Roots) {
1456 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001457 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001458 return Result;
1459 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001460 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001461}
1462
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001463ErrorOr<Entry *>
1464RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1465 sys::path::const_iterator End, Entry *From) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001466#ifndef LLVM_ON_WIN32
1467 assert(!isTraversalComponent(*Start) &&
1468 !isTraversalComponent(From->getName()) &&
1469 "Paths should not contain traversal components");
1470#else
1471 // FIXME: this is here to support windows, remove it once canonicalized
1472 // paths become globally default.
Bruno Cardoso Lopesbe056b12016-02-23 17:06:50 +00001473 if (Start->equals("."))
1474 ++Start;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001475#endif
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001476
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001477 StringRef FromName = From->getName();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001478
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001479 // Forward the search to the next component in case this is an empty one.
1480 if (!FromName.empty()) {
1481 if (CaseSensitive ? !Start->equals(FromName)
1482 : !Start->equals_lower(FromName))
1483 // failure to match
1484 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001485
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001486 ++Start;
1487
1488 if (Start == End) {
1489 // Match!
1490 return From;
1491 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001492 }
1493
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001494 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001495 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001496 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001497
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001498 for (const std::unique_ptr<Entry> &DirEntry :
1499 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1500 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001501 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001502 return Result;
1503 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001504 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001505}
1506
Ben Langmuirf13302e2015-12-10 23:41:39 +00001507static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1508 Status ExternalStatus) {
1509 Status S = ExternalStatus;
1510 if (!UseExternalNames)
1511 S = Status::copyWithNewName(S, Path.str());
1512 S.IsVFSMapped = true;
1513 return S;
1514}
1515
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001516ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001517 assert(E != nullptr);
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001518 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001519 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001520 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuir5de00f32014-05-23 18:15:47 +00001521 if (S)
Ben Langmuirf13302e2015-12-10 23:41:39 +00001522 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1523 *S);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001524 return S;
1525 } else { // directory
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001526 auto *DE = cast<RedirectingDirectoryEntry>(E);
Ben Langmuirf13302e2015-12-10 23:41:39 +00001527 return Status::copyWithNewName(DE->getStatus(), Path.str());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001528 }
1529}
1530
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001531ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001532 ErrorOr<Entry *> Result = lookupPath(Path);
1533 if (!Result)
1534 return Result.getError();
1535 return status(Path, *Result);
1536}
1537
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001538namespace {
Ben Langmuirf13302e2015-12-10 23:41:39 +00001539/// Provide a file wrapper with an overriden status.
1540class FileWithFixedStatus : public File {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001541 std::unique_ptr<File> InnerFile;
Ben Langmuirf13302e2015-12-10 23:41:39 +00001542 Status S;
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001543
1544public:
Ben Langmuirf13302e2015-12-10 23:41:39 +00001545 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
Benjamin Kramercfeacf52016-05-27 14:27:13 +00001546 : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001547
Ben Langmuirf13302e2015-12-10 23:41:39 +00001548 ErrorOr<Status> status() override { return S; }
1549 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +00001550 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1551 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001552 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1553 IsVolatile);
1554 }
1555 std::error_code close() override { return InnerFile->close(); }
1556};
1557} // end anonymous namespace
1558
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001559ErrorOr<std::unique_ptr<File>>
1560RedirectingFileSystem::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001561 ErrorOr<Entry *> E = lookupPath(Path);
1562 if (!E)
1563 return E.getError();
1564
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001565 auto *F = dyn_cast<RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001566 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001567 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001568
Benjamin Kramera8857962014-10-26 22:44:13 +00001569 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1570 if (!Result)
1571 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001572
Ben Langmuirf13302e2015-12-10 23:41:39 +00001573 auto ExternalStatus = (*Result)->status();
1574 if (!ExternalStatus)
1575 return ExternalStatus.getError();
Ben Langmuird066d4c2014-02-28 21:16:07 +00001576
Ben Langmuirf13302e2015-12-10 23:41:39 +00001577 // FIXME: Update the status with the name and VFSMapped.
1578 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1579 *ExternalStatus);
1580 return std::unique_ptr<File>(
1581 llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001582}
1583
1584IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001585vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001586 SourceMgr::DiagHandlerTy DiagHandler,
1587 StringRef YAMLFilePath,
1588 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001589 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001590 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001591 YAMLFilePath, DiagContext,
1592 std::move(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001593}
1594
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001595static void getVFSEntries(Entry *SrcE, SmallVectorImpl<StringRef> &Path,
1596 SmallVectorImpl<YAMLVFSEntry> &Entries) {
1597 auto Kind = SrcE->getKind();
1598 if (Kind == EK_Directory) {
1599 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1600 assert(DE && "Must be a directory");
1601 for (std::unique_ptr<Entry> &SubEntry :
1602 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1603 Path.push_back(SubEntry->getName());
1604 getVFSEntries(SubEntry.get(), Path, Entries);
1605 Path.pop_back();
1606 }
1607 return;
1608 }
1609
1610 assert(Kind == EK_File && "Must be a EK_File");
1611 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1612 assert(FE && "Must be a file");
1613 SmallString<128> VPath;
1614 for (auto &Comp : Path)
1615 llvm::sys::path::append(VPath, Comp);
1616 Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
1617}
1618
1619void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1620 SourceMgr::DiagHandlerTy DiagHandler,
1621 StringRef YAMLFilePath,
1622 SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
1623 void *DiagContext,
1624 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1625 RedirectingFileSystem *VFS = RedirectingFileSystem::create(
1626 std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
1627 std::move(ExternalFS));
1628 ErrorOr<Entry *> RootE = VFS->lookupPath("/");
1629 if (!RootE)
1630 return;
1631 SmallVector<StringRef, 8> Components;
1632 Components.push_back("/");
1633 getVFSEntries(*RootE, Components, CollectedEntries);
1634}
1635
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001636UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001637 static std::atomic<unsigned> UID;
1638 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001639 // The following assumes that uint64_t max will never collide with a real
1640 // dev_t value from the OS.
1641 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1642}
Justin Bogner9c785292014-05-20 21:43:27 +00001643
Justin Bogner9c785292014-05-20 21:43:27 +00001644void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1645 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1646 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1647 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1648 Mappings.emplace_back(VirtualPath, RealPath);
1649}
1650
Justin Bogner44fa450342014-05-21 22:46:51 +00001651namespace {
1652class JSONWriter {
1653 llvm::raw_ostream &OS;
1654 SmallVector<StringRef, 16> DirStack;
1655 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
1656 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1657 bool containedIn(StringRef Parent, StringRef Path);
1658 StringRef containedPart(StringRef Parent, StringRef Path);
1659 void startDirectory(StringRef Path);
1660 void endDirectory();
1661 void writeEntry(StringRef VPath, StringRef RPath);
1662
1663public:
1664 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001665 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
1666 Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001667 Optional<bool> IgnoreNonExistentContents, StringRef OverlayDir);
Justin Bogner44fa450342014-05-21 22:46:51 +00001668};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001669}
Justin Bogner9c785292014-05-20 21:43:27 +00001670
Justin Bogner44fa450342014-05-21 22:46:51 +00001671bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001672 using namespace llvm::sys;
1673 // Compare each path component.
1674 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1675 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1676 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1677 if (*IParent != *IChild)
1678 return false;
1679 }
1680 // Have we exhausted the parent path?
1681 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001682}
1683
Justin Bogner44fa450342014-05-21 22:46:51 +00001684StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1685 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001686 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001687 return Path.slice(Parent.size() + 1, StringRef::npos);
1688}
1689
Justin Bogner44fa450342014-05-21 22:46:51 +00001690void JSONWriter::startDirectory(StringRef Path) {
1691 StringRef Name =
1692 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1693 DirStack.push_back(Path);
1694 unsigned Indent = getDirIndent();
1695 OS.indent(Indent) << "{\n";
1696 OS.indent(Indent + 2) << "'type': 'directory',\n";
1697 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1698 OS.indent(Indent + 2) << "'contents': [\n";
1699}
1700
1701void JSONWriter::endDirectory() {
1702 unsigned Indent = getDirIndent();
1703 OS.indent(Indent + 2) << "]\n";
1704 OS.indent(Indent) << "}";
1705
1706 DirStack.pop_back();
1707}
1708
1709void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1710 unsigned Indent = getFileIndent();
1711 OS.indent(Indent) << "{\n";
1712 OS.indent(Indent + 2) << "'type': 'file',\n";
1713 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1714 OS.indent(Indent + 2) << "'external-contents': \""
1715 << llvm::yaml::escape(RPath) << "\"\n";
1716 OS.indent(Indent) << "}";
1717}
1718
1719void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001720 Optional<bool> UseExternalNames,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001721 Optional<bool> IsCaseSensitive,
1722 Optional<bool> IsOverlayRelative,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001723 Optional<bool> IgnoreNonExistentContents,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001724 StringRef OverlayDir) {
Justin Bogner44fa450342014-05-21 22:46:51 +00001725 using namespace llvm::sys;
1726
1727 OS << "{\n"
1728 " 'version': 0,\n";
1729 if (IsCaseSensitive.hasValue())
1730 OS << " 'case-sensitive': '"
1731 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001732 if (UseExternalNames.hasValue())
1733 OS << " 'use-external-names': '"
1734 << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001735 bool UseOverlayRelative = false;
1736 if (IsOverlayRelative.hasValue()) {
1737 UseOverlayRelative = IsOverlayRelative.getValue();
1738 OS << " 'overlay-relative': '"
1739 << (UseOverlayRelative ? "true" : "false") << "',\n";
1740 }
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001741 if (IgnoreNonExistentContents.hasValue())
1742 OS << " 'ignore-non-existent-contents': '"
1743 << (IgnoreNonExistentContents.getValue() ? "true" : "false") << "',\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001744 OS << " 'roots': [\n";
1745
Justin Bogner73466402014-07-15 01:24:35 +00001746 if (!Entries.empty()) {
1747 const YAMLVFSEntry &Entry = Entries.front();
1748 startDirectory(path::parent_path(Entry.VPath));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001749
1750 StringRef RPath = Entry.RPath;
1751 if (UseOverlayRelative) {
1752 unsigned OverlayDirLen = OverlayDir.size();
1753 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1754 "Overlay dir must be contained in RPath");
1755 RPath = RPath.slice(OverlayDirLen, RPath.size());
1756 }
1757
1758 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001759
Justin Bogner73466402014-07-15 01:24:35 +00001760 for (const auto &Entry : Entries.slice(1)) {
1761 StringRef Dir = path::parent_path(Entry.VPath);
1762 if (Dir == DirStack.back())
1763 OS << ",\n";
1764 else {
1765 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1766 OS << "\n";
1767 endDirectory();
1768 }
1769 OS << ",\n";
1770 startDirectory(Dir);
1771 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001772 StringRef RPath = Entry.RPath;
1773 if (UseOverlayRelative) {
1774 unsigned OverlayDirLen = OverlayDir.size();
1775 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1776 "Overlay dir must be contained in RPath");
1777 RPath = RPath.slice(OverlayDirLen, RPath.size());
1778 }
1779 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner73466402014-07-15 01:24:35 +00001780 }
1781
1782 while (!DirStack.empty()) {
1783 OS << "\n";
1784 endDirectory();
1785 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001786 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001787 }
1788
Justin Bogner73466402014-07-15 01:24:35 +00001789 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001790 << "}\n";
1791}
1792
Justin Bogner9c785292014-05-20 21:43:27 +00001793void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1794 std::sort(Mappings.begin(), Mappings.end(),
Justin Bogner44fa450342014-05-21 22:46:51 +00001795 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001796 return LHS.VPath < RHS.VPath;
1797 });
1798
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001799 JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001800 IsOverlayRelative, IgnoreNonExistentContents,
1801 OverlayDir);
Justin Bogner9c785292014-05-20 21:43:27 +00001802}
Ben Langmuir740812b2014-06-24 19:37:16 +00001803
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001804VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1805 const Twine &_Path, RedirectingFileSystem &FS,
1806 RedirectingDirectoryEntry::iterator Begin,
1807 RedirectingDirectoryEntry::iterator End, std::error_code &EC)
Ben Langmuir740812b2014-06-24 19:37:16 +00001808 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001809 while (Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001810 SmallString<128> PathStr(Dir);
1811 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001812 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001813 if (S) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001814 CurrentEntry = *S;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001815 return;
1816 }
1817 // Skip entries which do not map to a reliable external content.
1818 if (FS.ignoreNonExistentContents() &&
1819 S.getError() == llvm::errc::no_such_file_or_directory) {
1820 ++Current;
1821 continue;
1822 } else {
Ben Langmuir740812b2014-06-24 19:37:16 +00001823 EC = S.getError();
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001824 break;
1825 }
Ben Langmuir740812b2014-06-24 19:37:16 +00001826 }
1827}
1828
1829std::error_code VFSFromYamlDirIterImpl::increment() {
1830 assert(Current != End && "cannot iterate past end");
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001831 while (++Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001832 SmallString<128> PathStr(Dir);
1833 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001834 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001835 if (!S) {
1836 // Skip entries which do not map to a reliable external content.
1837 if (FS.ignoreNonExistentContents() &&
1838 S.getError() == llvm::errc::no_such_file_or_directory) {
1839 continue;
1840 } else {
1841 return S.getError();
1842 }
1843 }
Ben Langmuir740812b2014-06-24 19:37:16 +00001844 CurrentEntry = *S;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001845 break;
Bruno Cardoso Lopese43e2632016-08-12 02:17:26 +00001846 }
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001847
1848 if (Current == End)
1849 CurrentEntry = Status();
Ben Langmuir740812b2014-06-24 19:37:16 +00001850 return std::error_code();
1851}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001852
1853vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1854 const Twine &Path,
1855 std::error_code &EC)
1856 : FS(&FS_) {
1857 directory_iterator I = FS->dir_begin(Path, EC);
Juergen Ributzkaf9787432017-03-14 00:14:40 +00001858 if (I != directory_iterator()) {
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001859 State = std::make_shared<IterState>();
1860 State->push(I);
1861 }
1862}
1863
1864vfs::recursive_directory_iterator &
1865recursive_directory_iterator::increment(std::error_code &EC) {
1866 assert(FS && State && !State->empty() && "incrementing past end");
1867 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1868 vfs::directory_iterator End;
1869 if (State->top()->isDirectory()) {
1870 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001871 if (I != End) {
1872 State->push(I);
1873 return *this;
1874 }
1875 }
1876
1877 while (!State->empty() && State->top().increment(EC) == End)
1878 State->pop();
1879
1880 if (State->empty())
1881 State.reset(); // end iterator
1882
1883 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001884}