blob: a20132b3de892cd4fa43acf4c136948e30774f0a [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"
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
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000087File::~File() {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000088
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000089FileSystem::~FileSystem() {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000090
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
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000318clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
Ben Langmuir740812b2014-06-24 19:37:16 +0000319
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) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000401 virtual ~InMemoryNode() {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000402 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
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000478InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000479 : Root(new detail::InMemoryDirectory(
480 Status("", getNextVirtualUniqueID(), llvm::sys::TimeValue::MinTime(),
481 0, 0, 0, llvm::sys::fs::file_type::directory_file,
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000482 llvm::sys::fs::perms::all_all))),
483 UseNormalizedPaths(UseNormalizedPaths) {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000484
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000485InMemoryFileSystem::~InMemoryFileSystem() {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000486
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000487std::string InMemoryFileSystem::toString() const {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000488 return Root->toString(/*Indent=*/0);
489}
490
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000491bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000492 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
493 SmallString<128> Path;
494 P.toVector(Path);
495
496 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000497 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000498 assert(!EC);
499 (void)EC;
500
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000501 if (useNormalizedPaths())
502 FileManager::removeDotPaths(Path, /*RemoveDotDot=*/true);
503
504 if (Path.empty())
505 return false;
506
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000507 detail::InMemoryDirectory *Dir = Root.get();
508 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
509 while (true) {
510 StringRef Name = *I;
511 detail::InMemoryNode *Node = Dir->getChild(Name);
512 ++I;
513 if (!Node) {
514 if (I == E) {
515 // End of the path, create a new file.
516 // FIXME: expose the status details in the interface.
Benjamin Kramer1b8dbe32015-10-06 14:45:16 +0000517 Status Stat(P.str(), getNextVirtualUniqueID(),
Benjamin Kramer6b618052015-10-05 14:02:15 +0000518 llvm::sys::TimeValue(ModificationTime, 0), 0, 0,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000519 Buffer->getBufferSize(),
520 llvm::sys::fs::file_type::regular_file,
521 llvm::sys::fs::all_all);
522 Dir->addChild(Name, llvm::make_unique<detail::InMemoryFile>(
523 std::move(Stat), std::move(Buffer)));
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000524 return true;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000525 }
526
527 // Create a new directory. Use the path up to here.
528 // FIXME: expose the status details in the interface.
529 Status Stat(
530 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Benjamin Kramer6b618052015-10-05 14:02:15 +0000531 getNextVirtualUniqueID(), llvm::sys::TimeValue(ModificationTime, 0),
532 0, 0, Buffer->getBufferSize(),
533 llvm::sys::fs::file_type::directory_file, llvm::sys::fs::all_all);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000534 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
535 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
536 continue;
537 }
538
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000539 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000540 Dir = NewDir;
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000541 } else {
542 assert(isa<detail::InMemoryFile>(Node) &&
543 "Must be either file or directory!");
544
545 // Trying to insert a directory in place of a file.
546 if (I != E)
547 return false;
548
549 // Return false only if the new file is different from the existing one.
550 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
551 Buffer->getBuffer();
552 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000553 }
554}
555
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000556bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000557 llvm::MemoryBuffer *Buffer) {
558 return addFile(P, ModificationTime,
559 llvm::MemoryBuffer::getMemBuffer(
560 Buffer->getBuffer(), Buffer->getBufferIdentifier()));
561}
562
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000563static ErrorOr<detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000564lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
565 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000566 SmallString<128> Path;
567 P.toVector(Path);
568
569 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000570 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000571 assert(!EC);
572 (void)EC;
573
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000574 if (FS.useNormalizedPaths())
575 FileManager::removeDotPaths(Path, /*RemoveDotDot=*/true);
Benjamin Kramer4ad1c432015-10-12 13:30:38 +0000576
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000577 if (Path.empty())
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000578 return Dir;
579
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000580 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000581 while (true) {
582 detail::InMemoryNode *Node = Dir->getChild(*I);
583 ++I;
584 if (!Node)
585 return errc::no_such_file_or_directory;
586
587 // Return the file if it's at the end of the path.
588 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
589 if (I == E)
590 return File;
591 return errc::no_such_file_or_directory;
592 }
593
594 // Traverse directories.
595 Dir = cast<detail::InMemoryDirectory>(Node);
596 if (I == E)
597 return Dir;
598 }
599}
600
601llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000602 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000603 if (Node)
604 return (*Node)->getStatus();
605 return Node.getError();
606}
607
608llvm::ErrorOr<std::unique_ptr<File>>
609InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000610 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000611 if (!Node)
612 return Node.getError();
613
614 // When we have a file provide a heap-allocated wrapper for the memory buffer
615 // to match the ownership semantics for File.
616 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
617 return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
618
619 // FIXME: errc::not_a_file?
620 return make_error_code(llvm::errc::invalid_argument);
621}
622
623namespace {
624/// Adaptor from InMemoryDir::iterator to directory_iterator.
625class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
626 detail::InMemoryDirectory::const_iterator I;
627 detail::InMemoryDirectory::const_iterator E;
628
629public:
630 InMemoryDirIterator() {}
631 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
632 : I(Dir.begin()), E(Dir.end()) {
633 if (I != E)
634 CurrentEntry = I->second->getStatus();
635 }
636
637 std::error_code increment() override {
638 ++I;
639 // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
640 // the rest.
641 CurrentEntry = I != E ? I->second->getStatus() : Status();
642 return std::error_code();
643 }
644};
645} // end anonymous namespace
646
647directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
648 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000649 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000650 if (!Node) {
651 EC = Node.getError();
652 return directory_iterator(std::make_shared<InMemoryDirIterator>());
653 }
654
655 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
656 return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
657
658 EC = make_error_code(llvm::errc::not_a_directory);
659 return directory_iterator(std::make_shared<InMemoryDirIterator>());
660}
661}
662}
663
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000664//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000665// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000666//===-----------------------------------------------------------------------===/
667
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000668namespace {
669
670enum EntryKind {
671 EK_Directory,
672 EK_File
673};
674
675/// \brief A single file or directory in the VFS.
676class Entry {
677 EntryKind Kind;
678 std::string Name;
679
680public:
681 virtual ~Entry();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000682 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
683 StringRef getName() const { return Name; }
684 EntryKind getKind() const { return Kind; }
685};
686
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000687class RedirectingDirectoryEntry : public Entry {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000688 std::vector<std::unique_ptr<Entry>> Contents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000689 Status S;
690
691public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000692 RedirectingDirectoryEntry(StringRef Name,
693 std::vector<std::unique_ptr<Entry>> Contents,
694 Status S)
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000695 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000696 S(std::move(S)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000697 Status getStatus() { return S; }
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000698 typedef decltype(Contents)::iterator iterator;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000699 iterator contents_begin() { return Contents.begin(); }
700 iterator contents_end() { return Contents.end(); }
701 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
702};
703
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000704class RedirectingFileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000705public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000706 enum NameKind {
707 NK_NotSet,
708 NK_External,
709 NK_Virtual
710 };
711private:
712 std::string ExternalContentsPath;
713 NameKind UseName;
714public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000715 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
716 NameKind UseName)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000717 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
718 UseName(UseName) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000719 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Ben Langmuirb59cf672014-02-27 00:25:12 +0000720 /// \brief whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000721 bool useExternalName(bool GlobalUseExternalName) const {
722 return UseName == NK_NotSet ? GlobalUseExternalName
723 : (UseName == NK_External);
724 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000725 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
726};
727
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000728class RedirectingFileSystem;
Ben Langmuir740812b2014-06-24 19:37:16 +0000729
730class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
731 std::string Dir;
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000732 RedirectingFileSystem &FS;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000733 RedirectingDirectoryEntry::iterator Current, End;
734
Ben Langmuir740812b2014-06-24 19:37:16 +0000735public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000736 VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000737 RedirectingDirectoryEntry::iterator Begin,
738 RedirectingDirectoryEntry::iterator End,
739 std::error_code &EC);
Ben Langmuir740812b2014-06-24 19:37:16 +0000740 std::error_code increment() override;
741};
742
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000743/// \brief A virtual file system parsed from a YAML file.
744///
745/// Currently, this class allows creating virtual directories and mapping
746/// virtual file paths to existing external files, available in \c ExternalFS.
747///
748/// The basic structure of the parsed file is:
749/// \verbatim
750/// {
751/// 'version': <version number>,
752/// <optional configuration>
753/// 'roots': [
754/// <directory entries>
755/// ]
756/// }
757/// \endverbatim
758///
759/// All configuration options are optional.
760/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000761/// 'use-external-names': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000762///
763/// Virtual directories are represented as
764/// \verbatim
765/// {
766/// 'type': 'directory',
767/// 'name': <string>,
768/// 'contents': [ <file or directory entries> ]
769/// }
770/// \endverbatim
771///
772/// The default attributes for virtual directories are:
773/// \verbatim
774/// MTime = now() when created
775/// Perms = 0777
776/// User = Group = 0
777/// Size = 0
778/// UniqueID = unspecified unique value
779/// \endverbatim
780///
781/// Re-mapped files are represented as
782/// \verbatim
783/// {
784/// 'type': 'file',
785/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000786/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000787/// 'external-contents': <path to external file>)
788/// }
789/// \endverbatim
790///
791/// and inherit their attributes from the external contents.
792///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000793/// In both cases, the 'name' field may contain multiple path components (e.g.
794/// /path/to/file). However, any directory that contains more than one child
795/// must be uniquely represented by a directory entry.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000796class RedirectingFileSystem : public vfs::FileSystem {
797 /// The root(s) of the virtual file system.
798 std::vector<std::unique_ptr<Entry>> Roots;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000799 /// \brief The file system to use for external references.
800 IntrusiveRefCntPtr<FileSystem> ExternalFS;
801
802 /// @name Configuration
803 /// @{
804
805 /// \brief Whether to perform case-sensitive comparisons.
806 ///
807 /// Currently, case-insensitive matching only works correctly with ASCII.
Ben Langmuirb59cf672014-02-27 00:25:12 +0000808 bool CaseSensitive;
809
810 /// \brief Whether to use to use the value of 'external-contents' for the
811 /// names of files. This global value is overridable on a per-file basis.
812 bool UseExternalNames;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000813 /// @}
814
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000815 friend class RedirectingFileSystemParser;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000816
817private:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000818 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000819 : ExternalFS(ExternalFS), CaseSensitive(true), UseExternalNames(true) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000820
821 /// \brief Looks up \p Path in \c Roots.
822 ErrorOr<Entry *> lookupPath(const Twine &Path);
823
824 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
825 /// recursing into the contents of \p From if it is a directory.
826 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
827 sys::path::const_iterator End, Entry *From);
828
Ben Langmuir740812b2014-06-24 19:37:16 +0000829 /// \brief Get the status of a given an \c Entry.
830 ErrorOr<Status> status(const Twine &Path, Entry *E);
831
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000832public:
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000833 /// \brief Parses \p Buffer, which is expected to be in YAML format and
834 /// returns a virtual file system representing its contents.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000835 static RedirectingFileSystem *
836 create(std::unique_ptr<MemoryBuffer> Buffer,
837 SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext,
838 IntrusiveRefCntPtr<FileSystem> ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000839
Craig Toppera798a9d2014-03-02 09:32:10 +0000840 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000841 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000842
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000843 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
844 return ExternalFS->getCurrentWorkingDirectory();
845 }
846 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
847 return ExternalFS->setCurrentWorkingDirectory(Path);
848 }
849
Ben Langmuir740812b2014-06-24 19:37:16 +0000850 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
851 ErrorOr<Entry *> E = lookupPath(Dir);
852 if (!E) {
853 EC = E.getError();
854 return directory_iterator();
855 }
856 ErrorOr<Status> S = status(Dir, *E);
857 if (!S) {
858 EC = S.getError();
859 return directory_iterator();
860 }
861 if (!S->isDirectory()) {
862 EC = std::error_code(static_cast<int>(errc::not_a_directory),
863 std::system_category());
864 return directory_iterator();
865 }
866
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000867 auto *D = cast<RedirectingDirectoryEntry>(*E);
Ben Langmuir740812b2014-06-24 19:37:16 +0000868 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
869 *this, D->contents_begin(), D->contents_end(), EC));
870 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000871};
872
873/// \brief A helper class to hold the common YAML parsing state.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000874class RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000875 yaml::Stream &Stream;
876
877 void error(yaml::Node *N, const Twine &Msg) {
878 Stream.printError(N, Msg);
879 }
880
881 // false on error
882 bool parseScalarString(yaml::Node *N, StringRef &Result,
883 SmallVectorImpl<char> &Storage) {
884 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
885 if (!S) {
886 error(N, "expected string");
887 return false;
888 }
889 Result = S->getValue(Storage);
890 return true;
891 }
892
893 // false on error
894 bool parseScalarBool(yaml::Node *N, bool &Result) {
895 SmallString<5> Storage;
896 StringRef Value;
897 if (!parseScalarString(N, Value, Storage))
898 return false;
899
900 if (Value.equals_lower("true") || Value.equals_lower("on") ||
901 Value.equals_lower("yes") || Value == "1") {
902 Result = true;
903 return true;
904 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
905 Value.equals_lower("no") || Value == "0") {
906 Result = false;
907 return true;
908 }
909
910 error(N, "expected boolean value");
911 return false;
912 }
913
914 struct KeyStatus {
915 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
916 bool Required;
917 bool Seen;
918 };
919 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
920
921 // false on error
922 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
923 DenseMap<StringRef, KeyStatus> &Keys) {
924 if (!Keys.count(Key)) {
925 error(KeyNode, "unknown key");
926 return false;
927 }
928 KeyStatus &S = Keys[Key];
929 if (S.Seen) {
930 error(KeyNode, Twine("duplicate key '") + Key + "'");
931 return false;
932 }
933 S.Seen = true;
934 return true;
935 }
936
937 // false on error
938 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
939 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
940 E = Keys.end();
941 I != E; ++I) {
942 if (I->second.Required && !I->second.Seen) {
943 error(Obj, Twine("missing key '") + I->first + "'");
944 return false;
945 }
946 }
947 return true;
948 }
949
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000950 std::unique_ptr<Entry> parseEntry(yaml::Node *N) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000951 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
952 if (!M) {
953 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +0000954 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000955 }
956
957 KeyStatusPair Fields[] = {
958 KeyStatusPair("name", true),
959 KeyStatusPair("type", true),
960 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +0000961 KeyStatusPair("external-contents", false),
962 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000963 };
964
965 DenseMap<StringRef, KeyStatus> Keys(
966 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
967
968 bool HasContents = false; // external or otherwise
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000969 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000970 std::string ExternalContentsPath;
971 std::string Name;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000972 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000973 EntryKind Kind;
974
975 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
976 ++I) {
977 StringRef Key;
978 // Reuse the buffer for key and value, since we don't look at key after
979 // parsing value.
980 SmallString<256> Buffer;
981 if (!parseScalarString(I->getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000982 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000983
984 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +0000985 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000986
987 StringRef Value;
988 if (Key == "name") {
989 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000990 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000991 Name = Value;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000992 } else if (Key == "type") {
993 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000994 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000995 if (Value == "file")
996 Kind = EK_File;
997 else if (Value == "directory")
998 Kind = EK_Directory;
999 else {
1000 error(I->getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +00001001 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001002 }
1003 } else if (Key == "contents") {
1004 if (HasContents) {
1005 error(I->getKey(),
1006 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001007 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001008 }
1009 HasContents = true;
1010 yaml::SequenceNode *Contents =
1011 dyn_cast<yaml::SequenceNode>(I->getValue());
1012 if (!Contents) {
1013 // FIXME: this is only for directories, what about files?
1014 error(I->getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +00001015 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001016 }
1017
1018 for (yaml::SequenceNode::iterator I = Contents->begin(),
1019 E = Contents->end();
1020 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001021 if (std::unique_ptr<Entry> E = parseEntry(&*I))
1022 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001023 else
Craig Topperf1186c52014-05-08 06:41:40 +00001024 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001025 }
1026 } else if (Key == "external-contents") {
1027 if (HasContents) {
1028 error(I->getKey(),
1029 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001030 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001031 }
1032 HasContents = true;
1033 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001034 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001035 ExternalContentsPath = Value;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001036 } else if (Key == "use-external-name") {
1037 bool Val;
1038 if (!parseScalarBool(I->getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001039 return nullptr;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001040 UseExternalName = Val ? RedirectingFileEntry::NK_External
1041 : RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001042 } else {
1043 llvm_unreachable("key missing from Keys");
1044 }
1045 }
1046
1047 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001048 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001049
1050 // check for missing keys
1051 if (!HasContents) {
1052 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001053 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001054 }
1055 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001056 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001057
Ben Langmuirb59cf672014-02-27 00:25:12 +00001058 // check invalid configuration
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001059 if (Kind == EK_Directory &&
1060 UseExternalName != RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001061 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001062 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001063 }
1064
Ben Langmuir93853232014-03-05 21:32:20 +00001065 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001066 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001067 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1068 while (Trimmed.size() > RootPathLen &&
1069 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001070 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1071 // Get the last component
1072 StringRef LastComponent = sys::path::filename(Trimmed);
1073
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001074 std::unique_ptr<Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001075 switch (Kind) {
1076 case EK_File:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001077 Result = llvm::make_unique<RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001078 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001079 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001080 case EK_Directory:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001081 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001082 LastComponent, std::move(EntryArrayContents),
1083 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1084 file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001085 break;
1086 }
1087
1088 StringRef Parent = sys::path::parent_path(Trimmed);
1089 if (Parent.empty())
1090 return Result;
1091
1092 // if 'name' contains multiple components, create implicit directory entries
1093 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1094 E = sys::path::rend(Parent);
1095 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001096 std::vector<std::unique_ptr<Entry>> Entries;
1097 Entries.push_back(std::move(Result));
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001098 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001099 *I, std::move(Entries),
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001100 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1101 file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001102 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001103 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001104 }
1105
1106public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001107 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001108
1109 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001110 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001111 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
1112 if (!Top) {
1113 error(Root, "expected mapping node");
1114 return false;
1115 }
1116
1117 KeyStatusPair Fields[] = {
1118 KeyStatusPair("version", true),
1119 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001120 KeyStatusPair("use-external-names", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001121 KeyStatusPair("roots", true),
1122 };
1123
1124 DenseMap<StringRef, KeyStatus> Keys(
1125 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
1126
1127 // Parse configuration and 'roots'
1128 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
1129 ++I) {
1130 SmallString<10> KeyBuffer;
1131 StringRef Key;
1132 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
1133 return false;
1134
1135 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1136 return false;
1137
1138 if (Key == "roots") {
1139 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
1140 if (!Roots) {
1141 error(I->getValue(), "expected array");
1142 return false;
1143 }
1144
1145 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
1146 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001147 if (std::unique_ptr<Entry> E = parseEntry(&*I))
1148 FS->Roots.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001149 else
1150 return false;
1151 }
1152 } else if (Key == "version") {
1153 StringRef VersionString;
1154 SmallString<4> Storage;
1155 if (!parseScalarString(I->getValue(), VersionString, Storage))
1156 return false;
1157 int Version;
1158 if (VersionString.getAsInteger<int>(10, Version)) {
1159 error(I->getValue(), "expected integer");
1160 return false;
1161 }
1162 if (Version < 0) {
1163 error(I->getValue(), "invalid version number");
1164 return false;
1165 }
1166 if (Version != 0) {
1167 error(I->getValue(), "version mismatch, expected 0");
1168 return false;
1169 }
1170 } else if (Key == "case-sensitive") {
1171 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
1172 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001173 } else if (Key == "use-external-names") {
1174 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
1175 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001176 } else {
1177 llvm_unreachable("key missing from Keys");
1178 }
1179 }
1180
1181 if (Stream.failed())
1182 return false;
1183
1184 if (!checkMissingKeys(Top, Keys))
1185 return false;
1186 return true;
1187 }
1188};
1189} // end of anonymous namespace
1190
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001191Entry::~Entry() = default;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001192
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001193RedirectingFileSystem *RedirectingFileSystem::create(
1194 std::unique_ptr<MemoryBuffer> Buffer, SourceMgr::DiagHandlerTy DiagHandler,
1195 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001196
1197 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001198 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001199
Ben Langmuir97882e72014-02-24 20:56:37 +00001200 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001201 yaml::document_iterator DI = Stream.begin();
1202 yaml::Node *Root = DI->getRoot();
1203 if (DI == Stream.end() || !Root) {
1204 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001205 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001206 }
1207
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001208 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001209
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001210 std::unique_ptr<RedirectingFileSystem> FS(
1211 new RedirectingFileSystem(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001212 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001213 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001214
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001215 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001216}
1217
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001218ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001219 SmallString<256> Path;
1220 Path_.toVector(Path);
1221
1222 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001223 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001224 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001225
1226 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001227 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001228
1229 sys::path::const_iterator Start = sys::path::begin(Path);
1230 sys::path::const_iterator End = sys::path::end(Path);
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001231 for (const std::unique_ptr<Entry> &Root : Roots) {
1232 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001233 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001234 return Result;
1235 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001236 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001237}
1238
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001239ErrorOr<Entry *>
1240RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1241 sys::path::const_iterator End, Entry *From) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001242 if (Start->equals("."))
1243 ++Start;
1244
1245 // FIXME: handle ..
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001246 if (CaseSensitive ? !Start->equals(From->getName())
1247 : !Start->equals_lower(From->getName()))
1248 // failure to match
Rafael Espindola71de0b62014-06-13 17:20:50 +00001249 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001250
1251 ++Start;
1252
1253 if (Start == End) {
1254 // Match!
1255 return From;
1256 }
1257
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001258 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001259 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001260 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001261
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001262 for (const std::unique_ptr<Entry> &DirEntry :
1263 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1264 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001265 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001266 return Result;
1267 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001268 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001269}
1270
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001271ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001272 assert(E != nullptr);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001273 std::string PathStr(Path.str());
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001274 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001275 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001276 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuird066d4c2014-02-28 21:16:07 +00001277 if (S && !F->useExternalName(UseExternalNames))
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001278 *S = Status::copyWithNewName(*S, PathStr);
Ben Langmuir5de00f32014-05-23 18:15:47 +00001279 if (S)
1280 S->IsVFSMapped = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001281 return S;
1282 } else { // directory
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001283 auto *DE = cast<RedirectingDirectoryEntry>(E);
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001284 return Status::copyWithNewName(DE->getStatus(), PathStr);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001285 }
1286}
1287
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001288ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001289 ErrorOr<Entry *> Result = lookupPath(Path);
1290 if (!Result)
1291 return Result.getError();
1292 return status(Path, *Result);
1293}
1294
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001295namespace {
1296/// Provide a file wrapper that returns the external name when asked.
1297class NamedFileAdaptor : public File {
1298 std::unique_ptr<File> InnerFile;
1299 std::string NewName;
1300
1301public:
1302 NamedFileAdaptor(std::unique_ptr<File> InnerFile, std::string NewName)
1303 : InnerFile(std::move(InnerFile)), NewName(std::move(NewName)) {}
1304
1305 llvm::ErrorOr<Status> status() override {
1306 auto InnerStatus = InnerFile->status();
1307 if (InnerStatus)
1308 return Status::copyWithNewName(*InnerStatus, NewName);
1309 return InnerStatus.getError();
1310 }
1311 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +00001312 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1313 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001314 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1315 IsVolatile);
1316 }
1317 std::error_code close() override { return InnerFile->close(); }
1318};
1319} // end anonymous namespace
1320
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001321ErrorOr<std::unique_ptr<File>>
1322RedirectingFileSystem::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001323 ErrorOr<Entry *> E = lookupPath(Path);
1324 if (!E)
1325 return E.getError();
1326
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001327 auto *F = dyn_cast<RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001328 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001329 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001330
Benjamin Kramera8857962014-10-26 22:44:13 +00001331 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1332 if (!Result)
1333 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001334
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001335 if (!F->useExternalName(UseExternalNames))
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001336 return std::unique_ptr<File>(
1337 new NamedFileAdaptor(std::move(*Result), Path.str()));
Ben Langmuird066d4c2014-02-28 21:16:07 +00001338
Benjamin Kramera8857962014-10-26 22:44:13 +00001339 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001340}
1341
1342IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001343vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1344 SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001345 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001346 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
1347 DiagContext, ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001348}
1349
1350UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001351 static std::atomic<unsigned> UID;
1352 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001353 // The following assumes that uint64_t max will never collide with a real
1354 // dev_t value from the OS.
1355 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1356}
Justin Bogner9c785292014-05-20 21:43:27 +00001357
1358#ifndef NDEBUG
1359static bool pathHasTraversal(StringRef Path) {
1360 using namespace llvm::sys;
1361 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
1362 if (Comp == "." || Comp == "..")
1363 return true;
1364 return false;
1365}
1366#endif
1367
1368void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1369 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1370 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1371 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1372 Mappings.emplace_back(VirtualPath, RealPath);
1373}
1374
Justin Bogner44fa450342014-05-21 22:46:51 +00001375namespace {
1376class JSONWriter {
1377 llvm::raw_ostream &OS;
1378 SmallVector<StringRef, 16> DirStack;
1379 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
1380 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1381 bool containedIn(StringRef Parent, StringRef Path);
1382 StringRef containedPart(StringRef Parent, StringRef Path);
1383 void startDirectory(StringRef Path);
1384 void endDirectory();
1385 void writeEntry(StringRef VPath, StringRef RPath);
1386
1387public:
1388 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
1389 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive);
1390};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001391}
Justin Bogner9c785292014-05-20 21:43:27 +00001392
Justin Bogner44fa450342014-05-21 22:46:51 +00001393bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001394 using namespace llvm::sys;
1395 // Compare each path component.
1396 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1397 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1398 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1399 if (*IParent != *IChild)
1400 return false;
1401 }
1402 // Have we exhausted the parent path?
1403 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001404}
1405
Justin Bogner44fa450342014-05-21 22:46:51 +00001406StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1407 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001408 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001409 return Path.slice(Parent.size() + 1, StringRef::npos);
1410}
1411
Justin Bogner44fa450342014-05-21 22:46:51 +00001412void JSONWriter::startDirectory(StringRef Path) {
1413 StringRef Name =
1414 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1415 DirStack.push_back(Path);
1416 unsigned Indent = getDirIndent();
1417 OS.indent(Indent) << "{\n";
1418 OS.indent(Indent + 2) << "'type': 'directory',\n";
1419 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1420 OS.indent(Indent + 2) << "'contents': [\n";
1421}
1422
1423void JSONWriter::endDirectory() {
1424 unsigned Indent = getDirIndent();
1425 OS.indent(Indent + 2) << "]\n";
1426 OS.indent(Indent) << "}";
1427
1428 DirStack.pop_back();
1429}
1430
1431void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1432 unsigned Indent = getFileIndent();
1433 OS.indent(Indent) << "{\n";
1434 OS.indent(Indent + 2) << "'type': 'file',\n";
1435 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1436 OS.indent(Indent + 2) << "'external-contents': \""
1437 << llvm::yaml::escape(RPath) << "\"\n";
1438 OS.indent(Indent) << "}";
1439}
1440
1441void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
1442 Optional<bool> IsCaseSensitive) {
1443 using namespace llvm::sys;
1444
1445 OS << "{\n"
1446 " 'version': 0,\n";
1447 if (IsCaseSensitive.hasValue())
1448 OS << " 'case-sensitive': '"
1449 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
1450 OS << " 'roots': [\n";
1451
Justin Bogner73466402014-07-15 01:24:35 +00001452 if (!Entries.empty()) {
1453 const YAMLVFSEntry &Entry = Entries.front();
1454 startDirectory(path::parent_path(Entry.VPath));
Justin Bogner44fa450342014-05-21 22:46:51 +00001455 writeEntry(path::filename(Entry.VPath), Entry.RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001456
Justin Bogner73466402014-07-15 01:24:35 +00001457 for (const auto &Entry : Entries.slice(1)) {
1458 StringRef Dir = path::parent_path(Entry.VPath);
1459 if (Dir == DirStack.back())
1460 OS << ",\n";
1461 else {
1462 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1463 OS << "\n";
1464 endDirectory();
1465 }
1466 OS << ",\n";
1467 startDirectory(Dir);
1468 }
1469 writeEntry(path::filename(Entry.VPath), Entry.RPath);
1470 }
1471
1472 while (!DirStack.empty()) {
1473 OS << "\n";
1474 endDirectory();
1475 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001476 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001477 }
1478
Justin Bogner73466402014-07-15 01:24:35 +00001479 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001480 << "}\n";
1481}
1482
Justin Bogner9c785292014-05-20 21:43:27 +00001483void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1484 std::sort(Mappings.begin(), Mappings.end(),
Justin Bogner44fa450342014-05-21 22:46:51 +00001485 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001486 return LHS.VPath < RHS.VPath;
1487 });
1488
Justin Bogner44fa450342014-05-21 22:46:51 +00001489 JSONWriter(OS).write(Mappings, IsCaseSensitive);
Justin Bogner9c785292014-05-20 21:43:27 +00001490}
Ben Langmuir740812b2014-06-24 19:37:16 +00001491
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001492VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1493 const Twine &_Path, RedirectingFileSystem &FS,
1494 RedirectingDirectoryEntry::iterator Begin,
1495 RedirectingDirectoryEntry::iterator End, std::error_code &EC)
Ben Langmuir740812b2014-06-24 19:37:16 +00001496 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
1497 if (Current != End) {
1498 SmallString<128> PathStr(Dir);
1499 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001500 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001501 if (S)
1502 CurrentEntry = *S;
1503 else
1504 EC = S.getError();
1505 }
1506}
1507
1508std::error_code VFSFromYamlDirIterImpl::increment() {
1509 assert(Current != End && "cannot iterate past end");
1510 if (++Current != End) {
1511 SmallString<128> PathStr(Dir);
1512 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001513 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001514 if (!S)
1515 return S.getError();
1516 CurrentEntry = *S;
1517 } else {
1518 CurrentEntry = Status();
1519 }
1520 return std::error_code();
1521}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001522
1523vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1524 const Twine &Path,
1525 std::error_code &EC)
1526 : FS(&FS_) {
1527 directory_iterator I = FS->dir_begin(Path, EC);
1528 if (!EC && I != directory_iterator()) {
1529 State = std::make_shared<IterState>();
1530 State->push(I);
1531 }
1532}
1533
1534vfs::recursive_directory_iterator &
1535recursive_directory_iterator::increment(std::error_code &EC) {
1536 assert(FS && State && !State->empty() && "incrementing past end");
1537 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1538 vfs::directory_iterator End;
1539 if (State->top()->isDirectory()) {
1540 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
1541 if (EC)
1542 return *this;
1543 if (I != End) {
1544 State->push(I);
1545 return *this;
1546 }
1547 }
1548
1549 while (!State->empty() && State->top().increment(EC) == End)
1550 State->pop();
1551
1552 if (State->empty())
1553 State.reset(); // end iterator
1554
1555 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001556}