blob: a44111a388577a98cabc710ceb5fd2e29d5c815a [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"
David Majnemer6a6206d2016-03-04 05:26:14 +000022#include "llvm/Support/Process.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000023#include "llvm/Support/YAMLParser.h"
Benjamin Kramerd6bbee72015-10-05 14:06:36 +000024#include "llvm/Config/llvm-config.h"
Benjamin Kramer4527fb22014-03-02 17:08:31 +000025#include <atomic>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000026#include <memory>
Ben Langmuirc8130a72014-02-20 21:59:23 +000027
Benjamin Kramerd6bbee72015-10-05 14:06:36 +000028// For chdir.
29#ifdef LLVM_ON_WIN32
30# include <direct.h>
31#else
32# include <unistd.h>
33#endif
34
Ben Langmuirc8130a72014-02-20 21:59:23 +000035using namespace clang;
36using namespace clang::vfs;
37using namespace llvm;
38using llvm::sys::fs::file_status;
39using llvm::sys::fs::file_type;
40using llvm::sys::fs::perms;
41using llvm::sys::fs::UniqueID;
42
43Status::Status(const file_status &Status)
44 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
45 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
Ben Langmuir5de00f32014-05-23 18:15:47 +000046 Type(Status.type()), Perms(Status.permissions()), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000047
Benjamin Kramer268b51a2015-10-05 13:15:33 +000048Status::Status(StringRef Name, UniqueID UID, sys::TimeValue MTime,
49 uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
50 perms Perms)
Ben Langmuirb59cf672014-02-27 00:25:12 +000051 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
Ben Langmuir5de00f32014-05-23 18:15:47 +000052 Type(Type), Perms(Perms), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000053
Benjamin Kramer268b51a2015-10-05 13:15:33 +000054Status Status::copyWithNewName(const Status &In, StringRef NewName) {
55 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
56 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
57 In.getPermissions());
58}
59
60Status Status::copyWithNewName(const file_status &In, StringRef NewName) {
61 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
62 In.getUser(), In.getGroup(), In.getSize(), In.type(),
63 In.permissions());
64}
65
Ben Langmuirc8130a72014-02-20 21:59:23 +000066bool Status::equivalent(const Status &Other) const {
67 return getUniqueID() == Other.getUniqueID();
68}
69bool Status::isDirectory() const {
70 return Type == file_type::directory_file;
71}
72bool Status::isRegularFile() const {
73 return Type == file_type::regular_file;
74}
75bool Status::isOther() const {
76 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
77}
78bool Status::isSymlink() const {
79 return Type == file_type::symlink_file;
80}
81bool Status::isStatusKnown() const {
82 return Type != file_type::status_error;
83}
84bool Status::exists() const {
85 return isStatusKnown() && Type != file_type::file_not_found;
86}
87
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000088File::~File() {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000089
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000090FileSystem::~FileSystem() {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000091
Benjamin Kramera8857962014-10-26 22:44:13 +000092ErrorOr<std::unique_ptr<MemoryBuffer>>
93FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
94 bool RequiresNullTerminator, bool IsVolatile) {
95 auto F = openFileForRead(Name);
96 if (!F)
97 return F.getError();
Ben Langmuirc8130a72014-02-20 21:59:23 +000098
Benjamin Kramera8857962014-10-26 22:44:13 +000099 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000100}
101
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000102std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
Bob Wilsonf43354f2016-03-26 18:55:13 +0000103 if (llvm::sys::path::is_absolute(Path))
104 return std::error_code();
105
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000106 auto WorkingDir = getCurrentWorkingDirectory();
107 if (!WorkingDir)
108 return WorkingDir.getError();
109
110 return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
111}
112
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000113bool FileSystem::exists(const Twine &Path) {
114 auto Status = status(Path);
115 return Status && Status->exists();
116}
117
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000118#ifndef NDEBUG
119static bool isTraversalComponent(StringRef Component) {
120 return Component.equals("..") || Component.equals(".");
121}
122
123static bool pathHasTraversal(StringRef Path) {
124 using namespace llvm::sys;
125 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
126 if (isTraversalComponent(Comp))
127 return true;
128 return false;
129}
130#endif
131
Ben Langmuirc8130a72014-02-20 21:59:23 +0000132//===-----------------------------------------------------------------------===/
133// RealFileSystem implementation
134//===-----------------------------------------------------------------------===/
135
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000136namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000137/// \brief Wrapper around a raw file descriptor.
138class RealFile : public File {
139 int FD;
Ben Langmuird066d4c2014-02-28 21:16:07 +0000140 Status S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000141 friend class RealFileSystem;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000142 RealFile(int FD, StringRef NewName)
143 : FD(FD), S(NewName, {}, {}, {}, {}, {},
144 llvm::sys::fs::file_type::status_error, {}) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000145 assert(FD >= 0 && "Invalid or inactive file descriptor");
146 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000147
Ben Langmuirc8130a72014-02-20 21:59:23 +0000148public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000149 ~RealFile() override;
Craig Toppera798a9d2014-03-02 09:32:10 +0000150 ErrorOr<Status> status() override;
Benjamin Kramer737501c2015-10-05 21:20:19 +0000151 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
152 int64_t FileSize,
153 bool RequiresNullTerminator,
154 bool IsVolatile) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000155 std::error_code close() override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000156};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000157} // end anonymous namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000158RealFile::~RealFile() { close(); }
Ben Langmuirc8130a72014-02-20 21:59:23 +0000159
160ErrorOr<Status> RealFile::status() {
161 assert(FD != -1 && "cannot stat closed file");
Ben Langmuird066d4c2014-02-28 21:16:07 +0000162 if (!S.isStatusKnown()) {
163 file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000164 if (std::error_code EC = sys::fs::status(FD, RealStatus))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000165 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000166 S = Status::copyWithNewName(RealStatus, S.getName());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000167 }
168 return S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000169}
170
Benjamin Kramera8857962014-10-26 22:44:13 +0000171ErrorOr<std::unique_ptr<MemoryBuffer>>
172RealFile::getBuffer(const Twine &Name, int64_t FileSize,
173 bool RequiresNullTerminator, bool IsVolatile) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000174 assert(FD != -1 && "cannot get buffer for closed file");
Benjamin Kramera8857962014-10-26 22:44:13 +0000175 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
176 IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000177}
178
Rafael Espindola8e650d72014-06-12 20:37:59 +0000179std::error_code RealFile::close() {
David Majnemer6a6206d2016-03-04 05:26:14 +0000180 std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000181 FD = -1;
David Majnemer6a6206d2016-03-04 05:26:14 +0000182 return EC;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000183}
184
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000185namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000186/// \brief The file system according to your operating system.
187class RealFileSystem : public FileSystem {
188public:
Craig Toppera798a9d2014-03-02 09:32:10 +0000189 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000190 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000191 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000192
193 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
194 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000195};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000196} // end anonymous namespace
Ben Langmuirc8130a72014-02-20 21:59:23 +0000197
198ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
199 sys::fs::file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000200 if (std::error_code EC = sys::fs::status(Path, RealStatus))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000201 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000202 return Status::copyWithNewName(RealStatus, Path.str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000203}
204
Benjamin Kramera8857962014-10-26 22:44:13 +0000205ErrorOr<std::unique_ptr<File>>
206RealFileSystem::openFileForRead(const Twine &Name) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000207 int FD;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000208 if (std::error_code EC = sys::fs::openFileForRead(Name, FD))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000209 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000210 return std::unique_ptr<File>(new RealFile(FD, Name.str()));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000211}
212
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000213llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
214 SmallString<256> Dir;
215 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
216 return EC;
217 return Dir.str().str();
218}
219
220std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
221 // FIXME: chdir is thread hostile; on the other hand, creating the same
222 // behavior as chdir is complex: chdir resolves the path once, thus
223 // guaranteeing that all subsequent relative path operations work
224 // on the same path the original chdir resulted in. This makes a
225 // difference for example on network filesystems, where symlinks might be
226 // switched during runtime of the tool. Fixing this depends on having a
227 // file system abstraction that allows openat() style interactions.
228 SmallString<256> Storage;
229 StringRef Dir = Path.toNullTerminatedStringRef(Storage);
230 if (int Err = ::chdir(Dir.data()))
231 return std::error_code(Err, std::generic_category());
232 return std::error_code();
233}
234
Ben Langmuirc8130a72014-02-20 21:59:23 +0000235IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
236 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
237 return FS;
238}
239
Ben Langmuir740812b2014-06-24 19:37:16 +0000240namespace {
241class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
242 std::string Path;
243 llvm::sys::fs::directory_iterator Iter;
244public:
245 RealFSDirIter(const Twine &_Path, std::error_code &EC)
246 : Path(_Path.str()), Iter(Path, EC) {
247 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
248 llvm::sys::fs::file_status S;
249 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000250 if (!EC)
251 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000252 }
253 }
254
255 std::error_code increment() override {
256 std::error_code EC;
257 Iter.increment(EC);
258 if (EC) {
259 return EC;
260 } else if (Iter == llvm::sys::fs::directory_iterator()) {
261 CurrentEntry = Status();
262 } else {
263 llvm::sys::fs::file_status S;
264 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000265 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000266 }
267 return EC;
268 }
269};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000270}
Ben Langmuir740812b2014-06-24 19:37:16 +0000271
272directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
273 std::error_code &EC) {
274 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
275}
276
Ben Langmuirc8130a72014-02-20 21:59:23 +0000277//===-----------------------------------------------------------------------===/
278// OverlayFileSystem implementation
279//===-----------------------------------------------------------------------===/
280OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000281 FSList.push_back(BaseFS);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000282}
283
284void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
285 FSList.push_back(FS);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000286 // Synchronize added file systems by duplicating the working directory from
287 // the first one in the list.
288 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000289}
290
291ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
292 // FIXME: handle symlinks that cross file systems
293 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
294 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000295 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000296 return Status;
297 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000298 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000299}
300
Benjamin Kramera8857962014-10-26 22:44:13 +0000301ErrorOr<std::unique_ptr<File>>
302OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000303 // FIXME: handle symlinks that cross file systems
304 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000305 auto Result = (*I)->openFileForRead(Path);
306 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
307 return Result;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000308 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000309 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000310}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000311
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000312llvm::ErrorOr<std::string>
313OverlayFileSystem::getCurrentWorkingDirectory() const {
314 // All file systems are synchronized, just take the first working directory.
315 return FSList.front()->getCurrentWorkingDirectory();
316}
317std::error_code
318OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
319 for (auto &FS : FSList)
320 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
321 return EC;
322 return std::error_code();
323}
324
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000325clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
Ben Langmuir740812b2014-06-24 19:37:16 +0000326
327namespace {
328class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
329 OverlayFileSystem &Overlays;
330 std::string Path;
331 OverlayFileSystem::iterator CurrentFS;
332 directory_iterator CurrentDirIter;
333 llvm::StringSet<> SeenNames;
334
335 std::error_code incrementFS() {
336 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
337 ++CurrentFS;
338 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
339 std::error_code EC;
340 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
341 if (EC && EC != errc::no_such_file_or_directory)
342 return EC;
343 if (CurrentDirIter != directory_iterator())
344 break; // found
345 }
346 return std::error_code();
347 }
348
349 std::error_code incrementDirIter(bool IsFirstTime) {
350 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
351 "incrementing past end");
352 std::error_code EC;
353 if (!IsFirstTime)
354 CurrentDirIter.increment(EC);
355 if (!EC && CurrentDirIter == directory_iterator())
356 EC = incrementFS();
357 return EC;
358 }
359
360 std::error_code incrementImpl(bool IsFirstTime) {
361 while (true) {
362 std::error_code EC = incrementDirIter(IsFirstTime);
363 if (EC || CurrentDirIter == directory_iterator()) {
364 CurrentEntry = Status();
365 return EC;
366 }
367 CurrentEntry = *CurrentDirIter;
368 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
David Blaikie61b86d42014-11-19 02:56:13 +0000369 if (SeenNames.insert(Name).second)
Ben Langmuir740812b2014-06-24 19:37:16 +0000370 return EC; // name not seen before
371 }
372 llvm_unreachable("returned above");
373 }
374
375public:
376 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
377 std::error_code &EC)
378 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
379 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
380 EC = incrementImpl(true);
381 }
382
383 std::error_code increment() override { return incrementImpl(false); }
384};
385} // end anonymous namespace
386
387directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
388 std::error_code &EC) {
389 return directory_iterator(
390 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
391}
392
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000393namespace clang {
394namespace vfs {
395namespace detail {
396
397enum InMemoryNodeKind { IME_File, IME_Directory };
398
399/// The in memory file system is a tree of Nodes. Every node can either be a
400/// file or a directory.
401class InMemoryNode {
402 Status Stat;
403 InMemoryNodeKind Kind;
404
405public:
406 InMemoryNode(Status Stat, InMemoryNodeKind Kind)
407 : Stat(std::move(Stat)), Kind(Kind) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000408 virtual ~InMemoryNode() {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000409 const Status &getStatus() const { return Stat; }
410 InMemoryNodeKind getKind() const { return Kind; }
411 virtual std::string toString(unsigned Indent) const = 0;
412};
413
414namespace {
415class InMemoryFile : public InMemoryNode {
416 std::unique_ptr<llvm::MemoryBuffer> Buffer;
417
418public:
419 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
420 : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
421
422 llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
423 std::string toString(unsigned Indent) const override {
424 return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
425 }
426 static bool classof(const InMemoryNode *N) {
427 return N->getKind() == IME_File;
428 }
429};
430
431/// Adapt a InMemoryFile for VFS' File interface.
432class InMemoryFileAdaptor : public File {
433 InMemoryFile &Node;
434
435public:
436 explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
437
438 llvm::ErrorOr<Status> status() override { return Node.getStatus(); }
439 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +0000440 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
441 bool IsVolatile) override {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000442 llvm::MemoryBuffer *Buf = Node.getBuffer();
443 return llvm::MemoryBuffer::getMemBuffer(
444 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
445 }
446 std::error_code close() override { return std::error_code(); }
447};
448} // end anonymous namespace
449
450class InMemoryDirectory : public InMemoryNode {
451 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
452
453public:
454 InMemoryDirectory(Status Stat)
455 : InMemoryNode(std::move(Stat), IME_Directory) {}
456 InMemoryNode *getChild(StringRef Name) {
457 auto I = Entries.find(Name);
458 if (I != Entries.end())
459 return I->second.get();
460 return nullptr;
461 }
462 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
463 return Entries.insert(make_pair(Name, std::move(Child)))
464 .first->second.get();
465 }
466
467 typedef decltype(Entries)::const_iterator const_iterator;
468 const_iterator begin() const { return Entries.begin(); }
469 const_iterator end() const { return Entries.end(); }
470
471 std::string toString(unsigned Indent) const override {
472 std::string Result =
473 (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
474 for (const auto &Entry : Entries) {
475 Result += Entry.second->toString(Indent + 2);
476 }
477 return Result;
478 }
479 static bool classof(const InMemoryNode *N) {
480 return N->getKind() == IME_Directory;
481 }
482};
483}
484
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000485InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000486 : Root(new detail::InMemoryDirectory(
487 Status("", getNextVirtualUniqueID(), llvm::sys::TimeValue::MinTime(),
488 0, 0, 0, llvm::sys::fs::file_type::directory_file,
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000489 llvm::sys::fs::perms::all_all))),
490 UseNormalizedPaths(UseNormalizedPaths) {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000491
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000492InMemoryFileSystem::~InMemoryFileSystem() {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000493
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000494std::string InMemoryFileSystem::toString() const {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000495 return Root->toString(/*Indent=*/0);
496}
497
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000498bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000499 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
500 SmallString<128> Path;
501 P.toVector(Path);
502
503 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000504 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000505 assert(!EC);
506 (void)EC;
507
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000508 if (useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000509 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000510
511 if (Path.empty())
512 return false;
513
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000514 detail::InMemoryDirectory *Dir = Root.get();
515 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
516 while (true) {
517 StringRef Name = *I;
518 detail::InMemoryNode *Node = Dir->getChild(Name);
519 ++I;
520 if (!Node) {
521 if (I == E) {
522 // End of the path, create a new file.
523 // FIXME: expose the status details in the interface.
Benjamin Kramer1b8dbe32015-10-06 14:45:16 +0000524 Status Stat(P.str(), getNextVirtualUniqueID(),
Benjamin Kramer6b618052015-10-05 14:02:15 +0000525 llvm::sys::TimeValue(ModificationTime, 0), 0, 0,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000526 Buffer->getBufferSize(),
527 llvm::sys::fs::file_type::regular_file,
528 llvm::sys::fs::all_all);
529 Dir->addChild(Name, llvm::make_unique<detail::InMemoryFile>(
530 std::move(Stat), std::move(Buffer)));
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000531 return true;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000532 }
533
534 // Create a new directory. Use the path up to here.
535 // FIXME: expose the status details in the interface.
536 Status Stat(
537 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Benjamin Kramer6b618052015-10-05 14:02:15 +0000538 getNextVirtualUniqueID(), llvm::sys::TimeValue(ModificationTime, 0),
539 0, 0, Buffer->getBufferSize(),
540 llvm::sys::fs::file_type::directory_file, llvm::sys::fs::all_all);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000541 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
542 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
543 continue;
544 }
545
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000546 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000547 Dir = NewDir;
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000548 } else {
549 assert(isa<detail::InMemoryFile>(Node) &&
550 "Must be either file or directory!");
551
552 // Trying to insert a directory in place of a file.
553 if (I != E)
554 return false;
555
556 // Return false only if the new file is different from the existing one.
557 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
558 Buffer->getBuffer();
559 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000560 }
561}
562
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000563bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000564 llvm::MemoryBuffer *Buffer) {
565 return addFile(P, ModificationTime,
566 llvm::MemoryBuffer::getMemBuffer(
567 Buffer->getBuffer(), Buffer->getBufferIdentifier()));
568}
569
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000570static ErrorOr<detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000571lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
572 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000573 SmallString<128> Path;
574 P.toVector(Path);
575
576 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000577 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000578 assert(!EC);
579 (void)EC;
580
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000581 if (FS.useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000582 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer4ad1c432015-10-12 13:30:38 +0000583
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000584 if (Path.empty())
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000585 return Dir;
586
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000587 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000588 while (true) {
589 detail::InMemoryNode *Node = Dir->getChild(*I);
590 ++I;
591 if (!Node)
592 return errc::no_such_file_or_directory;
593
594 // Return the file if it's at the end of the path.
595 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
596 if (I == E)
597 return File;
598 return errc::no_such_file_or_directory;
599 }
600
601 // Traverse directories.
602 Dir = cast<detail::InMemoryDirectory>(Node);
603 if (I == E)
604 return Dir;
605 }
606}
607
608llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000609 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000610 if (Node)
611 return (*Node)->getStatus();
612 return Node.getError();
613}
614
615llvm::ErrorOr<std::unique_ptr<File>>
616InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000617 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000618 if (!Node)
619 return Node.getError();
620
621 // When we have a file provide a heap-allocated wrapper for the memory buffer
622 // to match the ownership semantics for File.
623 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
624 return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
625
626 // FIXME: errc::not_a_file?
627 return make_error_code(llvm::errc::invalid_argument);
628}
629
630namespace {
631/// Adaptor from InMemoryDir::iterator to directory_iterator.
632class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
633 detail::InMemoryDirectory::const_iterator I;
634 detail::InMemoryDirectory::const_iterator E;
635
636public:
637 InMemoryDirIterator() {}
638 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
639 : I(Dir.begin()), E(Dir.end()) {
640 if (I != E)
641 CurrentEntry = I->second->getStatus();
642 }
643
644 std::error_code increment() override {
645 ++I;
646 // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
647 // the rest.
648 CurrentEntry = I != E ? I->second->getStatus() : Status();
649 return std::error_code();
650 }
651};
652} // end anonymous namespace
653
654directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
655 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000656 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000657 if (!Node) {
658 EC = Node.getError();
659 return directory_iterator(std::make_shared<InMemoryDirIterator>());
660 }
661
662 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
663 return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
664
665 EC = make_error_code(llvm::errc::not_a_directory);
666 return directory_iterator(std::make_shared<InMemoryDirIterator>());
667}
Benjamin Kramere9e76072016-01-09 16:33:16 +0000668
669std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
670 SmallString<128> Path;
671 P.toVector(Path);
672
673 // Fix up relative paths. This just prepends the current working directory.
674 std::error_code EC = makeAbsolute(Path);
675 assert(!EC);
676 (void)EC;
677
678 if (useNormalizedPaths())
679 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
680
681 if (!Path.empty())
682 WorkingDirectory = Path.str();
683 return std::error_code();
684}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000685}
686}
687
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000688//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000689// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000690//===-----------------------------------------------------------------------===/
691
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000692namespace {
693
694enum EntryKind {
695 EK_Directory,
696 EK_File
697};
698
699/// \brief A single file or directory in the VFS.
700class Entry {
701 EntryKind Kind;
702 std::string Name;
703
704public:
705 virtual ~Entry();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000706 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
707 StringRef getName() const { return Name; }
708 EntryKind getKind() const { return Kind; }
709};
710
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000711class RedirectingDirectoryEntry : public Entry {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000712 std::vector<std::unique_ptr<Entry>> Contents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000713 Status S;
714
715public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000716 RedirectingDirectoryEntry(StringRef Name,
717 std::vector<std::unique_ptr<Entry>> Contents,
718 Status S)
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000719 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000720 S(std::move(S)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000721 Status getStatus() { return S; }
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000722 typedef decltype(Contents)::iterator iterator;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000723 iterator contents_begin() { return Contents.begin(); }
724 iterator contents_end() { return Contents.end(); }
725 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
726};
727
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000728class RedirectingFileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000729public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000730 enum NameKind {
731 NK_NotSet,
732 NK_External,
733 NK_Virtual
734 };
735private:
736 std::string ExternalContentsPath;
737 NameKind UseName;
738public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000739 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
740 NameKind UseName)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000741 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
742 UseName(UseName) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000743 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Ben Langmuirb59cf672014-02-27 00:25:12 +0000744 /// \brief whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000745 bool useExternalName(bool GlobalUseExternalName) const {
746 return UseName == NK_NotSet ? GlobalUseExternalName
747 : (UseName == NK_External);
748 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000749 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
750};
751
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000752class RedirectingFileSystem;
Ben Langmuir740812b2014-06-24 19:37:16 +0000753
754class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
755 std::string Dir;
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000756 RedirectingFileSystem &FS;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000757 RedirectingDirectoryEntry::iterator Current, End;
758
Ben Langmuir740812b2014-06-24 19:37:16 +0000759public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000760 VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000761 RedirectingDirectoryEntry::iterator Begin,
762 RedirectingDirectoryEntry::iterator End,
763 std::error_code &EC);
Ben Langmuir740812b2014-06-24 19:37:16 +0000764 std::error_code increment() override;
765};
766
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000767/// \brief A virtual file system parsed from a YAML file.
768///
769/// Currently, this class allows creating virtual directories and mapping
770/// virtual file paths to existing external files, available in \c ExternalFS.
771///
772/// The basic structure of the parsed file is:
773/// \verbatim
774/// {
775/// 'version': <version number>,
776/// <optional configuration>
777/// 'roots': [
778/// <directory entries>
779/// ]
780/// }
781/// \endverbatim
782///
783/// All configuration options are optional.
784/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000785/// 'use-external-names': <boolean, default=true>
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000786/// 'overlay-relative': <boolean, default=false>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000787///
788/// Virtual directories are represented as
789/// \verbatim
790/// {
791/// 'type': 'directory',
792/// 'name': <string>,
793/// 'contents': [ <file or directory entries> ]
794/// }
795/// \endverbatim
796///
797/// The default attributes for virtual directories are:
798/// \verbatim
799/// MTime = now() when created
800/// Perms = 0777
801/// User = Group = 0
802/// Size = 0
803/// UniqueID = unspecified unique value
804/// \endverbatim
805///
806/// Re-mapped files are represented as
807/// \verbatim
808/// {
809/// 'type': 'file',
810/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000811/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000812/// 'external-contents': <path to external file>)
813/// }
814/// \endverbatim
815///
816/// and inherit their attributes from the external contents.
817///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000818/// In both cases, the 'name' field may contain multiple path components (e.g.
819/// /path/to/file). However, any directory that contains more than one child
820/// must be uniquely represented by a directory entry.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000821class RedirectingFileSystem : public vfs::FileSystem {
822 /// The root(s) of the virtual file system.
823 std::vector<std::unique_ptr<Entry>> Roots;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000824 /// \brief The file system to use for external references.
825 IntrusiveRefCntPtr<FileSystem> ExternalFS;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000826 /// If IsRelativeOverlay is set, this represents the directory
827 /// path that should be prefixed to each 'external-contents' entry
828 /// when reading from YAML files.
829 std::string ExternalContentsPrefixDir;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000830
831 /// @name Configuration
832 /// @{
833
834 /// \brief Whether to perform case-sensitive comparisons.
835 ///
836 /// Currently, case-insensitive matching only works correctly with ASCII.
Ben Langmuirb59cf672014-02-27 00:25:12 +0000837 bool CaseSensitive;
838
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000839 /// IsRelativeOverlay marks whether a IsExternalContentsPrefixDir path must
840 /// be prefixed in every 'external-contents' when reading from YAML files.
841 bool IsRelativeOverlay = false;
842
Ben Langmuirb59cf672014-02-27 00:25:12 +0000843 /// \brief Whether to use to use the value of 'external-contents' for the
844 /// names of files. This global value is overridable on a per-file basis.
845 bool UseExternalNames;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000846 /// @}
847
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000848 /// Virtual file paths and external files could be canonicalized without "..",
849 /// "." and "./" in their paths. FIXME: some unittests currently fail on
850 /// win32 when using remove_dots and remove_leading_dotslash on paths.
851 bool UseCanonicalizedPaths =
852#ifdef LLVM_ON_WIN32
853 false;
854#else
855 true;
856#endif
857
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000858 friend class RedirectingFileSystemParser;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000859
860private:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000861 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000862 : ExternalFS(ExternalFS), CaseSensitive(true), UseExternalNames(true) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000863
864 /// \brief Looks up \p Path in \c Roots.
865 ErrorOr<Entry *> lookupPath(const Twine &Path);
866
867 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
868 /// recursing into the contents of \p From if it is a directory.
869 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
870 sys::path::const_iterator End, Entry *From);
871
Ben Langmuir740812b2014-06-24 19:37:16 +0000872 /// \brief Get the status of a given an \c Entry.
873 ErrorOr<Status> status(const Twine &Path, Entry *E);
874
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000875public:
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000876 /// \brief Parses \p Buffer, which is expected to be in YAML format and
877 /// returns a virtual file system representing its contents.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000878 static RedirectingFileSystem *
879 create(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000880 SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
881 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000882
Craig Toppera798a9d2014-03-02 09:32:10 +0000883 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000884 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000885
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000886 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
887 return ExternalFS->getCurrentWorkingDirectory();
888 }
889 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
890 return ExternalFS->setCurrentWorkingDirectory(Path);
891 }
892
Ben Langmuir740812b2014-06-24 19:37:16 +0000893 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
894 ErrorOr<Entry *> E = lookupPath(Dir);
895 if (!E) {
896 EC = E.getError();
897 return directory_iterator();
898 }
899 ErrorOr<Status> S = status(Dir, *E);
900 if (!S) {
901 EC = S.getError();
902 return directory_iterator();
903 }
904 if (!S->isDirectory()) {
905 EC = std::error_code(static_cast<int>(errc::not_a_directory),
906 std::system_category());
907 return directory_iterator();
908 }
909
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000910 auto *D = cast<RedirectingDirectoryEntry>(*E);
Ben Langmuir740812b2014-06-24 19:37:16 +0000911 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
912 *this, D->contents_begin(), D->contents_end(), EC));
913 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000914
915 void setExternalContentsPrefixDir(StringRef PrefixDir) {
916 ExternalContentsPrefixDir = PrefixDir.str();
917 }
918
919 StringRef getExternalContentsPrefixDir() const {
920 return ExternalContentsPrefixDir;
921 }
922
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000923};
924
925/// \brief A helper class to hold the common YAML parsing state.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000926class RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000927 yaml::Stream &Stream;
928
929 void error(yaml::Node *N, const Twine &Msg) {
930 Stream.printError(N, Msg);
931 }
932
933 // false on error
934 bool parseScalarString(yaml::Node *N, StringRef &Result,
935 SmallVectorImpl<char> &Storage) {
936 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
937 if (!S) {
938 error(N, "expected string");
939 return false;
940 }
941 Result = S->getValue(Storage);
942 return true;
943 }
944
945 // false on error
946 bool parseScalarBool(yaml::Node *N, bool &Result) {
947 SmallString<5> Storage;
948 StringRef Value;
949 if (!parseScalarString(N, Value, Storage))
950 return false;
951
952 if (Value.equals_lower("true") || Value.equals_lower("on") ||
953 Value.equals_lower("yes") || Value == "1") {
954 Result = true;
955 return true;
956 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
957 Value.equals_lower("no") || Value == "0") {
958 Result = false;
959 return true;
960 }
961
962 error(N, "expected boolean value");
963 return false;
964 }
965
966 struct KeyStatus {
967 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
968 bool Required;
969 bool Seen;
970 };
971 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
972
973 // false on error
974 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
975 DenseMap<StringRef, KeyStatus> &Keys) {
976 if (!Keys.count(Key)) {
977 error(KeyNode, "unknown key");
978 return false;
979 }
980 KeyStatus &S = Keys[Key];
981 if (S.Seen) {
982 error(KeyNode, Twine("duplicate key '") + Key + "'");
983 return false;
984 }
985 S.Seen = true;
986 return true;
987 }
988
989 // false on error
990 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
991 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
992 E = Keys.end();
993 I != E; ++I) {
994 if (I->second.Required && !I->second.Seen) {
995 error(Obj, Twine("missing key '") + I->first + "'");
996 return false;
997 }
998 }
999 return true;
1000 }
1001
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001002 std::unique_ptr<Entry> parseEntry(yaml::Node *N, RedirectingFileSystem *FS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001003 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
1004 if (!M) {
1005 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +00001006 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001007 }
1008
1009 KeyStatusPair Fields[] = {
1010 KeyStatusPair("name", true),
1011 KeyStatusPair("type", true),
1012 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001013 KeyStatusPair("external-contents", false),
1014 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001015 };
1016
Craig Topperac67c052015-11-30 03:11:10 +00001017 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001018
1019 bool HasContents = false; // external or otherwise
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001020 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001021 std::string ExternalContentsPath;
1022 std::string Name;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001023 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001024 EntryKind Kind;
1025
1026 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
1027 ++I) {
1028 StringRef Key;
1029 // Reuse the buffer for key and value, since we don't look at key after
1030 // parsing value.
1031 SmallString<256> Buffer;
1032 if (!parseScalarString(I->getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001033 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001034
1035 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001036 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001037
1038 StringRef Value;
1039 if (Key == "name") {
1040 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001041 return nullptr;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001042
1043 if (FS->UseCanonicalizedPaths) {
1044 SmallString<256> Path(Value);
1045 // Guarantee that old YAML files containing paths with ".." and "."
1046 // are properly canonicalized before read into the VFS.
1047 Path = sys::path::remove_leading_dotslash(Path);
1048 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1049 Name = Path.str();
1050 } else {
1051 Name = Value;
1052 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001053 } else if (Key == "type") {
1054 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001055 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001056 if (Value == "file")
1057 Kind = EK_File;
1058 else if (Value == "directory")
1059 Kind = EK_Directory;
1060 else {
1061 error(I->getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +00001062 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001063 }
1064 } else if (Key == "contents") {
1065 if (HasContents) {
1066 error(I->getKey(),
1067 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001068 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001069 }
1070 HasContents = true;
1071 yaml::SequenceNode *Contents =
1072 dyn_cast<yaml::SequenceNode>(I->getValue());
1073 if (!Contents) {
1074 // FIXME: this is only for directories, what about files?
1075 error(I->getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +00001076 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001077 }
1078
1079 for (yaml::SequenceNode::iterator I = Contents->begin(),
1080 E = Contents->end();
1081 I != E; ++I) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001082 if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001083 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001084 else
Craig Topperf1186c52014-05-08 06:41:40 +00001085 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001086 }
1087 } else if (Key == "external-contents") {
1088 if (HasContents) {
1089 error(I->getKey(),
1090 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001091 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001092 }
1093 HasContents = true;
1094 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001095 return nullptr;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001096
1097 SmallString<256> FullPath;
1098 if (FS->IsRelativeOverlay) {
1099 FullPath = FS->getExternalContentsPrefixDir();
1100 assert(!FullPath.empty() &&
1101 "External contents prefix directory must exist");
1102 llvm::sys::path::append(FullPath, Value);
1103 } else {
1104 FullPath = Value;
1105 }
1106
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001107 if (FS->UseCanonicalizedPaths) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001108 // Guarantee that old YAML files containing paths with ".." and "."
1109 // are properly canonicalized before read into the VFS.
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001110 FullPath = sys::path::remove_leading_dotslash(FullPath);
1111 sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001112 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001113 ExternalContentsPath = FullPath.str();
Ben Langmuirb59cf672014-02-27 00:25:12 +00001114 } else if (Key == "use-external-name") {
1115 bool Val;
1116 if (!parseScalarBool(I->getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001117 return nullptr;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001118 UseExternalName = Val ? RedirectingFileEntry::NK_External
1119 : RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001120 } else {
1121 llvm_unreachable("key missing from Keys");
1122 }
1123 }
1124
1125 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001126 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001127
1128 // check for missing keys
1129 if (!HasContents) {
1130 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001131 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001132 }
1133 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001134 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001135
Ben Langmuirb59cf672014-02-27 00:25:12 +00001136 // check invalid configuration
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001137 if (Kind == EK_Directory &&
1138 UseExternalName != RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001139 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001140 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001141 }
1142
Ben Langmuir93853232014-03-05 21:32:20 +00001143 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001144 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001145 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1146 while (Trimmed.size() > RootPathLen &&
1147 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001148 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1149 // Get the last component
1150 StringRef LastComponent = sys::path::filename(Trimmed);
1151
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001152 std::unique_ptr<Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001153 switch (Kind) {
1154 case EK_File:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001155 Result = llvm::make_unique<RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001156 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001157 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001158 case EK_Directory:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001159 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001160 LastComponent, std::move(EntryArrayContents),
1161 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1162 file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001163 break;
1164 }
1165
1166 StringRef Parent = sys::path::parent_path(Trimmed);
1167 if (Parent.empty())
1168 return Result;
1169
1170 // if 'name' contains multiple components, create implicit directory entries
1171 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1172 E = sys::path::rend(Parent);
1173 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001174 std::vector<std::unique_ptr<Entry>> Entries;
1175 Entries.push_back(std::move(Result));
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001176 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001177 *I, std::move(Entries),
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001178 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1179 file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001180 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001181 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001182 }
1183
1184public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001185 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001186
1187 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001188 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001189 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
1190 if (!Top) {
1191 error(Root, "expected mapping node");
1192 return false;
1193 }
1194
1195 KeyStatusPair Fields[] = {
1196 KeyStatusPair("version", true),
1197 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001198 KeyStatusPair("use-external-names", false),
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001199 KeyStatusPair("overlay-relative", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001200 KeyStatusPair("roots", true),
1201 };
1202
Craig Topperac67c052015-11-30 03:11:10 +00001203 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001204
1205 // Parse configuration and 'roots'
1206 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
1207 ++I) {
1208 SmallString<10> KeyBuffer;
1209 StringRef Key;
1210 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
1211 return false;
1212
1213 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1214 return false;
1215
1216 if (Key == "roots") {
1217 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
1218 if (!Roots) {
1219 error(I->getValue(), "expected array");
1220 return false;
1221 }
1222
1223 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
1224 I != E; ++I) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001225 if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001226 FS->Roots.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001227 else
1228 return false;
1229 }
1230 } else if (Key == "version") {
1231 StringRef VersionString;
1232 SmallString<4> Storage;
1233 if (!parseScalarString(I->getValue(), VersionString, Storage))
1234 return false;
1235 int Version;
1236 if (VersionString.getAsInteger<int>(10, Version)) {
1237 error(I->getValue(), "expected integer");
1238 return false;
1239 }
1240 if (Version < 0) {
1241 error(I->getValue(), "invalid version number");
1242 return false;
1243 }
1244 if (Version != 0) {
1245 error(I->getValue(), "version mismatch, expected 0");
1246 return false;
1247 }
1248 } else if (Key == "case-sensitive") {
1249 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
1250 return false;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001251 } else if (Key == "overlay-relative") {
1252 if (!parseScalarBool(I->getValue(), FS->IsRelativeOverlay))
1253 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001254 } else if (Key == "use-external-names") {
1255 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
1256 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001257 } else {
1258 llvm_unreachable("key missing from Keys");
1259 }
1260 }
1261
1262 if (Stream.failed())
1263 return false;
1264
1265 if (!checkMissingKeys(Top, Keys))
1266 return false;
1267 return true;
1268 }
1269};
1270} // end of anonymous namespace
1271
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001272Entry::~Entry() = default;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001273
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001274RedirectingFileSystem *
1275RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1276 SourceMgr::DiagHandlerTy DiagHandler,
1277 StringRef YAMLFilePath, void *DiagContext,
1278 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001279
1280 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001281 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001282
Ben Langmuir97882e72014-02-24 20:56:37 +00001283 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001284 yaml::document_iterator DI = Stream.begin();
1285 yaml::Node *Root = DI->getRoot();
1286 if (DI == Stream.end() || !Root) {
1287 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001288 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001289 }
1290
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001291 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001292
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001293 std::unique_ptr<RedirectingFileSystem> FS(
1294 new RedirectingFileSystem(ExternalFS));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001295
1296 if (!YAMLFilePath.empty()) {
1297 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1298 // to each 'external-contents' path.
1299 //
1300 // Example:
1301 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
1302 // yields:
1303 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1304 //
1305 SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1306 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1307 assert(!EC && "Overlay dir final path must be absolute");
1308 (void)EC;
1309 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1310 }
1311
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001312 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001313 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001314
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001315 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001316}
1317
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001318ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001319 SmallString<256> Path;
1320 Path_.toVector(Path);
1321
1322 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001323 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001324 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001325
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001326 // Canonicalize path by removing ".", "..", "./", etc components. This is
1327 // a VFS request, do bot bother about symlinks in the path components
1328 // but canonicalize in order to perform the correct entry search.
1329 if (UseCanonicalizedPaths) {
1330 Path = sys::path::remove_leading_dotslash(Path);
1331 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1332 }
1333
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001334 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001335 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001336
1337 sys::path::const_iterator Start = sys::path::begin(Path);
1338 sys::path::const_iterator End = sys::path::end(Path);
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001339 for (const std::unique_ptr<Entry> &Root : Roots) {
1340 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001341 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001342 return Result;
1343 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001344 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001345}
1346
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001347ErrorOr<Entry *>
1348RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1349 sys::path::const_iterator End, Entry *From) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001350#ifndef LLVM_ON_WIN32
1351 assert(!isTraversalComponent(*Start) &&
1352 !isTraversalComponent(From->getName()) &&
1353 "Paths should not contain traversal components");
1354#else
1355 // FIXME: this is here to support windows, remove it once canonicalized
1356 // paths become globally default.
Bruno Cardoso Lopesbe056b12016-02-23 17:06:50 +00001357 if (Start->equals("."))
1358 ++Start;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001359#endif
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001360
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001361 StringRef FromName = From->getName();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001362
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001363 // Forward the search to the next component in case this is an empty one.
1364 if (!FromName.empty()) {
1365 if (CaseSensitive ? !Start->equals(FromName)
1366 : !Start->equals_lower(FromName))
1367 // failure to match
1368 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001369
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001370 ++Start;
1371
1372 if (Start == End) {
1373 // Match!
1374 return From;
1375 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001376 }
1377
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001378 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001379 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001380 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001381
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001382 for (const std::unique_ptr<Entry> &DirEntry :
1383 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1384 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001385 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001386 return Result;
1387 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001388 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001389}
1390
Ben Langmuirf13302e2015-12-10 23:41:39 +00001391static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1392 Status ExternalStatus) {
1393 Status S = ExternalStatus;
1394 if (!UseExternalNames)
1395 S = Status::copyWithNewName(S, Path.str());
1396 S.IsVFSMapped = true;
1397 return S;
1398}
1399
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001400ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001401 assert(E != nullptr);
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001402 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001403 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001404 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuir5de00f32014-05-23 18:15:47 +00001405 if (S)
Ben Langmuirf13302e2015-12-10 23:41:39 +00001406 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1407 *S);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001408 return S;
1409 } else { // directory
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001410 auto *DE = cast<RedirectingDirectoryEntry>(E);
Ben Langmuirf13302e2015-12-10 23:41:39 +00001411 return Status::copyWithNewName(DE->getStatus(), Path.str());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001412 }
1413}
1414
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001415ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001416 ErrorOr<Entry *> Result = lookupPath(Path);
1417 if (!Result)
1418 return Result.getError();
1419 return status(Path, *Result);
1420}
1421
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001422namespace {
Ben Langmuirf13302e2015-12-10 23:41:39 +00001423/// Provide a file wrapper with an overriden status.
1424class FileWithFixedStatus : public File {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001425 std::unique_ptr<File> InnerFile;
Ben Langmuirf13302e2015-12-10 23:41:39 +00001426 Status S;
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001427
1428public:
Ben Langmuirf13302e2015-12-10 23:41:39 +00001429 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
1430 : InnerFile(std::move(InnerFile)), S(S) {}
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001431
Ben Langmuirf13302e2015-12-10 23:41:39 +00001432 ErrorOr<Status> status() override { return S; }
1433 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +00001434 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1435 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001436 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1437 IsVolatile);
1438 }
1439 std::error_code close() override { return InnerFile->close(); }
1440};
1441} // end anonymous namespace
1442
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001443ErrorOr<std::unique_ptr<File>>
1444RedirectingFileSystem::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001445 ErrorOr<Entry *> E = lookupPath(Path);
1446 if (!E)
1447 return E.getError();
1448
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001449 auto *F = dyn_cast<RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001450 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001451 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001452
Benjamin Kramera8857962014-10-26 22:44:13 +00001453 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1454 if (!Result)
1455 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001456
Ben Langmuirf13302e2015-12-10 23:41:39 +00001457 auto ExternalStatus = (*Result)->status();
1458 if (!ExternalStatus)
1459 return ExternalStatus.getError();
Ben Langmuird066d4c2014-02-28 21:16:07 +00001460
Ben Langmuirf13302e2015-12-10 23:41:39 +00001461 // FIXME: Update the status with the name and VFSMapped.
1462 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1463 *ExternalStatus);
1464 return std::unique_ptr<File>(
1465 llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001466}
1467
1468IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001469vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001470 SourceMgr::DiagHandlerTy DiagHandler,
1471 StringRef YAMLFilePath,
1472 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001473 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001474 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001475 YAMLFilePath, DiagContext, ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001476}
1477
1478UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001479 static std::atomic<unsigned> UID;
1480 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001481 // The following assumes that uint64_t max will never collide with a real
1482 // dev_t value from the OS.
1483 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1484}
Justin Bogner9c785292014-05-20 21:43:27 +00001485
Justin Bogner9c785292014-05-20 21:43:27 +00001486void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1487 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1488 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1489 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1490 Mappings.emplace_back(VirtualPath, RealPath);
1491}
1492
Justin Bogner44fa450342014-05-21 22:46:51 +00001493namespace {
1494class JSONWriter {
1495 llvm::raw_ostream &OS;
1496 SmallVector<StringRef, 16> DirStack;
1497 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
1498 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1499 bool containedIn(StringRef Parent, StringRef Path);
1500 StringRef containedPart(StringRef Parent, StringRef Path);
1501 void startDirectory(StringRef Path);
1502 void endDirectory();
1503 void writeEntry(StringRef VPath, StringRef RPath);
1504
1505public:
1506 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001507 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive,
1508 Optional<bool> IsOverlayRelative, StringRef OverlayDir);
Justin Bogner44fa450342014-05-21 22:46:51 +00001509};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001510}
Justin Bogner9c785292014-05-20 21:43:27 +00001511
Justin Bogner44fa450342014-05-21 22:46:51 +00001512bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001513 using namespace llvm::sys;
1514 // Compare each path component.
1515 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1516 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1517 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1518 if (*IParent != *IChild)
1519 return false;
1520 }
1521 // Have we exhausted the parent path?
1522 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001523}
1524
Justin Bogner44fa450342014-05-21 22:46:51 +00001525StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1526 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001527 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001528 return Path.slice(Parent.size() + 1, StringRef::npos);
1529}
1530
Justin Bogner44fa450342014-05-21 22:46:51 +00001531void JSONWriter::startDirectory(StringRef Path) {
1532 StringRef Name =
1533 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1534 DirStack.push_back(Path);
1535 unsigned Indent = getDirIndent();
1536 OS.indent(Indent) << "{\n";
1537 OS.indent(Indent + 2) << "'type': 'directory',\n";
1538 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1539 OS.indent(Indent + 2) << "'contents': [\n";
1540}
1541
1542void JSONWriter::endDirectory() {
1543 unsigned Indent = getDirIndent();
1544 OS.indent(Indent + 2) << "]\n";
1545 OS.indent(Indent) << "}";
1546
1547 DirStack.pop_back();
1548}
1549
1550void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1551 unsigned Indent = getFileIndent();
1552 OS.indent(Indent) << "{\n";
1553 OS.indent(Indent + 2) << "'type': 'file',\n";
1554 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1555 OS.indent(Indent + 2) << "'external-contents': \""
1556 << llvm::yaml::escape(RPath) << "\"\n";
1557 OS.indent(Indent) << "}";
1558}
1559
1560void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001561 Optional<bool> IsCaseSensitive,
1562 Optional<bool> IsOverlayRelative,
1563 StringRef OverlayDir) {
Justin Bogner44fa450342014-05-21 22:46:51 +00001564 using namespace llvm::sys;
1565
1566 OS << "{\n"
1567 " 'version': 0,\n";
1568 if (IsCaseSensitive.hasValue())
1569 OS << " 'case-sensitive': '"
1570 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001571 bool UseOverlayRelative = false;
1572 if (IsOverlayRelative.hasValue()) {
1573 UseOverlayRelative = IsOverlayRelative.getValue();
1574 OS << " 'overlay-relative': '"
1575 << (UseOverlayRelative ? "true" : "false") << "',\n";
1576 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001577 OS << " 'roots': [\n";
1578
Justin Bogner73466402014-07-15 01:24:35 +00001579 if (!Entries.empty()) {
1580 const YAMLVFSEntry &Entry = Entries.front();
1581 startDirectory(path::parent_path(Entry.VPath));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001582
1583 StringRef RPath = Entry.RPath;
1584 if (UseOverlayRelative) {
1585 unsigned OverlayDirLen = OverlayDir.size();
1586 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1587 "Overlay dir must be contained in RPath");
1588 RPath = RPath.slice(OverlayDirLen, RPath.size());
1589 }
1590
1591 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001592
Justin Bogner73466402014-07-15 01:24:35 +00001593 for (const auto &Entry : Entries.slice(1)) {
1594 StringRef Dir = path::parent_path(Entry.VPath);
1595 if (Dir == DirStack.back())
1596 OS << ",\n";
1597 else {
1598 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1599 OS << "\n";
1600 endDirectory();
1601 }
1602 OS << ",\n";
1603 startDirectory(Dir);
1604 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001605 StringRef RPath = Entry.RPath;
1606 if (UseOverlayRelative) {
1607 unsigned OverlayDirLen = OverlayDir.size();
1608 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1609 "Overlay dir must be contained in RPath");
1610 RPath = RPath.slice(OverlayDirLen, RPath.size());
1611 }
1612 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner73466402014-07-15 01:24:35 +00001613 }
1614
1615 while (!DirStack.empty()) {
1616 OS << "\n";
1617 endDirectory();
1618 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001619 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001620 }
1621
Justin Bogner73466402014-07-15 01:24:35 +00001622 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001623 << "}\n";
1624}
1625
Justin Bogner9c785292014-05-20 21:43:27 +00001626void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1627 std::sort(Mappings.begin(), Mappings.end(),
Justin Bogner44fa450342014-05-21 22:46:51 +00001628 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001629 return LHS.VPath < RHS.VPath;
1630 });
1631
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001632 JSONWriter(OS).write(Mappings, IsCaseSensitive, IsOverlayRelative,
1633 OverlayDir);
Justin Bogner9c785292014-05-20 21:43:27 +00001634}
Ben Langmuir740812b2014-06-24 19:37:16 +00001635
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001636VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1637 const Twine &_Path, RedirectingFileSystem &FS,
1638 RedirectingDirectoryEntry::iterator Begin,
1639 RedirectingDirectoryEntry::iterator End, std::error_code &EC)
Ben Langmuir740812b2014-06-24 19:37:16 +00001640 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
1641 if (Current != End) {
1642 SmallString<128> PathStr(Dir);
1643 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001644 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001645 if (S)
1646 CurrentEntry = *S;
1647 else
1648 EC = S.getError();
1649 }
1650}
1651
1652std::error_code VFSFromYamlDirIterImpl::increment() {
1653 assert(Current != End && "cannot iterate past end");
1654 if (++Current != End) {
1655 SmallString<128> PathStr(Dir);
1656 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001657 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001658 if (!S)
1659 return S.getError();
1660 CurrentEntry = *S;
1661 } else {
1662 CurrentEntry = Status();
1663 }
1664 return std::error_code();
1665}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001666
1667vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1668 const Twine &Path,
1669 std::error_code &EC)
1670 : FS(&FS_) {
1671 directory_iterator I = FS->dir_begin(Path, EC);
1672 if (!EC && I != directory_iterator()) {
1673 State = std::make_shared<IterState>();
1674 State->push(I);
1675 }
1676}
1677
1678vfs::recursive_directory_iterator &
1679recursive_directory_iterator::increment(std::error_code &EC) {
1680 assert(FS && State && !State->empty() && "incrementing past end");
1681 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1682 vfs::directory_iterator End;
1683 if (State->top()->isDirectory()) {
1684 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
1685 if (EC)
1686 return *this;
1687 if (I != End) {
1688 State->push(I);
1689 return *this;
1690 }
1691 }
1692
1693 while (!State->empty() && State->top().increment(EC) == End)
1694 State->pop();
1695
1696 if (State->empty())
1697 State.reset(); // end iterator
1698
1699 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001700}