blob: 68ad428ec7eb639cc0efc33f09972fd87fec4583 [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
Bruno Cardoso Lopes956e6a02016-02-22 18:41:01 +0000114#ifndef NDEBUG
115static bool isTraversalComponent(StringRef Component) {
116 return Component.equals("..") || Component.equals(".");
117}
118
119static bool pathHasTraversal(StringRef Path) {
120 using namespace llvm::sys;
121 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
122 if (isTraversalComponent(Comp))
123 return true;
124 return false;
125}
126#endif
127
Ben Langmuirc8130a72014-02-20 21:59:23 +0000128//===-----------------------------------------------------------------------===/
129// RealFileSystem implementation
130//===-----------------------------------------------------------------------===/
131
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000132namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000133/// \brief Wrapper around a raw file descriptor.
134class RealFile : public File {
135 int FD;
Ben Langmuird066d4c2014-02-28 21:16:07 +0000136 Status S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000137 friend class RealFileSystem;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000138 RealFile(int FD, StringRef NewName)
139 : FD(FD), S(NewName, {}, {}, {}, {}, {},
140 llvm::sys::fs::file_type::status_error, {}) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000141 assert(FD >= 0 && "Invalid or inactive file descriptor");
142 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000143
Ben Langmuirc8130a72014-02-20 21:59:23 +0000144public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000145 ~RealFile() override;
Craig Toppera798a9d2014-03-02 09:32:10 +0000146 ErrorOr<Status> status() override;
Benjamin Kramer737501c2015-10-05 21:20:19 +0000147 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
148 int64_t FileSize,
149 bool RequiresNullTerminator,
150 bool IsVolatile) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000151 std::error_code close() override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000152};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000153} // end anonymous namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000154RealFile::~RealFile() { close(); }
Ben Langmuirc8130a72014-02-20 21:59:23 +0000155
156ErrorOr<Status> RealFile::status() {
157 assert(FD != -1 && "cannot stat closed file");
Ben Langmuird066d4c2014-02-28 21:16:07 +0000158 if (!S.isStatusKnown()) {
159 file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000160 if (std::error_code EC = sys::fs::status(FD, RealStatus))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000161 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000162 S = Status::copyWithNewName(RealStatus, S.getName());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000163 }
164 return S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000165}
166
Benjamin Kramera8857962014-10-26 22:44:13 +0000167ErrorOr<std::unique_ptr<MemoryBuffer>>
168RealFile::getBuffer(const Twine &Name, int64_t FileSize,
169 bool RequiresNullTerminator, bool IsVolatile) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000170 assert(FD != -1 && "cannot get buffer for closed file");
Benjamin Kramera8857962014-10-26 22:44:13 +0000171 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
172 IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000173}
174
175// FIXME: This is terrible, we need this for ::close.
176#if !defined(_MSC_VER) && !defined(__MINGW32__)
177#include <unistd.h>
178#include <sys/uio.h>
179#else
180#include <io.h>
181#ifndef S_ISFIFO
182#define S_ISFIFO(x) (0)
183#endif
184#endif
Rafael Espindola8e650d72014-06-12 20:37:59 +0000185std::error_code RealFile::close() {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000186 if (::close(FD))
Rafael Espindola8e650d72014-06-12 20:37:59 +0000187 return std::error_code(errno, std::generic_category());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000188 FD = -1;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000189 return std::error_code();
Ben Langmuirc8130a72014-02-20 21:59:23 +0000190}
191
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000192namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000193/// \brief The file system according to your operating system.
194class RealFileSystem : public FileSystem {
195public:
Craig Toppera798a9d2014-03-02 09:32:10 +0000196 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000197 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000198 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000199
200 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
201 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000202};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000203} // end anonymous namespace
Ben Langmuirc8130a72014-02-20 21:59:23 +0000204
205ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
206 sys::fs::file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000207 if (std::error_code EC = sys::fs::status(Path, RealStatus))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000208 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000209 return Status::copyWithNewName(RealStatus, Path.str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000210}
211
Benjamin Kramera8857962014-10-26 22:44:13 +0000212ErrorOr<std::unique_ptr<File>>
213RealFileSystem::openFileForRead(const Twine &Name) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000214 int FD;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000215 if (std::error_code EC = sys::fs::openFileForRead(Name, FD))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000216 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000217 return std::unique_ptr<File>(new RealFile(FD, Name.str()));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000218}
219
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000220llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
221 SmallString<256> Dir;
222 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
223 return EC;
224 return Dir.str().str();
225}
226
227std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
228 // FIXME: chdir is thread hostile; on the other hand, creating the same
229 // behavior as chdir is complex: chdir resolves the path once, thus
230 // guaranteeing that all subsequent relative path operations work
231 // on the same path the original chdir resulted in. This makes a
232 // difference for example on network filesystems, where symlinks might be
233 // switched during runtime of the tool. Fixing this depends on having a
234 // file system abstraction that allows openat() style interactions.
235 SmallString<256> Storage;
236 StringRef Dir = Path.toNullTerminatedStringRef(Storage);
237 if (int Err = ::chdir(Dir.data()))
238 return std::error_code(Err, std::generic_category());
239 return std::error_code();
240}
241
Ben Langmuirc8130a72014-02-20 21:59:23 +0000242IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
243 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
244 return FS;
245}
246
Ben Langmuir740812b2014-06-24 19:37:16 +0000247namespace {
248class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
249 std::string Path;
250 llvm::sys::fs::directory_iterator Iter;
251public:
252 RealFSDirIter(const Twine &_Path, std::error_code &EC)
253 : Path(_Path.str()), Iter(Path, EC) {
254 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
255 llvm::sys::fs::file_status S;
256 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000257 if (!EC)
258 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000259 }
260 }
261
262 std::error_code increment() override {
263 std::error_code EC;
264 Iter.increment(EC);
265 if (EC) {
266 return EC;
267 } else if (Iter == llvm::sys::fs::directory_iterator()) {
268 CurrentEntry = Status();
269 } else {
270 llvm::sys::fs::file_status S;
271 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000272 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000273 }
274 return EC;
275 }
276};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000277}
Ben Langmuir740812b2014-06-24 19:37:16 +0000278
279directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
280 std::error_code &EC) {
281 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
282}
283
Ben Langmuirc8130a72014-02-20 21:59:23 +0000284//===-----------------------------------------------------------------------===/
285// OverlayFileSystem implementation
286//===-----------------------------------------------------------------------===/
287OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000288 FSList.push_back(BaseFS);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000289}
290
291void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
292 FSList.push_back(FS);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000293 // Synchronize added file systems by duplicating the working directory from
294 // the first one in the list.
295 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000296}
297
298ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
299 // FIXME: handle symlinks that cross file systems
300 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
301 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000302 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000303 return Status;
304 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000305 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000306}
307
Benjamin Kramera8857962014-10-26 22:44:13 +0000308ErrorOr<std::unique_ptr<File>>
309OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000310 // FIXME: handle symlinks that cross file systems
311 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000312 auto Result = (*I)->openFileForRead(Path);
313 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
314 return Result;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000315 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000316 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000317}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000318
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000319llvm::ErrorOr<std::string>
320OverlayFileSystem::getCurrentWorkingDirectory() const {
321 // All file systems are synchronized, just take the first working directory.
322 return FSList.front()->getCurrentWorkingDirectory();
323}
324std::error_code
325OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
326 for (auto &FS : FSList)
327 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
328 return EC;
329 return std::error_code();
330}
331
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000332clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
Ben Langmuir740812b2014-06-24 19:37:16 +0000333
334namespace {
335class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
336 OverlayFileSystem &Overlays;
337 std::string Path;
338 OverlayFileSystem::iterator CurrentFS;
339 directory_iterator CurrentDirIter;
340 llvm::StringSet<> SeenNames;
341
342 std::error_code incrementFS() {
343 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
344 ++CurrentFS;
345 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
346 std::error_code EC;
347 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
348 if (EC && EC != errc::no_such_file_or_directory)
349 return EC;
350 if (CurrentDirIter != directory_iterator())
351 break; // found
352 }
353 return std::error_code();
354 }
355
356 std::error_code incrementDirIter(bool IsFirstTime) {
357 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
358 "incrementing past end");
359 std::error_code EC;
360 if (!IsFirstTime)
361 CurrentDirIter.increment(EC);
362 if (!EC && CurrentDirIter == directory_iterator())
363 EC = incrementFS();
364 return EC;
365 }
366
367 std::error_code incrementImpl(bool IsFirstTime) {
368 while (true) {
369 std::error_code EC = incrementDirIter(IsFirstTime);
370 if (EC || CurrentDirIter == directory_iterator()) {
371 CurrentEntry = Status();
372 return EC;
373 }
374 CurrentEntry = *CurrentDirIter;
375 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
David Blaikie61b86d42014-11-19 02:56:13 +0000376 if (SeenNames.insert(Name).second)
Ben Langmuir740812b2014-06-24 19:37:16 +0000377 return EC; // name not seen before
378 }
379 llvm_unreachable("returned above");
380 }
381
382public:
383 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
384 std::error_code &EC)
385 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
386 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
387 EC = incrementImpl(true);
388 }
389
390 std::error_code increment() override { return incrementImpl(false); }
391};
392} // end anonymous namespace
393
394directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
395 std::error_code &EC) {
396 return directory_iterator(
397 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
398}
399
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000400namespace clang {
401namespace vfs {
402namespace detail {
403
404enum InMemoryNodeKind { IME_File, IME_Directory };
405
406/// The in memory file system is a tree of Nodes. Every node can either be a
407/// file or a directory.
408class InMemoryNode {
409 Status Stat;
410 InMemoryNodeKind Kind;
411
412public:
413 InMemoryNode(Status Stat, InMemoryNodeKind Kind)
414 : Stat(std::move(Stat)), Kind(Kind) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000415 virtual ~InMemoryNode() {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000416 const Status &getStatus() const { return Stat; }
417 InMemoryNodeKind getKind() const { return Kind; }
418 virtual std::string toString(unsigned Indent) const = 0;
419};
420
421namespace {
422class InMemoryFile : public InMemoryNode {
423 std::unique_ptr<llvm::MemoryBuffer> Buffer;
424
425public:
426 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
427 : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
428
429 llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
430 std::string toString(unsigned Indent) const override {
431 return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
432 }
433 static bool classof(const InMemoryNode *N) {
434 return N->getKind() == IME_File;
435 }
436};
437
438/// Adapt a InMemoryFile for VFS' File interface.
439class InMemoryFileAdaptor : public File {
440 InMemoryFile &Node;
441
442public:
443 explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
444
445 llvm::ErrorOr<Status> status() override { return Node.getStatus(); }
446 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +0000447 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
448 bool IsVolatile) override {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000449 llvm::MemoryBuffer *Buf = Node.getBuffer();
450 return llvm::MemoryBuffer::getMemBuffer(
451 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
452 }
453 std::error_code close() override { return std::error_code(); }
454};
455} // end anonymous namespace
456
457class InMemoryDirectory : public InMemoryNode {
458 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
459
460public:
461 InMemoryDirectory(Status Stat)
462 : InMemoryNode(std::move(Stat), IME_Directory) {}
463 InMemoryNode *getChild(StringRef Name) {
464 auto I = Entries.find(Name);
465 if (I != Entries.end())
466 return I->second.get();
467 return nullptr;
468 }
469 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
470 return Entries.insert(make_pair(Name, std::move(Child)))
471 .first->second.get();
472 }
473
474 typedef decltype(Entries)::const_iterator const_iterator;
475 const_iterator begin() const { return Entries.begin(); }
476 const_iterator end() const { return Entries.end(); }
477
478 std::string toString(unsigned Indent) const override {
479 std::string Result =
480 (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
481 for (const auto &Entry : Entries) {
482 Result += Entry.second->toString(Indent + 2);
483 }
484 return Result;
485 }
486 static bool classof(const InMemoryNode *N) {
487 return N->getKind() == IME_Directory;
488 }
489};
490}
491
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000492InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000493 : Root(new detail::InMemoryDirectory(
494 Status("", getNextVirtualUniqueID(), llvm::sys::TimeValue::MinTime(),
495 0, 0, 0, llvm::sys::fs::file_type::directory_file,
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000496 llvm::sys::fs::perms::all_all))),
497 UseNormalizedPaths(UseNormalizedPaths) {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000498
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000499InMemoryFileSystem::~InMemoryFileSystem() {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000500
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000501std::string InMemoryFileSystem::toString() const {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000502 return Root->toString(/*Indent=*/0);
503}
504
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000505bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000506 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
507 SmallString<128> Path;
508 P.toVector(Path);
509
510 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000511 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000512 assert(!EC);
513 (void)EC;
514
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000515 if (useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000516 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000517
518 if (Path.empty())
519 return false;
520
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000521 detail::InMemoryDirectory *Dir = Root.get();
522 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
523 while (true) {
524 StringRef Name = *I;
525 detail::InMemoryNode *Node = Dir->getChild(Name);
526 ++I;
527 if (!Node) {
528 if (I == E) {
529 // End of the path, create a new file.
530 // FIXME: expose the status details in the interface.
Benjamin Kramer1b8dbe32015-10-06 14:45:16 +0000531 Status Stat(P.str(), getNextVirtualUniqueID(),
Benjamin Kramer6b618052015-10-05 14:02:15 +0000532 llvm::sys::TimeValue(ModificationTime, 0), 0, 0,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000533 Buffer->getBufferSize(),
534 llvm::sys::fs::file_type::regular_file,
535 llvm::sys::fs::all_all);
536 Dir->addChild(Name, llvm::make_unique<detail::InMemoryFile>(
537 std::move(Stat), std::move(Buffer)));
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000538 return true;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000539 }
540
541 // Create a new directory. Use the path up to here.
542 // FIXME: expose the status details in the interface.
543 Status Stat(
544 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Benjamin Kramer6b618052015-10-05 14:02:15 +0000545 getNextVirtualUniqueID(), llvm::sys::TimeValue(ModificationTime, 0),
546 0, 0, Buffer->getBufferSize(),
547 llvm::sys::fs::file_type::directory_file, llvm::sys::fs::all_all);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000548 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
549 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
550 continue;
551 }
552
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000553 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000554 Dir = NewDir;
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000555 } else {
556 assert(isa<detail::InMemoryFile>(Node) &&
557 "Must be either file or directory!");
558
559 // Trying to insert a directory in place of a file.
560 if (I != E)
561 return false;
562
563 // Return false only if the new file is different from the existing one.
564 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
565 Buffer->getBuffer();
566 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000567 }
568}
569
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000570bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000571 llvm::MemoryBuffer *Buffer) {
572 return addFile(P, ModificationTime,
573 llvm::MemoryBuffer::getMemBuffer(
574 Buffer->getBuffer(), Buffer->getBufferIdentifier()));
575}
576
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000577static ErrorOr<detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000578lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
579 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000580 SmallString<128> Path;
581 P.toVector(Path);
582
583 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000584 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000585 assert(!EC);
586 (void)EC;
587
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000588 if (FS.useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000589 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer4ad1c432015-10-12 13:30:38 +0000590
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000591 if (Path.empty())
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000592 return Dir;
593
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000594 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000595 while (true) {
596 detail::InMemoryNode *Node = Dir->getChild(*I);
597 ++I;
598 if (!Node)
599 return errc::no_such_file_or_directory;
600
601 // Return the file if it's at the end of the path.
602 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
603 if (I == E)
604 return File;
605 return errc::no_such_file_or_directory;
606 }
607
608 // Traverse directories.
609 Dir = cast<detail::InMemoryDirectory>(Node);
610 if (I == E)
611 return Dir;
612 }
613}
614
615llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000616 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000617 if (Node)
618 return (*Node)->getStatus();
619 return Node.getError();
620}
621
622llvm::ErrorOr<std::unique_ptr<File>>
623InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000624 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000625 if (!Node)
626 return Node.getError();
627
628 // When we have a file provide a heap-allocated wrapper for the memory buffer
629 // to match the ownership semantics for File.
630 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
631 return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
632
633 // FIXME: errc::not_a_file?
634 return make_error_code(llvm::errc::invalid_argument);
635}
636
637namespace {
638/// Adaptor from InMemoryDir::iterator to directory_iterator.
639class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
640 detail::InMemoryDirectory::const_iterator I;
641 detail::InMemoryDirectory::const_iterator E;
642
643public:
644 InMemoryDirIterator() {}
645 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
646 : I(Dir.begin()), E(Dir.end()) {
647 if (I != E)
648 CurrentEntry = I->second->getStatus();
649 }
650
651 std::error_code increment() override {
652 ++I;
653 // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
654 // the rest.
655 CurrentEntry = I != E ? I->second->getStatus() : Status();
656 return std::error_code();
657 }
658};
659} // end anonymous namespace
660
661directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
662 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000663 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000664 if (!Node) {
665 EC = Node.getError();
666 return directory_iterator(std::make_shared<InMemoryDirIterator>());
667 }
668
669 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
670 return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
671
672 EC = make_error_code(llvm::errc::not_a_directory);
673 return directory_iterator(std::make_shared<InMemoryDirIterator>());
674}
Benjamin Kramere9e76072016-01-09 16:33:16 +0000675
676std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
677 SmallString<128> Path;
678 P.toVector(Path);
679
680 // Fix up relative paths. This just prepends the current working directory.
681 std::error_code EC = makeAbsolute(Path);
682 assert(!EC);
683 (void)EC;
684
685 if (useNormalizedPaths())
686 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
687
688 if (!Path.empty())
689 WorkingDirectory = Path.str();
690 return std::error_code();
691}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000692}
693}
694
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000695//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000696// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000697//===-----------------------------------------------------------------------===/
698
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000699namespace {
700
701enum EntryKind {
702 EK_Directory,
703 EK_File
704};
705
706/// \brief A single file or directory in the VFS.
707class Entry {
708 EntryKind Kind;
709 std::string Name;
710
711public:
712 virtual ~Entry();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000713 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
714 StringRef getName() const { return Name; }
715 EntryKind getKind() const { return Kind; }
716};
717
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000718class RedirectingDirectoryEntry : public Entry {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000719 std::vector<std::unique_ptr<Entry>> Contents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000720 Status S;
721
722public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000723 RedirectingDirectoryEntry(StringRef Name,
724 std::vector<std::unique_ptr<Entry>> Contents,
725 Status S)
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000726 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000727 S(std::move(S)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000728 Status getStatus() { return S; }
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000729 typedef decltype(Contents)::iterator iterator;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000730 iterator contents_begin() { return Contents.begin(); }
731 iterator contents_end() { return Contents.end(); }
732 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
733};
734
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000735class RedirectingFileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000736public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000737 enum NameKind {
738 NK_NotSet,
739 NK_External,
740 NK_Virtual
741 };
742private:
743 std::string ExternalContentsPath;
744 NameKind UseName;
745public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000746 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
747 NameKind UseName)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000748 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
749 UseName(UseName) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000750 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Ben Langmuirb59cf672014-02-27 00:25:12 +0000751 /// \brief whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000752 bool useExternalName(bool GlobalUseExternalName) const {
753 return UseName == NK_NotSet ? GlobalUseExternalName
754 : (UseName == NK_External);
755 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000756 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
757};
758
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000759class RedirectingFileSystem;
Ben Langmuir740812b2014-06-24 19:37:16 +0000760
761class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
762 std::string Dir;
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000763 RedirectingFileSystem &FS;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000764 RedirectingDirectoryEntry::iterator Current, End;
765
Ben Langmuir740812b2014-06-24 19:37:16 +0000766public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000767 VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000768 RedirectingDirectoryEntry::iterator Begin,
769 RedirectingDirectoryEntry::iterator End,
770 std::error_code &EC);
Ben Langmuir740812b2014-06-24 19:37:16 +0000771 std::error_code increment() override;
772};
773
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000774/// \brief A virtual file system parsed from a YAML file.
775///
776/// Currently, this class allows creating virtual directories and mapping
777/// virtual file paths to existing external files, available in \c ExternalFS.
778///
779/// The basic structure of the parsed file is:
780/// \verbatim
781/// {
782/// 'version': <version number>,
783/// <optional configuration>
784/// 'roots': [
785/// <directory entries>
786/// ]
787/// }
788/// \endverbatim
789///
790/// All configuration options are optional.
791/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000792/// 'use-external-names': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000793///
794/// Virtual directories are represented as
795/// \verbatim
796/// {
797/// 'type': 'directory',
798/// 'name': <string>,
799/// 'contents': [ <file or directory entries> ]
800/// }
801/// \endverbatim
802///
803/// The default attributes for virtual directories are:
804/// \verbatim
805/// MTime = now() when created
806/// Perms = 0777
807/// User = Group = 0
808/// Size = 0
809/// UniqueID = unspecified unique value
810/// \endverbatim
811///
812/// Re-mapped files are represented as
813/// \verbatim
814/// {
815/// 'type': 'file',
816/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000817/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000818/// 'external-contents': <path to external file>)
819/// }
820/// \endverbatim
821///
822/// and inherit their attributes from the external contents.
823///
Bruno Cardoso Lopes956e6a02016-02-22 18:41:01 +0000824/// Virtual file paths and external files are expected to be canonicalized
825/// without "..", "." and "./" in their paths.
826///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000827/// In both cases, the 'name' field may contain multiple path components (e.g.
828/// /path/to/file). However, any directory that contains more than one child
829/// must be uniquely represented by a directory entry.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000830class RedirectingFileSystem : public vfs::FileSystem {
831 /// The root(s) of the virtual file system.
832 std::vector<std::unique_ptr<Entry>> Roots;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000833 /// \brief The file system to use for external references.
834 IntrusiveRefCntPtr<FileSystem> ExternalFS;
835
836 /// @name Configuration
837 /// @{
838
839 /// \brief Whether to perform case-sensitive comparisons.
840 ///
841 /// Currently, case-insensitive matching only works correctly with ASCII.
Ben Langmuirb59cf672014-02-27 00:25:12 +0000842 bool CaseSensitive;
843
844 /// \brief Whether to use to use the value of 'external-contents' for the
845 /// names of files. This global value is overridable on a per-file basis.
846 bool UseExternalNames;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000847 /// @}
848
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000849 friend class RedirectingFileSystemParser;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000850
851private:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000852 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000853 : ExternalFS(ExternalFS), CaseSensitive(true), UseExternalNames(true) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000854
855 /// \brief Looks up \p Path in \c Roots.
856 ErrorOr<Entry *> lookupPath(const Twine &Path);
857
858 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
859 /// recursing into the contents of \p From if it is a directory.
860 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
861 sys::path::const_iterator End, Entry *From);
862
Ben Langmuir740812b2014-06-24 19:37:16 +0000863 /// \brief Get the status of a given an \c Entry.
864 ErrorOr<Status> status(const Twine &Path, Entry *E);
865
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000866public:
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000867 /// \brief Parses \p Buffer, which is expected to be in YAML format and
868 /// returns a virtual file system representing its contents.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000869 static RedirectingFileSystem *
870 create(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesb7eb8db2016-02-23 07:06:12 +0000871 SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext,
872 IntrusiveRefCntPtr<FileSystem> ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000873
Craig Toppera798a9d2014-03-02 09:32:10 +0000874 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000875 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000876
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000877 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
878 return ExternalFS->getCurrentWorkingDirectory();
879 }
880 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
881 return ExternalFS->setCurrentWorkingDirectory(Path);
882 }
883
Ben Langmuir740812b2014-06-24 19:37:16 +0000884 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
885 ErrorOr<Entry *> E = lookupPath(Dir);
886 if (!E) {
887 EC = E.getError();
888 return directory_iterator();
889 }
890 ErrorOr<Status> S = status(Dir, *E);
891 if (!S) {
892 EC = S.getError();
893 return directory_iterator();
894 }
895 if (!S->isDirectory()) {
896 EC = std::error_code(static_cast<int>(errc::not_a_directory),
897 std::system_category());
898 return directory_iterator();
899 }
900
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000901 auto *D = cast<RedirectingDirectoryEntry>(*E);
Ben Langmuir740812b2014-06-24 19:37:16 +0000902 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
903 *this, D->contents_begin(), D->contents_end(), EC));
904 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000905};
906
907/// \brief A helper class to hold the common YAML parsing state.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000908class RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000909 yaml::Stream &Stream;
910
911 void error(yaml::Node *N, const Twine &Msg) {
912 Stream.printError(N, Msg);
913 }
914
915 // false on error
916 bool parseScalarString(yaml::Node *N, StringRef &Result,
917 SmallVectorImpl<char> &Storage) {
918 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
919 if (!S) {
920 error(N, "expected string");
921 return false;
922 }
923 Result = S->getValue(Storage);
924 return true;
925 }
926
927 // false on error
928 bool parseScalarBool(yaml::Node *N, bool &Result) {
929 SmallString<5> Storage;
930 StringRef Value;
931 if (!parseScalarString(N, Value, Storage))
932 return false;
933
934 if (Value.equals_lower("true") || Value.equals_lower("on") ||
935 Value.equals_lower("yes") || Value == "1") {
936 Result = true;
937 return true;
938 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
939 Value.equals_lower("no") || Value == "0") {
940 Result = false;
941 return true;
942 }
943
944 error(N, "expected boolean value");
945 return false;
946 }
947
948 struct KeyStatus {
949 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
950 bool Required;
951 bool Seen;
952 };
953 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
954
955 // false on error
956 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
957 DenseMap<StringRef, KeyStatus> &Keys) {
958 if (!Keys.count(Key)) {
959 error(KeyNode, "unknown key");
960 return false;
961 }
962 KeyStatus &S = Keys[Key];
963 if (S.Seen) {
964 error(KeyNode, Twine("duplicate key '") + Key + "'");
965 return false;
966 }
967 S.Seen = true;
968 return true;
969 }
970
971 // false on error
972 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
973 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
974 E = Keys.end();
975 I != E; ++I) {
976 if (I->second.Required && !I->second.Seen) {
977 error(Obj, Twine("missing key '") + I->first + "'");
978 return false;
979 }
980 }
981 return true;
982 }
983
Bruno Cardoso Lopesb7eb8db2016-02-23 07:06:12 +0000984 std::unique_ptr<Entry> parseEntry(yaml::Node *N) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000985 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
986 if (!M) {
987 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +0000988 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000989 }
990
991 KeyStatusPair Fields[] = {
992 KeyStatusPair("name", true),
993 KeyStatusPair("type", true),
994 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +0000995 KeyStatusPair("external-contents", false),
996 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000997 };
998
Craig Topperac67c052015-11-30 03:11:10 +0000999 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001000
1001 bool HasContents = false; // external or otherwise
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001002 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001003 std::string ExternalContentsPath;
1004 std::string Name;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001005 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001006 EntryKind Kind;
1007
1008 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
1009 ++I) {
1010 StringRef Key;
1011 // Reuse the buffer for key and value, since we don't look at key after
1012 // parsing value.
1013 SmallString<256> Buffer;
1014 if (!parseScalarString(I->getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001015 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001016
1017 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001018 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001019
1020 StringRef Value;
1021 if (Key == "name") {
1022 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001023 return nullptr;
Bruno Cardoso Lopes956e6a02016-02-22 18:41:01 +00001024
1025 SmallString<256> Path(Value);
1026 // Guarantee that old YAML files containing paths with ".." and "." are
1027 // properly canonicalized before read into the VFS.
1028 Path = sys::path::remove_leading_dotslash(Path);
1029 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1030 Name = Path.str();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001031 } else if (Key == "type") {
1032 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001033 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001034 if (Value == "file")
1035 Kind = EK_File;
1036 else if (Value == "directory")
1037 Kind = EK_Directory;
1038 else {
1039 error(I->getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +00001040 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001041 }
1042 } else if (Key == "contents") {
1043 if (HasContents) {
1044 error(I->getKey(),
1045 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001046 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001047 }
1048 HasContents = true;
1049 yaml::SequenceNode *Contents =
1050 dyn_cast<yaml::SequenceNode>(I->getValue());
1051 if (!Contents) {
1052 // FIXME: this is only for directories, what about files?
1053 error(I->getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +00001054 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001055 }
1056
1057 for (yaml::SequenceNode::iterator I = Contents->begin(),
1058 E = Contents->end();
1059 I != E; ++I) {
Bruno Cardoso Lopesb7eb8db2016-02-23 07:06:12 +00001060 if (std::unique_ptr<Entry> E = parseEntry(&*I))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001061 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001062 else
Craig Topperf1186c52014-05-08 06:41:40 +00001063 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001064 }
1065 } else if (Key == "external-contents") {
1066 if (HasContents) {
1067 error(I->getKey(),
1068 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001069 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001070 }
1071 HasContents = true;
1072 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001073 return nullptr;
Bruno Cardoso Lopesb7eb8db2016-02-23 07:06:12 +00001074 SmallString<256> Path(Value);
Bruno Cardoso Lopes956e6a02016-02-22 18:41:01 +00001075 // Guarantee that old YAML files containing paths with ".." and "." are
1076 // properly canonicalized before read into the VFS.
Bruno Cardoso Lopesb7eb8db2016-02-23 07:06:12 +00001077 Path = sys::path::remove_leading_dotslash(Path);
1078 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1079 ExternalContentsPath = Path.str();
Ben Langmuirb59cf672014-02-27 00:25:12 +00001080 } else if (Key == "use-external-name") {
1081 bool Val;
1082 if (!parseScalarBool(I->getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001083 return nullptr;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001084 UseExternalName = Val ? RedirectingFileEntry::NK_External
1085 : RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001086 } else {
1087 llvm_unreachable("key missing from Keys");
1088 }
1089 }
1090
1091 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001092 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001093
1094 // check for missing keys
1095 if (!HasContents) {
1096 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001097 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001098 }
1099 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001100 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001101
Ben Langmuirb59cf672014-02-27 00:25:12 +00001102 // check invalid configuration
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001103 if (Kind == EK_Directory &&
1104 UseExternalName != RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001105 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001106 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001107 }
1108
Ben Langmuir93853232014-03-05 21:32:20 +00001109 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001110 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001111 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1112 while (Trimmed.size() > RootPathLen &&
1113 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001114 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1115 // Get the last component
1116 StringRef LastComponent = sys::path::filename(Trimmed);
1117
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001118 std::unique_ptr<Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001119 switch (Kind) {
1120 case EK_File:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001121 Result = llvm::make_unique<RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001122 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001123 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001124 case EK_Directory:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001125 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001126 LastComponent, std::move(EntryArrayContents),
1127 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1128 file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001129 break;
1130 }
1131
1132 StringRef Parent = sys::path::parent_path(Trimmed);
1133 if (Parent.empty())
1134 return Result;
1135
1136 // if 'name' contains multiple components, create implicit directory entries
1137 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1138 E = sys::path::rend(Parent);
1139 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001140 std::vector<std::unique_ptr<Entry>> Entries;
1141 Entries.push_back(std::move(Result));
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001142 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001143 *I, std::move(Entries),
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001144 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1145 file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001146 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001147 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001148 }
1149
1150public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001151 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001152
1153 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001154 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001155 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
1156 if (!Top) {
1157 error(Root, "expected mapping node");
1158 return false;
1159 }
1160
1161 KeyStatusPair Fields[] = {
1162 KeyStatusPair("version", true),
1163 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001164 KeyStatusPair("use-external-names", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001165 KeyStatusPair("roots", true),
1166 };
1167
Craig Topperac67c052015-11-30 03:11:10 +00001168 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001169
1170 // Parse configuration and 'roots'
1171 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
1172 ++I) {
1173 SmallString<10> KeyBuffer;
1174 StringRef Key;
1175 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
1176 return false;
1177
1178 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1179 return false;
1180
1181 if (Key == "roots") {
1182 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
1183 if (!Roots) {
1184 error(I->getValue(), "expected array");
1185 return false;
1186 }
1187
1188 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
1189 I != E; ++I) {
Bruno Cardoso Lopesb7eb8db2016-02-23 07:06:12 +00001190 if (std::unique_ptr<Entry> E = parseEntry(&*I))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001191 FS->Roots.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001192 else
1193 return false;
1194 }
1195 } else if (Key == "version") {
1196 StringRef VersionString;
1197 SmallString<4> Storage;
1198 if (!parseScalarString(I->getValue(), VersionString, Storage))
1199 return false;
1200 int Version;
1201 if (VersionString.getAsInteger<int>(10, Version)) {
1202 error(I->getValue(), "expected integer");
1203 return false;
1204 }
1205 if (Version < 0) {
1206 error(I->getValue(), "invalid version number");
1207 return false;
1208 }
1209 if (Version != 0) {
1210 error(I->getValue(), "version mismatch, expected 0");
1211 return false;
1212 }
1213 } else if (Key == "case-sensitive") {
1214 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
1215 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001216 } else if (Key == "use-external-names") {
1217 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
1218 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001219 } else {
1220 llvm_unreachable("key missing from Keys");
1221 }
1222 }
1223
1224 if (Stream.failed())
1225 return false;
1226
1227 if (!checkMissingKeys(Top, Keys))
1228 return false;
1229 return true;
1230 }
1231};
1232} // end of anonymous namespace
1233
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001234Entry::~Entry() = default;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001235
Bruno Cardoso Lopesb7eb8db2016-02-23 07:06:12 +00001236RedirectingFileSystem *RedirectingFileSystem::create(
1237 std::unique_ptr<MemoryBuffer> Buffer, SourceMgr::DiagHandlerTy DiagHandler,
1238 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001239
1240 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001241 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001242
Ben Langmuir97882e72014-02-24 20:56:37 +00001243 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001244 yaml::document_iterator DI = Stream.begin();
1245 yaml::Node *Root = DI->getRoot();
1246 if (DI == Stream.end() || !Root) {
1247 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001248 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001249 }
1250
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001251 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001252
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001253 std::unique_ptr<RedirectingFileSystem> FS(
1254 new RedirectingFileSystem(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001255 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001256 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001257
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001258 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001259}
1260
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001261ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001262 SmallString<256> Path;
1263 Path_.toVector(Path);
1264
1265 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001266 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001267 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001268
Bruno Cardoso Lopes956e6a02016-02-22 18:41:01 +00001269 // Canonicalize path by removing ".", "..", "./", etc components. This is
1270 // a VFS request, do bot bother about symlinks in the path components
1271 // but canonicalize in order to perform the correct entry search.
1272 Path = sys::path::remove_leading_dotslash(Path);
1273 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1274
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001275 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001276 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001277
1278 sys::path::const_iterator Start = sys::path::begin(Path);
1279 sys::path::const_iterator End = sys::path::end(Path);
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001280 for (const std::unique_ptr<Entry> &Root : Roots) {
1281 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001282 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001283 return Result;
1284 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001285 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001286}
1287
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001288ErrorOr<Entry *>
1289RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1290 sys::path::const_iterator End, Entry *From) {
Bruno Cardoso Lopes956e6a02016-02-22 18:41:01 +00001291 assert(!isTraversalComponent(*Start) &&
1292 !isTraversalComponent(From->getName()) &&
1293 "Paths should not contain traversal components");
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001294
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001295 if (CaseSensitive ? !Start->equals(From->getName())
1296 : !Start->equals_lower(From->getName()))
1297 // failure to match
Rafael Espindola71de0b62014-06-13 17:20:50 +00001298 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001299
1300 ++Start;
1301
1302 if (Start == End) {
1303 // Match!
1304 return From;
1305 }
1306
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001307 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001308 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001309 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001310
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001311 for (const std::unique_ptr<Entry> &DirEntry :
1312 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1313 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001314 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001315 return Result;
1316 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001317 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001318}
1319
Ben Langmuirf13302e2015-12-10 23:41:39 +00001320static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1321 Status ExternalStatus) {
1322 Status S = ExternalStatus;
1323 if (!UseExternalNames)
1324 S = Status::copyWithNewName(S, Path.str());
1325 S.IsVFSMapped = true;
1326 return S;
1327}
1328
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001329ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001330 assert(E != nullptr);
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001331 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001332 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001333 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuir5de00f32014-05-23 18:15:47 +00001334 if (S)
Ben Langmuirf13302e2015-12-10 23:41:39 +00001335 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1336 *S);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001337 return S;
1338 } else { // directory
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001339 auto *DE = cast<RedirectingDirectoryEntry>(E);
Ben Langmuirf13302e2015-12-10 23:41:39 +00001340 return Status::copyWithNewName(DE->getStatus(), Path.str());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001341 }
1342}
1343
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001344ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001345 ErrorOr<Entry *> Result = lookupPath(Path);
1346 if (!Result)
1347 return Result.getError();
1348 return status(Path, *Result);
1349}
1350
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001351namespace {
Ben Langmuirf13302e2015-12-10 23:41:39 +00001352/// Provide a file wrapper with an overriden status.
1353class FileWithFixedStatus : public File {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001354 std::unique_ptr<File> InnerFile;
Ben Langmuirf13302e2015-12-10 23:41:39 +00001355 Status S;
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001356
1357public:
Ben Langmuirf13302e2015-12-10 23:41:39 +00001358 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
1359 : InnerFile(std::move(InnerFile)), S(S) {}
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001360
Ben Langmuirf13302e2015-12-10 23:41:39 +00001361 ErrorOr<Status> status() override { return S; }
1362 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +00001363 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1364 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001365 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1366 IsVolatile);
1367 }
1368 std::error_code close() override { return InnerFile->close(); }
1369};
1370} // end anonymous namespace
1371
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001372ErrorOr<std::unique_ptr<File>>
1373RedirectingFileSystem::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001374 ErrorOr<Entry *> E = lookupPath(Path);
1375 if (!E)
1376 return E.getError();
1377
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001378 auto *F = dyn_cast<RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001379 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001380 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001381
Benjamin Kramera8857962014-10-26 22:44:13 +00001382 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1383 if (!Result)
1384 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001385
Ben Langmuirf13302e2015-12-10 23:41:39 +00001386 auto ExternalStatus = (*Result)->status();
1387 if (!ExternalStatus)
1388 return ExternalStatus.getError();
Ben Langmuird066d4c2014-02-28 21:16:07 +00001389
Ben Langmuirf13302e2015-12-10 23:41:39 +00001390 // FIXME: Update the status with the name and VFSMapped.
1391 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1392 *ExternalStatus);
1393 return std::unique_ptr<File>(
1394 llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001395}
1396
1397IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001398vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesb7eb8db2016-02-23 07:06:12 +00001399 SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001400 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001401 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
Bruno Cardoso Lopesb7eb8db2016-02-23 07:06:12 +00001402 DiagContext, ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001403}
1404
1405UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001406 static std::atomic<unsigned> UID;
1407 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001408 // The following assumes that uint64_t max will never collide with a real
1409 // dev_t value from the OS.
1410 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1411}
Justin Bogner9c785292014-05-20 21:43:27 +00001412
Justin Bogner9c785292014-05-20 21:43:27 +00001413void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1414 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1415 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1416 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1417 Mappings.emplace_back(VirtualPath, RealPath);
1418}
1419
Justin Bogner44fa450342014-05-21 22:46:51 +00001420namespace {
1421class JSONWriter {
1422 llvm::raw_ostream &OS;
1423 SmallVector<StringRef, 16> DirStack;
1424 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
1425 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1426 bool containedIn(StringRef Parent, StringRef Path);
1427 StringRef containedPart(StringRef Parent, StringRef Path);
1428 void startDirectory(StringRef Path);
1429 void endDirectory();
1430 void writeEntry(StringRef VPath, StringRef RPath);
1431
1432public:
1433 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
Bruno Cardoso Lopesb7eb8db2016-02-23 07:06:12 +00001434 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive);
Justin Bogner44fa450342014-05-21 22:46:51 +00001435};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001436}
Justin Bogner9c785292014-05-20 21:43:27 +00001437
Justin Bogner44fa450342014-05-21 22:46:51 +00001438bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001439 using namespace llvm::sys;
1440 // Compare each path component.
1441 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1442 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1443 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1444 if (*IParent != *IChild)
1445 return false;
1446 }
1447 // Have we exhausted the parent path?
1448 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001449}
1450
Justin Bogner44fa450342014-05-21 22:46:51 +00001451StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1452 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001453 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001454 return Path.slice(Parent.size() + 1, StringRef::npos);
1455}
1456
Justin Bogner44fa450342014-05-21 22:46:51 +00001457void JSONWriter::startDirectory(StringRef Path) {
1458 StringRef Name =
1459 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1460 DirStack.push_back(Path);
1461 unsigned Indent = getDirIndent();
1462 OS.indent(Indent) << "{\n";
1463 OS.indent(Indent + 2) << "'type': 'directory',\n";
1464 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1465 OS.indent(Indent + 2) << "'contents': [\n";
1466}
1467
1468void JSONWriter::endDirectory() {
1469 unsigned Indent = getDirIndent();
1470 OS.indent(Indent + 2) << "]\n";
1471 OS.indent(Indent) << "}";
1472
1473 DirStack.pop_back();
1474}
1475
1476void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1477 unsigned Indent = getFileIndent();
1478 OS.indent(Indent) << "{\n";
1479 OS.indent(Indent + 2) << "'type': 'file',\n";
1480 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1481 OS.indent(Indent + 2) << "'external-contents': \""
1482 << llvm::yaml::escape(RPath) << "\"\n";
1483 OS.indent(Indent) << "}";
1484}
1485
1486void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
Bruno Cardoso Lopesb7eb8db2016-02-23 07:06:12 +00001487 Optional<bool> IsCaseSensitive) {
Justin Bogner44fa450342014-05-21 22:46:51 +00001488 using namespace llvm::sys;
1489
1490 OS << "{\n"
1491 " 'version': 0,\n";
1492 if (IsCaseSensitive.hasValue())
1493 OS << " 'case-sensitive': '"
1494 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
1495 OS << " 'roots': [\n";
1496
Justin Bogner73466402014-07-15 01:24:35 +00001497 if (!Entries.empty()) {
1498 const YAMLVFSEntry &Entry = Entries.front();
1499 startDirectory(path::parent_path(Entry.VPath));
Bruno Cardoso Lopesb7eb8db2016-02-23 07:06:12 +00001500 writeEntry(path::filename(Entry.VPath), Entry.RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001501
Justin Bogner73466402014-07-15 01:24:35 +00001502 for (const auto &Entry : Entries.slice(1)) {
1503 StringRef Dir = path::parent_path(Entry.VPath);
1504 if (Dir == DirStack.back())
1505 OS << ",\n";
1506 else {
1507 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1508 OS << "\n";
1509 endDirectory();
1510 }
1511 OS << ",\n";
1512 startDirectory(Dir);
1513 }
Bruno Cardoso Lopesb7eb8db2016-02-23 07:06:12 +00001514 writeEntry(path::filename(Entry.VPath), Entry.RPath);
Justin Bogner73466402014-07-15 01:24:35 +00001515 }
1516
1517 while (!DirStack.empty()) {
1518 OS << "\n";
1519 endDirectory();
1520 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001521 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001522 }
1523
Justin Bogner73466402014-07-15 01:24:35 +00001524 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001525 << "}\n";
1526}
1527
Justin Bogner9c785292014-05-20 21:43:27 +00001528void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1529 std::sort(Mappings.begin(), Mappings.end(),
Justin Bogner44fa450342014-05-21 22:46:51 +00001530 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001531 return LHS.VPath < RHS.VPath;
1532 });
1533
Bruno Cardoso Lopesb7eb8db2016-02-23 07:06:12 +00001534 JSONWriter(OS).write(Mappings, IsCaseSensitive);
Justin Bogner9c785292014-05-20 21:43:27 +00001535}
Ben Langmuir740812b2014-06-24 19:37:16 +00001536
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001537VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1538 const Twine &_Path, RedirectingFileSystem &FS,
1539 RedirectingDirectoryEntry::iterator Begin,
1540 RedirectingDirectoryEntry::iterator End, std::error_code &EC)
Ben Langmuir740812b2014-06-24 19:37:16 +00001541 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
1542 if (Current != End) {
1543 SmallString<128> PathStr(Dir);
1544 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001545 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001546 if (S)
1547 CurrentEntry = *S;
1548 else
1549 EC = S.getError();
1550 }
1551}
1552
1553std::error_code VFSFromYamlDirIterImpl::increment() {
1554 assert(Current != End && "cannot iterate past end");
1555 if (++Current != End) {
1556 SmallString<128> PathStr(Dir);
1557 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001558 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001559 if (!S)
1560 return S.getError();
1561 CurrentEntry = *S;
1562 } else {
1563 CurrentEntry = Status();
1564 }
1565 return std::error_code();
1566}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001567
1568vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1569 const Twine &Path,
1570 std::error_code &EC)
1571 : FS(&FS_) {
1572 directory_iterator I = FS->dir_begin(Path, EC);
1573 if (!EC && I != directory_iterator()) {
1574 State = std::make_shared<IterState>();
1575 State->push(I);
1576 }
1577}
1578
1579vfs::recursive_directory_iterator &
1580recursive_directory_iterator::increment(std::error_code &EC) {
1581 assert(FS && State && !State->empty() && "incrementing past end");
1582 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1583 vfs::directory_iterator End;
1584 if (State->top()->isDirectory()) {
1585 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
1586 if (EC)
1587 return *this;
1588 if (I != End) {
1589 State->push(I);
1590 return *this;
1591 }
1592 }
1593
1594 while (!State->empty() && State->top().increment(EC) == End)
1595 State->pop();
1596
1597 if (State->empty())
1598 State.reset(); // end iterator
1599
1600 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001601}