blob: cb09e2ec84f326e9f1bc16a06c9cc68ee8a8ee99 [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 Kramerdecb2ae2015-10-09 13:03:22 +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"
Rafael Espindola71de0b62014-06-13 17:20:50 +000019#include "llvm/Support/Errc.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000020#include "llvm/Support/MemoryBuffer.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000021#include "llvm/Support/Path.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000022#include "llvm/Support/YAMLParser.h"
Benjamin Kramerd6bbee72015-10-05 14:06:36 +000023#include "llvm/Config/llvm-config.h"
Benjamin Kramer4527fb22014-03-02 17:08:31 +000024#include <atomic>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000025#include <memory>
Ben Langmuirc8130a72014-02-20 21:59:23 +000026
Benjamin Kramerd6bbee72015-10-05 14:06:36 +000027// For chdir.
28#ifdef LLVM_ON_WIN32
29# include <direct.h>
30#else
31# include <unistd.h>
32#endif
33
Ben Langmuirc8130a72014-02-20 21:59:23 +000034using namespace clang;
35using namespace clang::vfs;
36using namespace llvm;
37using llvm::sys::fs::file_status;
38using llvm::sys::fs::file_type;
39using llvm::sys::fs::perms;
40using llvm::sys::fs::UniqueID;
41
42Status::Status(const file_status &Status)
43 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
44 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
Ben Langmuir5de00f32014-05-23 18:15:47 +000045 Type(Status.type()), Perms(Status.permissions()), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000046
Benjamin Kramer268b51a2015-10-05 13:15:33 +000047Status::Status(StringRef Name, UniqueID UID, sys::TimeValue MTime,
48 uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
49 perms Perms)
Ben Langmuirb59cf672014-02-27 00:25:12 +000050 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
Ben Langmuir5de00f32014-05-23 18:15:47 +000051 Type(Type), Perms(Perms), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000052
Benjamin Kramer268b51a2015-10-05 13:15:33 +000053Status Status::copyWithNewName(const Status &In, StringRef NewName) {
54 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
55 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
56 In.getPermissions());
57}
58
59Status Status::copyWithNewName(const file_status &In, StringRef NewName) {
60 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
61 In.getUser(), In.getGroup(), In.getSize(), In.type(),
62 In.permissions());
63}
64
Ben Langmuirc8130a72014-02-20 21:59:23 +000065bool Status::equivalent(const Status &Other) const {
66 return getUniqueID() == Other.getUniqueID();
67}
68bool Status::isDirectory() const {
69 return Type == file_type::directory_file;
70}
71bool Status::isRegularFile() const {
72 return Type == file_type::regular_file;
73}
74bool Status::isOther() const {
75 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
76}
77bool Status::isSymlink() const {
78 return Type == file_type::symlink_file;
79}
80bool Status::isStatusKnown() const {
81 return Type != file_type::status_error;
82}
83bool Status::exists() const {
84 return isStatusKnown() && Type != file_type::file_not_found;
85}
86
87File::~File() {}
88
89FileSystem::~FileSystem() {}
90
Benjamin Kramera8857962014-10-26 22:44:13 +000091ErrorOr<std::unique_ptr<MemoryBuffer>>
92FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
93 bool RequiresNullTerminator, bool IsVolatile) {
94 auto F = openFileForRead(Name);
95 if (!F)
96 return F.getError();
Ben Langmuirc8130a72014-02-20 21:59:23 +000097
Benjamin Kramera8857962014-10-26 22:44:13 +000098 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +000099}
100
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000101std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
102 auto WorkingDir = getCurrentWorkingDirectory();
103 if (!WorkingDir)
104 return WorkingDir.getError();
105
106 return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
107}
108
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000109bool FileSystem::exists(const Twine &Path) {
110 auto Status = status(Path);
111 return Status && Status->exists();
112}
113
Ben Langmuirc8130a72014-02-20 21:59:23 +0000114//===-----------------------------------------------------------------------===/
115// RealFileSystem implementation
116//===-----------------------------------------------------------------------===/
117
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000118namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000119/// \brief Wrapper around a raw file descriptor.
120class RealFile : public File {
121 int FD;
Ben Langmuird066d4c2014-02-28 21:16:07 +0000122 Status S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000123 friend class RealFileSystem;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000124 RealFile(int FD, StringRef NewName)
125 : FD(FD), S(NewName, {}, {}, {}, {}, {},
126 llvm::sys::fs::file_type::status_error, {}) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000127 assert(FD >= 0 && "Invalid or inactive file descriptor");
128 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000129
Ben Langmuirc8130a72014-02-20 21:59:23 +0000130public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000131 ~RealFile() override;
Craig Toppera798a9d2014-03-02 09:32:10 +0000132 ErrorOr<Status> status() override;
Benjamin Kramer737501c2015-10-05 21:20:19 +0000133 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
134 int64_t FileSize,
135 bool RequiresNullTerminator,
136 bool IsVolatile) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000137 std::error_code close() override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000138};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000139} // end anonymous namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000140RealFile::~RealFile() { close(); }
Ben Langmuirc8130a72014-02-20 21:59:23 +0000141
142ErrorOr<Status> RealFile::status() {
143 assert(FD != -1 && "cannot stat closed file");
Ben Langmuird066d4c2014-02-28 21:16:07 +0000144 if (!S.isStatusKnown()) {
145 file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000146 if (std::error_code EC = sys::fs::status(FD, RealStatus))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000147 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000148 S = Status::copyWithNewName(RealStatus, S.getName());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000149 }
150 return S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000151}
152
Benjamin Kramera8857962014-10-26 22:44:13 +0000153ErrorOr<std::unique_ptr<MemoryBuffer>>
154RealFile::getBuffer(const Twine &Name, int64_t FileSize,
155 bool RequiresNullTerminator, bool IsVolatile) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000156 assert(FD != -1 && "cannot get buffer for closed file");
Benjamin Kramera8857962014-10-26 22:44:13 +0000157 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
158 IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000159}
160
161// FIXME: This is terrible, we need this for ::close.
162#if !defined(_MSC_VER) && !defined(__MINGW32__)
163#include <unistd.h>
164#include <sys/uio.h>
165#else
166#include <io.h>
167#ifndef S_ISFIFO
168#define S_ISFIFO(x) (0)
169#endif
170#endif
Rafael Espindola8e650d72014-06-12 20:37:59 +0000171std::error_code RealFile::close() {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000172 if (::close(FD))
Rafael Espindola8e650d72014-06-12 20:37:59 +0000173 return std::error_code(errno, std::generic_category());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000174 FD = -1;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000175 return std::error_code();
Ben Langmuirc8130a72014-02-20 21:59:23 +0000176}
177
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000178namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000179/// \brief The file system according to your operating system.
180class RealFileSystem : public FileSystem {
181public:
Craig Toppera798a9d2014-03-02 09:32:10 +0000182 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000183 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000184 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000185
186 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
187 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000188};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000189} // end anonymous namespace
Ben Langmuirc8130a72014-02-20 21:59:23 +0000190
191ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
192 sys::fs::file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000193 if (std::error_code EC = sys::fs::status(Path, RealStatus))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000194 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000195 return Status::copyWithNewName(RealStatus, Path.str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000196}
197
Benjamin Kramera8857962014-10-26 22:44:13 +0000198ErrorOr<std::unique_ptr<File>>
199RealFileSystem::openFileForRead(const Twine &Name) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000200 int FD;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000201 if (std::error_code EC = sys::fs::openFileForRead(Name, FD))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000202 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000203 return std::unique_ptr<File>(new RealFile(FD, Name.str()));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000204}
205
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000206llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
207 SmallString<256> Dir;
208 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
209 return EC;
210 return Dir.str().str();
211}
212
213std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
214 // FIXME: chdir is thread hostile; on the other hand, creating the same
215 // behavior as chdir is complex: chdir resolves the path once, thus
216 // guaranteeing that all subsequent relative path operations work
217 // on the same path the original chdir resulted in. This makes a
218 // difference for example on network filesystems, where symlinks might be
219 // switched during runtime of the tool. Fixing this depends on having a
220 // file system abstraction that allows openat() style interactions.
221 SmallString<256> Storage;
222 StringRef Dir = Path.toNullTerminatedStringRef(Storage);
223 if (int Err = ::chdir(Dir.data()))
224 return std::error_code(Err, std::generic_category());
225 return std::error_code();
226}
227
Ben Langmuirc8130a72014-02-20 21:59:23 +0000228IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
229 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
230 return FS;
231}
232
Ben Langmuir740812b2014-06-24 19:37:16 +0000233namespace {
234class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
235 std::string Path;
236 llvm::sys::fs::directory_iterator Iter;
237public:
238 RealFSDirIter(const Twine &_Path, std::error_code &EC)
239 : Path(_Path.str()), Iter(Path, EC) {
240 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
241 llvm::sys::fs::file_status S;
242 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000243 if (!EC)
244 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000245 }
246 }
247
248 std::error_code increment() override {
249 std::error_code EC;
250 Iter.increment(EC);
251 if (EC) {
252 return EC;
253 } else if (Iter == llvm::sys::fs::directory_iterator()) {
254 CurrentEntry = Status();
255 } else {
256 llvm::sys::fs::file_status S;
257 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000258 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000259 }
260 return EC;
261 }
262};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000263}
Ben Langmuir740812b2014-06-24 19:37:16 +0000264
265directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
266 std::error_code &EC) {
267 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
268}
269
Ben Langmuirc8130a72014-02-20 21:59:23 +0000270//===-----------------------------------------------------------------------===/
271// OverlayFileSystem implementation
272//===-----------------------------------------------------------------------===/
273OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000274 FSList.push_back(BaseFS);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000275}
276
277void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
278 FSList.push_back(FS);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000279 // Synchronize added file systems by duplicating the working directory from
280 // the first one in the list.
281 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000282}
283
284ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
285 // FIXME: handle symlinks that cross file systems
286 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
287 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000288 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000289 return Status;
290 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000291 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000292}
293
Benjamin Kramera8857962014-10-26 22:44:13 +0000294ErrorOr<std::unique_ptr<File>>
295OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000296 // FIXME: handle symlinks that cross file systems
297 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000298 auto Result = (*I)->openFileForRead(Path);
299 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
300 return Result;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000301 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000302 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000303}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000304
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000305llvm::ErrorOr<std::string>
306OverlayFileSystem::getCurrentWorkingDirectory() const {
307 // All file systems are synchronized, just take the first working directory.
308 return FSList.front()->getCurrentWorkingDirectory();
309}
310std::error_code
311OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
312 for (auto &FS : FSList)
313 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
314 return EC;
315 return std::error_code();
316}
317
Ben Langmuir740812b2014-06-24 19:37:16 +0000318clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
319
320namespace {
321class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
322 OverlayFileSystem &Overlays;
323 std::string Path;
324 OverlayFileSystem::iterator CurrentFS;
325 directory_iterator CurrentDirIter;
326 llvm::StringSet<> SeenNames;
327
328 std::error_code incrementFS() {
329 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
330 ++CurrentFS;
331 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
332 std::error_code EC;
333 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
334 if (EC && EC != errc::no_such_file_or_directory)
335 return EC;
336 if (CurrentDirIter != directory_iterator())
337 break; // found
338 }
339 return std::error_code();
340 }
341
342 std::error_code incrementDirIter(bool IsFirstTime) {
343 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
344 "incrementing past end");
345 std::error_code EC;
346 if (!IsFirstTime)
347 CurrentDirIter.increment(EC);
348 if (!EC && CurrentDirIter == directory_iterator())
349 EC = incrementFS();
350 return EC;
351 }
352
353 std::error_code incrementImpl(bool IsFirstTime) {
354 while (true) {
355 std::error_code EC = incrementDirIter(IsFirstTime);
356 if (EC || CurrentDirIter == directory_iterator()) {
357 CurrentEntry = Status();
358 return EC;
359 }
360 CurrentEntry = *CurrentDirIter;
361 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
David Blaikie61b86d42014-11-19 02:56:13 +0000362 if (SeenNames.insert(Name).second)
Ben Langmuir740812b2014-06-24 19:37:16 +0000363 return EC; // name not seen before
364 }
365 llvm_unreachable("returned above");
366 }
367
368public:
369 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
370 std::error_code &EC)
371 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
372 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
373 EC = incrementImpl(true);
374 }
375
376 std::error_code increment() override { return incrementImpl(false); }
377};
378} // end anonymous namespace
379
380directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
381 std::error_code &EC) {
382 return directory_iterator(
383 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
384}
385
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000386namespace clang {
387namespace vfs {
388namespace detail {
389
390enum InMemoryNodeKind { IME_File, IME_Directory };
391
392/// The in memory file system is a tree of Nodes. Every node can either be a
393/// file or a directory.
394class InMemoryNode {
395 Status Stat;
396 InMemoryNodeKind Kind;
397
398public:
399 InMemoryNode(Status Stat, InMemoryNodeKind Kind)
400 : Stat(std::move(Stat)), Kind(Kind) {}
401 virtual ~InMemoryNode() {}
402 const Status &getStatus() const { return Stat; }
403 InMemoryNodeKind getKind() const { return Kind; }
404 virtual std::string toString(unsigned Indent) const = 0;
405};
406
407namespace {
408class InMemoryFile : public InMemoryNode {
409 std::unique_ptr<llvm::MemoryBuffer> Buffer;
410
411public:
412 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
413 : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
414
415 llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
416 std::string toString(unsigned Indent) const override {
417 return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
418 }
419 static bool classof(const InMemoryNode *N) {
420 return N->getKind() == IME_File;
421 }
422};
423
424/// Adapt a InMemoryFile for VFS' File interface.
425class InMemoryFileAdaptor : public File {
426 InMemoryFile &Node;
427
428public:
429 explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
430
431 llvm::ErrorOr<Status> status() override { return Node.getStatus(); }
432 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +0000433 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
434 bool IsVolatile) override {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000435 llvm::MemoryBuffer *Buf = Node.getBuffer();
436 return llvm::MemoryBuffer::getMemBuffer(
437 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
438 }
439 std::error_code close() override { return std::error_code(); }
440};
441} // end anonymous namespace
442
443class InMemoryDirectory : public InMemoryNode {
444 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
445
446public:
447 InMemoryDirectory(Status Stat)
448 : InMemoryNode(std::move(Stat), IME_Directory) {}
449 InMemoryNode *getChild(StringRef Name) {
450 auto I = Entries.find(Name);
451 if (I != Entries.end())
452 return I->second.get();
453 return nullptr;
454 }
455 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
456 return Entries.insert(make_pair(Name, std::move(Child)))
457 .first->second.get();
458 }
459
460 typedef decltype(Entries)::const_iterator const_iterator;
461 const_iterator begin() const { return Entries.begin(); }
462 const_iterator end() const { return Entries.end(); }
463
464 std::string toString(unsigned Indent) const override {
465 std::string Result =
466 (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
467 for (const auto &Entry : Entries) {
468 Result += Entry.second->toString(Indent + 2);
469 }
470 return Result;
471 }
472 static bool classof(const InMemoryNode *N) {
473 return N->getKind() == IME_Directory;
474 }
475};
476}
477
478InMemoryFileSystem::InMemoryFileSystem()
479 : Root(new detail::InMemoryDirectory(
480 Status("", getNextVirtualUniqueID(), llvm::sys::TimeValue::MinTime(),
481 0, 0, 0, llvm::sys::fs::file_type::directory_file,
482 llvm::sys::fs::perms::all_all))) {}
483
484InMemoryFileSystem::~InMemoryFileSystem() {}
485
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000486std::string InMemoryFileSystem::toString() const {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000487 return Root->toString(/*Indent=*/0);
488}
489
490void InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
491 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
492 SmallString<128> Path;
493 P.toVector(Path);
494
495 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000496 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000497 assert(!EC);
498 (void)EC;
499
Benjamin Kramerc3741ec2015-10-12 09:22:07 +0000500 FileManager::removeDotPaths(Path, /*RemoveDotDot=*/false);
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000501 if (Path.empty())
502 return;
503
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000504 detail::InMemoryDirectory *Dir = Root.get();
505 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
506 while (true) {
507 StringRef Name = *I;
508 detail::InMemoryNode *Node = Dir->getChild(Name);
509 ++I;
510 if (!Node) {
511 if (I == E) {
512 // End of the path, create a new file.
513 // FIXME: expose the status details in the interface.
Benjamin Kramer1b8dbe32015-10-06 14:45:16 +0000514 Status Stat(P.str(), getNextVirtualUniqueID(),
Benjamin Kramer6b618052015-10-05 14:02:15 +0000515 llvm::sys::TimeValue(ModificationTime, 0), 0, 0,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000516 Buffer->getBufferSize(),
517 llvm::sys::fs::file_type::regular_file,
518 llvm::sys::fs::all_all);
519 Dir->addChild(Name, llvm::make_unique<detail::InMemoryFile>(
520 std::move(Stat), std::move(Buffer)));
521 return;
522 }
523
524 // Create a new directory. Use the path up to here.
525 // FIXME: expose the status details in the interface.
526 Status Stat(
527 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Benjamin Kramer6b618052015-10-05 14:02:15 +0000528 getNextVirtualUniqueID(), llvm::sys::TimeValue(ModificationTime, 0),
529 0, 0, Buffer->getBufferSize(),
530 llvm::sys::fs::file_type::directory_file, llvm::sys::fs::all_all);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000531 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
532 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
533 continue;
534 }
535
536 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node))
537 Dir = NewDir;
538 }
539}
540
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000541void InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
542 llvm::MemoryBuffer *Buffer) {
543 return addFile(P, ModificationTime,
544 llvm::MemoryBuffer::getMemBuffer(
545 Buffer->getBuffer(), Buffer->getBufferIdentifier()));
546}
547
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000548static ErrorOr<detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000549lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
550 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000551 SmallString<128> Path;
552 P.toVector(Path);
553
554 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000555 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000556 assert(!EC);
557 (void)EC;
558
Benjamin Kramerc3741ec2015-10-12 09:22:07 +0000559 FileManager::removeDotPaths(Path, /*RemoveDotDot=*/false);
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000560 if (Path.empty())
561 return Dir;
562
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000563 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
564 while (true) {
565 detail::InMemoryNode *Node = Dir->getChild(*I);
566 ++I;
567 if (!Node)
568 return errc::no_such_file_or_directory;
569
570 // Return the file if it's at the end of the path.
571 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
572 if (I == E)
573 return File;
574 return errc::no_such_file_or_directory;
575 }
576
577 // Traverse directories.
578 Dir = cast<detail::InMemoryDirectory>(Node);
579 if (I == E)
580 return Dir;
581 }
582}
583
584llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000585 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000586 if (Node)
587 return (*Node)->getStatus();
588 return Node.getError();
589}
590
591llvm::ErrorOr<std::unique_ptr<File>>
592InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000593 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000594 if (!Node)
595 return Node.getError();
596
597 // When we have a file provide a heap-allocated wrapper for the memory buffer
598 // to match the ownership semantics for File.
599 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
600 return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
601
602 // FIXME: errc::not_a_file?
603 return make_error_code(llvm::errc::invalid_argument);
604}
605
606namespace {
607/// Adaptor from InMemoryDir::iterator to directory_iterator.
608class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
609 detail::InMemoryDirectory::const_iterator I;
610 detail::InMemoryDirectory::const_iterator E;
611
612public:
613 InMemoryDirIterator() {}
614 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
615 : I(Dir.begin()), E(Dir.end()) {
616 if (I != E)
617 CurrentEntry = I->second->getStatus();
618 }
619
620 std::error_code increment() override {
621 ++I;
622 // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
623 // the rest.
624 CurrentEntry = I != E ? I->second->getStatus() : Status();
625 return std::error_code();
626 }
627};
628} // end anonymous namespace
629
630directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
631 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000632 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000633 if (!Node) {
634 EC = Node.getError();
635 return directory_iterator(std::make_shared<InMemoryDirIterator>());
636 }
637
638 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
639 return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
640
641 EC = make_error_code(llvm::errc::not_a_directory);
642 return directory_iterator(std::make_shared<InMemoryDirIterator>());
643}
644}
645}
646
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000647//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000648// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000649//===-----------------------------------------------------------------------===/
650
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000651namespace {
652
653enum EntryKind {
654 EK_Directory,
655 EK_File
656};
657
658/// \brief A single file or directory in the VFS.
659class Entry {
660 EntryKind Kind;
661 std::string Name;
662
663public:
664 virtual ~Entry();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000665 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
666 StringRef getName() const { return Name; }
667 EntryKind getKind() const { return Kind; }
668};
669
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000670class RedirectingDirectoryEntry : public Entry {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000671 std::vector<std::unique_ptr<Entry>> Contents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000672 Status S;
673
674public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000675 RedirectingDirectoryEntry(StringRef Name,
676 std::vector<std::unique_ptr<Entry>> Contents,
677 Status S)
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000678 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000679 S(std::move(S)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000680 Status getStatus() { return S; }
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000681 typedef decltype(Contents)::iterator iterator;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000682 iterator contents_begin() { return Contents.begin(); }
683 iterator contents_end() { return Contents.end(); }
684 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
685};
686
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000687class RedirectingFileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000688public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000689 enum NameKind {
690 NK_NotSet,
691 NK_External,
692 NK_Virtual
693 };
694private:
695 std::string ExternalContentsPath;
696 NameKind UseName;
697public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000698 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
699 NameKind UseName)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000700 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
701 UseName(UseName) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000702 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Ben Langmuirb59cf672014-02-27 00:25:12 +0000703 /// \brief whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000704 bool useExternalName(bool GlobalUseExternalName) const {
705 return UseName == NK_NotSet ? GlobalUseExternalName
706 : (UseName == NK_External);
707 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000708 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
709};
710
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000711class RedirectingFileSystem;
Ben Langmuir740812b2014-06-24 19:37:16 +0000712
713class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
714 std::string Dir;
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000715 RedirectingFileSystem &FS;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000716 RedirectingDirectoryEntry::iterator Current, End;
717
Ben Langmuir740812b2014-06-24 19:37:16 +0000718public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000719 VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000720 RedirectingDirectoryEntry::iterator Begin,
721 RedirectingDirectoryEntry::iterator End,
722 std::error_code &EC);
Ben Langmuir740812b2014-06-24 19:37:16 +0000723 std::error_code increment() override;
724};
725
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000726/// \brief A virtual file system parsed from a YAML file.
727///
728/// Currently, this class allows creating virtual directories and mapping
729/// virtual file paths to existing external files, available in \c ExternalFS.
730///
731/// The basic structure of the parsed file is:
732/// \verbatim
733/// {
734/// 'version': <version number>,
735/// <optional configuration>
736/// 'roots': [
737/// <directory entries>
738/// ]
739/// }
740/// \endverbatim
741///
742/// All configuration options are optional.
743/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000744/// 'use-external-names': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000745///
746/// Virtual directories are represented as
747/// \verbatim
748/// {
749/// 'type': 'directory',
750/// 'name': <string>,
751/// 'contents': [ <file or directory entries> ]
752/// }
753/// \endverbatim
754///
755/// The default attributes for virtual directories are:
756/// \verbatim
757/// MTime = now() when created
758/// Perms = 0777
759/// User = Group = 0
760/// Size = 0
761/// UniqueID = unspecified unique value
762/// \endverbatim
763///
764/// Re-mapped files are represented as
765/// \verbatim
766/// {
767/// 'type': 'file',
768/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000769/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000770/// 'external-contents': <path to external file>)
771/// }
772/// \endverbatim
773///
774/// and inherit their attributes from the external contents.
775///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000776/// In both cases, the 'name' field may contain multiple path components (e.g.
777/// /path/to/file). However, any directory that contains more than one child
778/// must be uniquely represented by a directory entry.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000779class RedirectingFileSystem : public vfs::FileSystem {
780 /// The root(s) of the virtual file system.
781 std::vector<std::unique_ptr<Entry>> Roots;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000782 /// \brief The file system to use for external references.
783 IntrusiveRefCntPtr<FileSystem> ExternalFS;
784
785 /// @name Configuration
786 /// @{
787
788 /// \brief Whether to perform case-sensitive comparisons.
789 ///
790 /// Currently, case-insensitive matching only works correctly with ASCII.
Ben Langmuirb59cf672014-02-27 00:25:12 +0000791 bool CaseSensitive;
792
793 /// \brief Whether to use to use the value of 'external-contents' for the
794 /// names of files. This global value is overridable on a per-file basis.
795 bool UseExternalNames;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000796 /// @}
797
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000798 friend class RedirectingFileSystemParser;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000799
800private:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000801 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000802 : ExternalFS(ExternalFS), CaseSensitive(true), UseExternalNames(true) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000803
804 /// \brief Looks up \p Path in \c Roots.
805 ErrorOr<Entry *> lookupPath(const Twine &Path);
806
807 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
808 /// recursing into the contents of \p From if it is a directory.
809 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
810 sys::path::const_iterator End, Entry *From);
811
Ben Langmuir740812b2014-06-24 19:37:16 +0000812 /// \brief Get the status of a given an \c Entry.
813 ErrorOr<Status> status(const Twine &Path, Entry *E);
814
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000815public:
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000816 /// \brief Parses \p Buffer, which is expected to be in YAML format and
817 /// returns a virtual file system representing its contents.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000818 static RedirectingFileSystem *
819 create(std::unique_ptr<MemoryBuffer> Buffer,
820 SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext,
821 IntrusiveRefCntPtr<FileSystem> ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000822
Craig Toppera798a9d2014-03-02 09:32:10 +0000823 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000824 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000825
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000826 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
827 return ExternalFS->getCurrentWorkingDirectory();
828 }
829 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
830 return ExternalFS->setCurrentWorkingDirectory(Path);
831 }
832
Ben Langmuir740812b2014-06-24 19:37:16 +0000833 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
834 ErrorOr<Entry *> E = lookupPath(Dir);
835 if (!E) {
836 EC = E.getError();
837 return directory_iterator();
838 }
839 ErrorOr<Status> S = status(Dir, *E);
840 if (!S) {
841 EC = S.getError();
842 return directory_iterator();
843 }
844 if (!S->isDirectory()) {
845 EC = std::error_code(static_cast<int>(errc::not_a_directory),
846 std::system_category());
847 return directory_iterator();
848 }
849
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000850 auto *D = cast<RedirectingDirectoryEntry>(*E);
Ben Langmuir740812b2014-06-24 19:37:16 +0000851 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
852 *this, D->contents_begin(), D->contents_end(), EC));
853 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000854};
855
856/// \brief A helper class to hold the common YAML parsing state.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000857class RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000858 yaml::Stream &Stream;
859
860 void error(yaml::Node *N, const Twine &Msg) {
861 Stream.printError(N, Msg);
862 }
863
864 // false on error
865 bool parseScalarString(yaml::Node *N, StringRef &Result,
866 SmallVectorImpl<char> &Storage) {
867 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
868 if (!S) {
869 error(N, "expected string");
870 return false;
871 }
872 Result = S->getValue(Storage);
873 return true;
874 }
875
876 // false on error
877 bool parseScalarBool(yaml::Node *N, bool &Result) {
878 SmallString<5> Storage;
879 StringRef Value;
880 if (!parseScalarString(N, Value, Storage))
881 return false;
882
883 if (Value.equals_lower("true") || Value.equals_lower("on") ||
884 Value.equals_lower("yes") || Value == "1") {
885 Result = true;
886 return true;
887 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
888 Value.equals_lower("no") || Value == "0") {
889 Result = false;
890 return true;
891 }
892
893 error(N, "expected boolean value");
894 return false;
895 }
896
897 struct KeyStatus {
898 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
899 bool Required;
900 bool Seen;
901 };
902 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
903
904 // false on error
905 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
906 DenseMap<StringRef, KeyStatus> &Keys) {
907 if (!Keys.count(Key)) {
908 error(KeyNode, "unknown key");
909 return false;
910 }
911 KeyStatus &S = Keys[Key];
912 if (S.Seen) {
913 error(KeyNode, Twine("duplicate key '") + Key + "'");
914 return false;
915 }
916 S.Seen = true;
917 return true;
918 }
919
920 // false on error
921 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
922 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
923 E = Keys.end();
924 I != E; ++I) {
925 if (I->second.Required && !I->second.Seen) {
926 error(Obj, Twine("missing key '") + I->first + "'");
927 return false;
928 }
929 }
930 return true;
931 }
932
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000933 std::unique_ptr<Entry> parseEntry(yaml::Node *N) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000934 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
935 if (!M) {
936 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +0000937 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000938 }
939
940 KeyStatusPair Fields[] = {
941 KeyStatusPair("name", true),
942 KeyStatusPair("type", true),
943 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +0000944 KeyStatusPair("external-contents", false),
945 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000946 };
947
948 DenseMap<StringRef, KeyStatus> Keys(
949 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
950
951 bool HasContents = false; // external or otherwise
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000952 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000953 std::string ExternalContentsPath;
954 std::string Name;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000955 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000956 EntryKind Kind;
957
958 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
959 ++I) {
960 StringRef Key;
961 // Reuse the buffer for key and value, since we don't look at key after
962 // parsing value.
963 SmallString<256> Buffer;
964 if (!parseScalarString(I->getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000965 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000966
967 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +0000968 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000969
970 StringRef Value;
971 if (Key == "name") {
972 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000973 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000974 Name = Value;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000975 } else if (Key == "type") {
976 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000977 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000978 if (Value == "file")
979 Kind = EK_File;
980 else if (Value == "directory")
981 Kind = EK_Directory;
982 else {
983 error(I->getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +0000984 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000985 }
986 } else if (Key == "contents") {
987 if (HasContents) {
988 error(I->getKey(),
989 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +0000990 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000991 }
992 HasContents = true;
993 yaml::SequenceNode *Contents =
994 dyn_cast<yaml::SequenceNode>(I->getValue());
995 if (!Contents) {
996 // FIXME: this is only for directories, what about files?
997 error(I->getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +0000998 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000999 }
1000
1001 for (yaml::SequenceNode::iterator I = Contents->begin(),
1002 E = Contents->end();
1003 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001004 if (std::unique_ptr<Entry> E = parseEntry(&*I))
1005 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001006 else
Craig Topperf1186c52014-05-08 06:41:40 +00001007 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001008 }
1009 } else if (Key == "external-contents") {
1010 if (HasContents) {
1011 error(I->getKey(),
1012 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001013 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001014 }
1015 HasContents = true;
1016 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001017 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001018 ExternalContentsPath = Value;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001019 } else if (Key == "use-external-name") {
1020 bool Val;
1021 if (!parseScalarBool(I->getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001022 return nullptr;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001023 UseExternalName = Val ? RedirectingFileEntry::NK_External
1024 : RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001025 } else {
1026 llvm_unreachable("key missing from Keys");
1027 }
1028 }
1029
1030 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001031 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001032
1033 // check for missing keys
1034 if (!HasContents) {
1035 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001036 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001037 }
1038 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001039 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001040
Ben Langmuirb59cf672014-02-27 00:25:12 +00001041 // check invalid configuration
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001042 if (Kind == EK_Directory &&
1043 UseExternalName != RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001044 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001045 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001046 }
1047
Ben Langmuir93853232014-03-05 21:32:20 +00001048 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001049 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001050 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1051 while (Trimmed.size() > RootPathLen &&
1052 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001053 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1054 // Get the last component
1055 StringRef LastComponent = sys::path::filename(Trimmed);
1056
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001057 std::unique_ptr<Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001058 switch (Kind) {
1059 case EK_File:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001060 Result = llvm::make_unique<RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001061 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001062 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001063 case EK_Directory:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001064 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001065 LastComponent, std::move(EntryArrayContents),
1066 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1067 file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001068 break;
1069 }
1070
1071 StringRef Parent = sys::path::parent_path(Trimmed);
1072 if (Parent.empty())
1073 return Result;
1074
1075 // if 'name' contains multiple components, create implicit directory entries
1076 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1077 E = sys::path::rend(Parent);
1078 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001079 std::vector<std::unique_ptr<Entry>> Entries;
1080 Entries.push_back(std::move(Result));
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001081 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001082 *I, std::move(Entries),
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001083 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1084 file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001085 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001086 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001087 }
1088
1089public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001090 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001091
1092 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001093 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001094 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
1095 if (!Top) {
1096 error(Root, "expected mapping node");
1097 return false;
1098 }
1099
1100 KeyStatusPair Fields[] = {
1101 KeyStatusPair("version", true),
1102 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001103 KeyStatusPair("use-external-names", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001104 KeyStatusPair("roots", true),
1105 };
1106
1107 DenseMap<StringRef, KeyStatus> Keys(
1108 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
1109
1110 // Parse configuration and 'roots'
1111 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
1112 ++I) {
1113 SmallString<10> KeyBuffer;
1114 StringRef Key;
1115 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
1116 return false;
1117
1118 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1119 return false;
1120
1121 if (Key == "roots") {
1122 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
1123 if (!Roots) {
1124 error(I->getValue(), "expected array");
1125 return false;
1126 }
1127
1128 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
1129 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001130 if (std::unique_ptr<Entry> E = parseEntry(&*I))
1131 FS->Roots.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001132 else
1133 return false;
1134 }
1135 } else if (Key == "version") {
1136 StringRef VersionString;
1137 SmallString<4> Storage;
1138 if (!parseScalarString(I->getValue(), VersionString, Storage))
1139 return false;
1140 int Version;
1141 if (VersionString.getAsInteger<int>(10, Version)) {
1142 error(I->getValue(), "expected integer");
1143 return false;
1144 }
1145 if (Version < 0) {
1146 error(I->getValue(), "invalid version number");
1147 return false;
1148 }
1149 if (Version != 0) {
1150 error(I->getValue(), "version mismatch, expected 0");
1151 return false;
1152 }
1153 } else if (Key == "case-sensitive") {
1154 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
1155 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001156 } else if (Key == "use-external-names") {
1157 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
1158 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001159 } else {
1160 llvm_unreachable("key missing from Keys");
1161 }
1162 }
1163
1164 if (Stream.failed())
1165 return false;
1166
1167 if (!checkMissingKeys(Top, Keys))
1168 return false;
1169 return true;
1170 }
1171};
1172} // end of anonymous namespace
1173
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001174Entry::~Entry() = default;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001175
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001176RedirectingFileSystem *RedirectingFileSystem::create(
1177 std::unique_ptr<MemoryBuffer> Buffer, SourceMgr::DiagHandlerTy DiagHandler,
1178 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001179
1180 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001181 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001182
Ben Langmuir97882e72014-02-24 20:56:37 +00001183 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001184 yaml::document_iterator DI = Stream.begin();
1185 yaml::Node *Root = DI->getRoot();
1186 if (DI == Stream.end() || !Root) {
1187 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001188 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001189 }
1190
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001191 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001192
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001193 std::unique_ptr<RedirectingFileSystem> FS(
1194 new RedirectingFileSystem(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001195 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001196 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001197
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001198 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001199}
1200
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001201ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001202 SmallString<256> Path;
1203 Path_.toVector(Path);
1204
1205 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001206 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001207 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001208
1209 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001210 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001211
1212 sys::path::const_iterator Start = sys::path::begin(Path);
1213 sys::path::const_iterator End = sys::path::end(Path);
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001214 for (const std::unique_ptr<Entry> &Root : Roots) {
1215 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001216 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001217 return Result;
1218 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001219 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001220}
1221
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001222ErrorOr<Entry *>
1223RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1224 sys::path::const_iterator End, Entry *From) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001225 if (Start->equals("."))
1226 ++Start;
1227
1228 // FIXME: handle ..
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001229 if (CaseSensitive ? !Start->equals(From->getName())
1230 : !Start->equals_lower(From->getName()))
1231 // failure to match
Rafael Espindola71de0b62014-06-13 17:20:50 +00001232 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001233
1234 ++Start;
1235
1236 if (Start == End) {
1237 // Match!
1238 return From;
1239 }
1240
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001241 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001242 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001243 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001244
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001245 for (const std::unique_ptr<Entry> &DirEntry :
1246 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1247 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001248 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001249 return Result;
1250 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001251 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001252}
1253
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001254ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001255 assert(E != nullptr);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001256 std::string PathStr(Path.str());
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001257 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001258 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001259 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuird066d4c2014-02-28 21:16:07 +00001260 if (S && !F->useExternalName(UseExternalNames))
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001261 *S = Status::copyWithNewName(*S, PathStr);
Ben Langmuir5de00f32014-05-23 18:15:47 +00001262 if (S)
1263 S->IsVFSMapped = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001264 return S;
1265 } else { // directory
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001266 auto *DE = cast<RedirectingDirectoryEntry>(E);
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001267 return Status::copyWithNewName(DE->getStatus(), PathStr);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001268 }
1269}
1270
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001271ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001272 ErrorOr<Entry *> Result = lookupPath(Path);
1273 if (!Result)
1274 return Result.getError();
1275 return status(Path, *Result);
1276}
1277
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001278namespace {
1279/// Provide a file wrapper that returns the external name when asked.
1280class NamedFileAdaptor : public File {
1281 std::unique_ptr<File> InnerFile;
1282 std::string NewName;
1283
1284public:
1285 NamedFileAdaptor(std::unique_ptr<File> InnerFile, std::string NewName)
1286 : InnerFile(std::move(InnerFile)), NewName(std::move(NewName)) {}
1287
1288 llvm::ErrorOr<Status> status() override {
1289 auto InnerStatus = InnerFile->status();
1290 if (InnerStatus)
1291 return Status::copyWithNewName(*InnerStatus, NewName);
1292 return InnerStatus.getError();
1293 }
1294 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +00001295 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1296 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001297 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1298 IsVolatile);
1299 }
1300 std::error_code close() override { return InnerFile->close(); }
1301};
1302} // end anonymous namespace
1303
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001304ErrorOr<std::unique_ptr<File>>
1305RedirectingFileSystem::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001306 ErrorOr<Entry *> E = lookupPath(Path);
1307 if (!E)
1308 return E.getError();
1309
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001310 auto *F = dyn_cast<RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001311 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001312 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001313
Benjamin Kramera8857962014-10-26 22:44:13 +00001314 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1315 if (!Result)
1316 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001317
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001318 if (!F->useExternalName(UseExternalNames))
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001319 return std::unique_ptr<File>(
1320 new NamedFileAdaptor(std::move(*Result), Path.str()));
Ben Langmuird066d4c2014-02-28 21:16:07 +00001321
Benjamin Kramera8857962014-10-26 22:44:13 +00001322 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001323}
1324
1325IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001326vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1327 SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001328 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001329 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
1330 DiagContext, ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001331}
1332
1333UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001334 static std::atomic<unsigned> UID;
1335 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001336 // The following assumes that uint64_t max will never collide with a real
1337 // dev_t value from the OS.
1338 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1339}
Justin Bogner9c785292014-05-20 21:43:27 +00001340
1341#ifndef NDEBUG
1342static bool pathHasTraversal(StringRef Path) {
1343 using namespace llvm::sys;
1344 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
1345 if (Comp == "." || Comp == "..")
1346 return true;
1347 return false;
1348}
1349#endif
1350
1351void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1352 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1353 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1354 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1355 Mappings.emplace_back(VirtualPath, RealPath);
1356}
1357
Justin Bogner44fa450342014-05-21 22:46:51 +00001358namespace {
1359class JSONWriter {
1360 llvm::raw_ostream &OS;
1361 SmallVector<StringRef, 16> DirStack;
1362 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
1363 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1364 bool containedIn(StringRef Parent, StringRef Path);
1365 StringRef containedPart(StringRef Parent, StringRef Path);
1366 void startDirectory(StringRef Path);
1367 void endDirectory();
1368 void writeEntry(StringRef VPath, StringRef RPath);
1369
1370public:
1371 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
1372 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive);
1373};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001374}
Justin Bogner9c785292014-05-20 21:43:27 +00001375
Justin Bogner44fa450342014-05-21 22:46:51 +00001376bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001377 using namespace llvm::sys;
1378 // Compare each path component.
1379 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1380 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1381 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1382 if (*IParent != *IChild)
1383 return false;
1384 }
1385 // Have we exhausted the parent path?
1386 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001387}
1388
Justin Bogner44fa450342014-05-21 22:46:51 +00001389StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1390 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001391 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001392 return Path.slice(Parent.size() + 1, StringRef::npos);
1393}
1394
Justin Bogner44fa450342014-05-21 22:46:51 +00001395void JSONWriter::startDirectory(StringRef Path) {
1396 StringRef Name =
1397 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1398 DirStack.push_back(Path);
1399 unsigned Indent = getDirIndent();
1400 OS.indent(Indent) << "{\n";
1401 OS.indent(Indent + 2) << "'type': 'directory',\n";
1402 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1403 OS.indent(Indent + 2) << "'contents': [\n";
1404}
1405
1406void JSONWriter::endDirectory() {
1407 unsigned Indent = getDirIndent();
1408 OS.indent(Indent + 2) << "]\n";
1409 OS.indent(Indent) << "}";
1410
1411 DirStack.pop_back();
1412}
1413
1414void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1415 unsigned Indent = getFileIndent();
1416 OS.indent(Indent) << "{\n";
1417 OS.indent(Indent + 2) << "'type': 'file',\n";
1418 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1419 OS.indent(Indent + 2) << "'external-contents': \""
1420 << llvm::yaml::escape(RPath) << "\"\n";
1421 OS.indent(Indent) << "}";
1422}
1423
1424void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
1425 Optional<bool> IsCaseSensitive) {
1426 using namespace llvm::sys;
1427
1428 OS << "{\n"
1429 " 'version': 0,\n";
1430 if (IsCaseSensitive.hasValue())
1431 OS << " 'case-sensitive': '"
1432 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
1433 OS << " 'roots': [\n";
1434
Justin Bogner73466402014-07-15 01:24:35 +00001435 if (!Entries.empty()) {
1436 const YAMLVFSEntry &Entry = Entries.front();
1437 startDirectory(path::parent_path(Entry.VPath));
Justin Bogner44fa450342014-05-21 22:46:51 +00001438 writeEntry(path::filename(Entry.VPath), Entry.RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001439
Justin Bogner73466402014-07-15 01:24:35 +00001440 for (const auto &Entry : Entries.slice(1)) {
1441 StringRef Dir = path::parent_path(Entry.VPath);
1442 if (Dir == DirStack.back())
1443 OS << ",\n";
1444 else {
1445 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1446 OS << "\n";
1447 endDirectory();
1448 }
1449 OS << ",\n";
1450 startDirectory(Dir);
1451 }
1452 writeEntry(path::filename(Entry.VPath), Entry.RPath);
1453 }
1454
1455 while (!DirStack.empty()) {
1456 OS << "\n";
1457 endDirectory();
1458 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001459 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001460 }
1461
Justin Bogner73466402014-07-15 01:24:35 +00001462 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001463 << "}\n";
1464}
1465
Justin Bogner9c785292014-05-20 21:43:27 +00001466void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1467 std::sort(Mappings.begin(), Mappings.end(),
Justin Bogner44fa450342014-05-21 22:46:51 +00001468 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001469 return LHS.VPath < RHS.VPath;
1470 });
1471
Justin Bogner44fa450342014-05-21 22:46:51 +00001472 JSONWriter(OS).write(Mappings, IsCaseSensitive);
Justin Bogner9c785292014-05-20 21:43:27 +00001473}
Ben Langmuir740812b2014-06-24 19:37:16 +00001474
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001475VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1476 const Twine &_Path, RedirectingFileSystem &FS,
1477 RedirectingDirectoryEntry::iterator Begin,
1478 RedirectingDirectoryEntry::iterator End, std::error_code &EC)
Ben Langmuir740812b2014-06-24 19:37:16 +00001479 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
1480 if (Current != End) {
1481 SmallString<128> PathStr(Dir);
1482 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001483 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001484 if (S)
1485 CurrentEntry = *S;
1486 else
1487 EC = S.getError();
1488 }
1489}
1490
1491std::error_code VFSFromYamlDirIterImpl::increment() {
1492 assert(Current != End && "cannot iterate past end");
1493 if (++Current != End) {
1494 SmallString<128> PathStr(Dir);
1495 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001496 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001497 if (!S)
1498 return S.getError();
1499 CurrentEntry = *S;
1500 } else {
1501 CurrentEntry = Status();
1502 }
1503 return std::error_code();
1504}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001505
1506vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1507 const Twine &Path,
1508 std::error_code &EC)
1509 : FS(&FS_) {
1510 directory_iterator I = FS->dir_begin(Path, EC);
1511 if (!EC && I != directory_iterator()) {
1512 State = std::make_shared<IterState>();
1513 State->push(I);
1514 }
1515}
1516
1517vfs::recursive_directory_iterator &
1518recursive_directory_iterator::increment(std::error_code &EC) {
1519 assert(FS && State && !State->empty() && "incrementing past end");
1520 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1521 vfs::directory_iterator End;
1522 if (State->top()->isDirectory()) {
1523 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
1524 if (EC)
1525 return *this;
1526 if (I != End) {
1527 State->push(I);
1528 return *this;
1529 }
1530 }
1531
1532 while (!State->empty() && State->top().increment(EC) == End)
1533 State->pop();
1534
1535 if (State->empty())
1536 State.reset(); // end iterator
1537
1538 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001539}