blob: 6977f400287fa78893416fcc61ddeb5128b21993 [file] [log] [blame]
Ben Langmuirc8130a72014-02-20 21:59:23 +00001//===- VirtualFileSystem.cpp - Virtual File System Layer --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// This file implements the VirtualFileSystem interface.
10//===----------------------------------------------------------------------===//
11
12#include "clang/Basic/VirtualFileSystem.h"
Benjamin Kramer71ce3762015-10-12 16:16:39 +000013#include "clang/Basic/FileManager.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000014#include "llvm/ADT/DenseMap.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000015#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/StringExtras.h"
Ben Langmuir740812b2014-06-24 19:37:16 +000017#include "llvm/ADT/StringSet.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "llvm/ADT/iterator_range.h"
Rafael Espindola71de0b62014-06-13 17:20:50 +000019#include "llvm/Support/Errc.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000020#include "llvm/Support/MemoryBuffer.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000021#include "llvm/Support/Path.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000022#include "llvm/Support/YAMLParser.h"
Benjamin Kramerd6bbee72015-10-05 14:06:36 +000023#include "llvm/Config/llvm-config.h"
Benjamin Kramer4527fb22014-03-02 17:08:31 +000024#include <atomic>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000025#include <memory>
Ben Langmuirc8130a72014-02-20 21:59:23 +000026
Benjamin Kramerd6bbee72015-10-05 14:06:36 +000027// For chdir.
28#ifdef LLVM_ON_WIN32
29# include <direct.h>
30#else
31# include <unistd.h>
32#endif
33
Ben Langmuirc8130a72014-02-20 21:59:23 +000034using namespace clang;
35using namespace clang::vfs;
36using namespace llvm;
37using llvm::sys::fs::file_status;
38using llvm::sys::fs::file_type;
39using llvm::sys::fs::perms;
40using llvm::sys::fs::UniqueID;
41
42Status::Status(const file_status &Status)
43 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
44 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
Ben Langmuir5de00f32014-05-23 18:15:47 +000045 Type(Status.type()), Perms(Status.permissions()), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000046
Benjamin Kramer268b51a2015-10-05 13:15:33 +000047Status::Status(StringRef Name, UniqueID UID, sys::TimeValue MTime,
48 uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
49 perms Perms)
Ben Langmuirb59cf672014-02-27 00:25:12 +000050 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
Ben Langmuir5de00f32014-05-23 18:15:47 +000051 Type(Type), Perms(Perms), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000052
Benjamin Kramer268b51a2015-10-05 13:15:33 +000053Status Status::copyWithNewName(const Status &In, StringRef NewName) {
54 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
55 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
56 In.getPermissions());
57}
58
59Status Status::copyWithNewName(const file_status &In, StringRef NewName) {
60 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
61 In.getUser(), In.getGroup(), In.getSize(), In.type(),
62 In.permissions());
63}
64
Ben Langmuirc8130a72014-02-20 21:59:23 +000065bool Status::equivalent(const Status &Other) const {
66 return getUniqueID() == Other.getUniqueID();
67}
68bool Status::isDirectory() const {
69 return Type == file_type::directory_file;
70}
71bool Status::isRegularFile() const {
72 return Type == file_type::regular_file;
73}
74bool Status::isOther() const {
75 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
76}
77bool Status::isSymlink() const {
78 return Type == file_type::symlink_file;
79}
80bool Status::isStatusKnown() const {
81 return Type != file_type::status_error;
82}
83bool Status::exists() const {
84 return isStatusKnown() && Type != file_type::file_not_found;
85}
86
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000087File::~File() {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000088
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000089FileSystem::~FileSystem() {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000090
Benjamin Kramera8857962014-10-26 22:44:13 +000091ErrorOr<std::unique_ptr<MemoryBuffer>>
92FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
93 bool RequiresNullTerminator, bool IsVolatile) {
94 auto F = openFileForRead(Name);
95 if (!F)
96 return F.getError();
Ben Langmuirc8130a72014-02-20 21:59:23 +000097
Benjamin Kramera8857962014-10-26 22:44:13 +000098 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +000099}
100
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000101std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
102 auto WorkingDir = getCurrentWorkingDirectory();
103 if (!WorkingDir)
104 return WorkingDir.getError();
105
106 return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
107}
108
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000109bool FileSystem::exists(const Twine &Path) {
110 auto Status = status(Path);
111 return Status && Status->exists();
112}
113
Ben Langmuirc8130a72014-02-20 21:59:23 +0000114//===-----------------------------------------------------------------------===/
115// RealFileSystem implementation
116//===-----------------------------------------------------------------------===/
117
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000118namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000119/// \brief Wrapper around a raw file descriptor.
120class RealFile : public File {
121 int FD;
Ben Langmuird066d4c2014-02-28 21:16:07 +0000122 Status S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000123 friend class RealFileSystem;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000124 RealFile(int FD, StringRef NewName)
125 : FD(FD), S(NewName, {}, {}, {}, {}, {},
126 llvm::sys::fs::file_type::status_error, {}) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000127 assert(FD >= 0 && "Invalid or inactive file descriptor");
128 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000129
Ben Langmuirc8130a72014-02-20 21:59:23 +0000130public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000131 ~RealFile() override;
Craig Toppera798a9d2014-03-02 09:32:10 +0000132 ErrorOr<Status> status() override;
Benjamin Kramer737501c2015-10-05 21:20:19 +0000133 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
134 int64_t FileSize,
135 bool RequiresNullTerminator,
136 bool IsVolatile) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000137 std::error_code close() override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000138};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000139} // end anonymous namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000140RealFile::~RealFile() { close(); }
Ben Langmuirc8130a72014-02-20 21:59:23 +0000141
142ErrorOr<Status> RealFile::status() {
143 assert(FD != -1 && "cannot stat closed file");
Ben Langmuird066d4c2014-02-28 21:16:07 +0000144 if (!S.isStatusKnown()) {
145 file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000146 if (std::error_code EC = sys::fs::status(FD, RealStatus))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000147 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000148 S = Status::copyWithNewName(RealStatus, S.getName());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000149 }
150 return S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000151}
152
Benjamin Kramera8857962014-10-26 22:44:13 +0000153ErrorOr<std::unique_ptr<MemoryBuffer>>
154RealFile::getBuffer(const Twine &Name, int64_t FileSize,
155 bool RequiresNullTerminator, bool IsVolatile) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000156 assert(FD != -1 && "cannot get buffer for closed file");
Benjamin Kramera8857962014-10-26 22:44:13 +0000157 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
158 IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000159}
160
161// FIXME: This is terrible, we need this for ::close.
162#if !defined(_MSC_VER) && !defined(__MINGW32__)
163#include <unistd.h>
164#include <sys/uio.h>
165#else
166#include <io.h>
167#ifndef S_ISFIFO
168#define S_ISFIFO(x) (0)
169#endif
170#endif
Rafael Espindola8e650d72014-06-12 20:37:59 +0000171std::error_code RealFile::close() {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000172 if (::close(FD))
Rafael Espindola8e650d72014-06-12 20:37:59 +0000173 return std::error_code(errno, std::generic_category());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000174 FD = -1;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000175 return std::error_code();
Ben Langmuirc8130a72014-02-20 21:59:23 +0000176}
177
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000178namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000179/// \brief The file system according to your operating system.
180class RealFileSystem : public FileSystem {
181public:
Craig Toppera798a9d2014-03-02 09:32:10 +0000182 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000183 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000184 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000185
186 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
187 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000188};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000189} // end anonymous namespace
Ben Langmuirc8130a72014-02-20 21:59:23 +0000190
191ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
192 sys::fs::file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000193 if (std::error_code EC = sys::fs::status(Path, RealStatus))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000194 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000195 return Status::copyWithNewName(RealStatus, Path.str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000196}
197
Benjamin Kramera8857962014-10-26 22:44:13 +0000198ErrorOr<std::unique_ptr<File>>
199RealFileSystem::openFileForRead(const Twine &Name) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000200 int FD;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000201 if (std::error_code EC = sys::fs::openFileForRead(Name, FD))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000202 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000203 return std::unique_ptr<File>(new RealFile(FD, Name.str()));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000204}
205
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000206llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
207 SmallString<256> Dir;
208 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
209 return EC;
210 return Dir.str().str();
211}
212
213std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
214 // FIXME: chdir is thread hostile; on the other hand, creating the same
215 // behavior as chdir is complex: chdir resolves the path once, thus
216 // guaranteeing that all subsequent relative path operations work
217 // on the same path the original chdir resulted in. This makes a
218 // difference for example on network filesystems, where symlinks might be
219 // switched during runtime of the tool. Fixing this depends on having a
220 // file system abstraction that allows openat() style interactions.
221 SmallString<256> Storage;
222 StringRef Dir = Path.toNullTerminatedStringRef(Storage);
223 if (int Err = ::chdir(Dir.data()))
224 return std::error_code(Err, std::generic_category());
225 return std::error_code();
226}
227
Ben Langmuirc8130a72014-02-20 21:59:23 +0000228IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
229 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
230 return FS;
231}
232
Ben Langmuir740812b2014-06-24 19:37:16 +0000233namespace {
234class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
235 std::string Path;
236 llvm::sys::fs::directory_iterator Iter;
237public:
238 RealFSDirIter(const Twine &_Path, std::error_code &EC)
239 : Path(_Path.str()), Iter(Path, EC) {
240 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
241 llvm::sys::fs::file_status S;
242 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000243 if (!EC)
244 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000245 }
246 }
247
248 std::error_code increment() override {
249 std::error_code EC;
250 Iter.increment(EC);
251 if (EC) {
252 return EC;
253 } else if (Iter == llvm::sys::fs::directory_iterator()) {
254 CurrentEntry = Status();
255 } else {
256 llvm::sys::fs::file_status S;
257 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000258 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000259 }
260 return EC;
261 }
262};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000263}
Ben Langmuir740812b2014-06-24 19:37:16 +0000264
265directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
266 std::error_code &EC) {
267 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
268}
269
Ben Langmuirc8130a72014-02-20 21:59:23 +0000270//===-----------------------------------------------------------------------===/
271// OverlayFileSystem implementation
272//===-----------------------------------------------------------------------===/
273OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000274 FSList.push_back(BaseFS);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000275}
276
277void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
278 FSList.push_back(FS);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000279 // Synchronize added file systems by duplicating the working directory from
280 // the first one in the list.
281 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000282}
283
284ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
285 // FIXME: handle symlinks that cross file systems
286 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
287 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000288 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000289 return Status;
290 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000291 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000292}
293
Benjamin Kramera8857962014-10-26 22:44:13 +0000294ErrorOr<std::unique_ptr<File>>
295OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000296 // FIXME: handle symlinks that cross file systems
297 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000298 auto Result = (*I)->openFileForRead(Path);
299 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
300 return Result;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000301 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000302 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000303}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000304
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000305llvm::ErrorOr<std::string>
306OverlayFileSystem::getCurrentWorkingDirectory() const {
307 // All file systems are synchronized, just take the first working directory.
308 return FSList.front()->getCurrentWorkingDirectory();
309}
310std::error_code
311OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
312 for (auto &FS : FSList)
313 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
314 return EC;
315 return std::error_code();
316}
317
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000318clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
Ben Langmuir740812b2014-06-24 19:37:16 +0000319
320namespace {
321class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
322 OverlayFileSystem &Overlays;
323 std::string Path;
324 OverlayFileSystem::iterator CurrentFS;
325 directory_iterator CurrentDirIter;
326 llvm::StringSet<> SeenNames;
327
328 std::error_code incrementFS() {
329 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
330 ++CurrentFS;
331 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
332 std::error_code EC;
333 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
334 if (EC && EC != errc::no_such_file_or_directory)
335 return EC;
336 if (CurrentDirIter != directory_iterator())
337 break; // found
338 }
339 return std::error_code();
340 }
341
342 std::error_code incrementDirIter(bool IsFirstTime) {
343 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
344 "incrementing past end");
345 std::error_code EC;
346 if (!IsFirstTime)
347 CurrentDirIter.increment(EC);
348 if (!EC && CurrentDirIter == directory_iterator())
349 EC = incrementFS();
350 return EC;
351 }
352
353 std::error_code incrementImpl(bool IsFirstTime) {
354 while (true) {
355 std::error_code EC = incrementDirIter(IsFirstTime);
356 if (EC || CurrentDirIter == directory_iterator()) {
357 CurrentEntry = Status();
358 return EC;
359 }
360 CurrentEntry = *CurrentDirIter;
361 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
David Blaikie61b86d42014-11-19 02:56:13 +0000362 if (SeenNames.insert(Name).second)
Ben Langmuir740812b2014-06-24 19:37:16 +0000363 return EC; // name not seen before
364 }
365 llvm_unreachable("returned above");
366 }
367
368public:
369 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
370 std::error_code &EC)
371 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
372 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
373 EC = incrementImpl(true);
374 }
375
376 std::error_code increment() override { return incrementImpl(false); }
377};
378} // end anonymous namespace
379
380directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
381 std::error_code &EC) {
382 return directory_iterator(
383 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
384}
385
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000386namespace clang {
387namespace vfs {
388namespace detail {
389
390enum InMemoryNodeKind { IME_File, IME_Directory };
391
392/// The in memory file system is a tree of Nodes. Every node can either be a
393/// file or a directory.
394class InMemoryNode {
395 Status Stat;
396 InMemoryNodeKind Kind;
397
398public:
399 InMemoryNode(Status Stat, InMemoryNodeKind Kind)
400 : Stat(std::move(Stat)), Kind(Kind) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000401 virtual ~InMemoryNode() {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000402 const Status &getStatus() const { return Stat; }
403 InMemoryNodeKind getKind() const { return Kind; }
404 virtual std::string toString(unsigned Indent) const = 0;
405};
406
407namespace {
408class InMemoryFile : public InMemoryNode {
409 std::unique_ptr<llvm::MemoryBuffer> Buffer;
410
411public:
412 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
413 : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
414
415 llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
416 std::string toString(unsigned Indent) const override {
417 return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
418 }
419 static bool classof(const InMemoryNode *N) {
420 return N->getKind() == IME_File;
421 }
422};
423
424/// Adapt a InMemoryFile for VFS' File interface.
425class InMemoryFileAdaptor : public File {
426 InMemoryFile &Node;
427
428public:
429 explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
430
431 llvm::ErrorOr<Status> status() override { return Node.getStatus(); }
432 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +0000433 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
434 bool IsVolatile) override {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000435 llvm::MemoryBuffer *Buf = Node.getBuffer();
436 return llvm::MemoryBuffer::getMemBuffer(
437 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
438 }
439 std::error_code close() override { return std::error_code(); }
440};
441} // end anonymous namespace
442
443class InMemoryDirectory : public InMemoryNode {
444 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
445
446public:
447 InMemoryDirectory(Status Stat)
448 : InMemoryNode(std::move(Stat), IME_Directory) {}
449 InMemoryNode *getChild(StringRef Name) {
450 auto I = Entries.find(Name);
451 if (I != Entries.end())
452 return I->second.get();
453 return nullptr;
454 }
455 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
456 return Entries.insert(make_pair(Name, std::move(Child)))
457 .first->second.get();
458 }
459
460 typedef decltype(Entries)::const_iterator const_iterator;
461 const_iterator begin() const { return Entries.begin(); }
462 const_iterator end() const { return Entries.end(); }
463
464 std::string toString(unsigned Indent) const override {
465 std::string Result =
466 (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
467 for (const auto &Entry : Entries) {
468 Result += Entry.second->toString(Indent + 2);
469 }
470 return Result;
471 }
472 static bool classof(const InMemoryNode *N) {
473 return N->getKind() == IME_Directory;
474 }
475};
476}
477
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000478InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000479 : Root(new detail::InMemoryDirectory(
480 Status("", getNextVirtualUniqueID(), llvm::sys::TimeValue::MinTime(),
481 0, 0, 0, llvm::sys::fs::file_type::directory_file,
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000482 llvm::sys::fs::perms::all_all))),
483 UseNormalizedPaths(UseNormalizedPaths) {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000484
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000485InMemoryFileSystem::~InMemoryFileSystem() {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000486
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000487std::string InMemoryFileSystem::toString() const {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000488 return Root->toString(/*Indent=*/0);
489}
490
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000491bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000492 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
493 SmallString<128> Path;
494 P.toVector(Path);
495
496 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000497 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000498 assert(!EC);
499 (void)EC;
500
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000501 if (useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000502 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000503
504 if (Path.empty())
505 return false;
506
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000507 detail::InMemoryDirectory *Dir = Root.get();
508 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
509 while (true) {
510 StringRef Name = *I;
511 detail::InMemoryNode *Node = Dir->getChild(Name);
512 ++I;
513 if (!Node) {
514 if (I == E) {
515 // End of the path, create a new file.
516 // FIXME: expose the status details in the interface.
Benjamin Kramer1b8dbe32015-10-06 14:45:16 +0000517 Status Stat(P.str(), getNextVirtualUniqueID(),
Benjamin Kramer6b618052015-10-05 14:02:15 +0000518 llvm::sys::TimeValue(ModificationTime, 0), 0, 0,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000519 Buffer->getBufferSize(),
520 llvm::sys::fs::file_type::regular_file,
521 llvm::sys::fs::all_all);
522 Dir->addChild(Name, llvm::make_unique<detail::InMemoryFile>(
523 std::move(Stat), std::move(Buffer)));
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000524 return true;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000525 }
526
527 // Create a new directory. Use the path up to here.
528 // FIXME: expose the status details in the interface.
529 Status Stat(
530 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Benjamin Kramer6b618052015-10-05 14:02:15 +0000531 getNextVirtualUniqueID(), llvm::sys::TimeValue(ModificationTime, 0),
532 0, 0, Buffer->getBufferSize(),
533 llvm::sys::fs::file_type::directory_file, llvm::sys::fs::all_all);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000534 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
535 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
536 continue;
537 }
538
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000539 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000540 Dir = NewDir;
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000541 } else {
542 assert(isa<detail::InMemoryFile>(Node) &&
543 "Must be either file or directory!");
544
545 // Trying to insert a directory in place of a file.
546 if (I != E)
547 return false;
548
549 // Return false only if the new file is different from the existing one.
550 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
551 Buffer->getBuffer();
552 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000553 }
554}
555
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000556bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000557 llvm::MemoryBuffer *Buffer) {
558 return addFile(P, ModificationTime,
559 llvm::MemoryBuffer::getMemBuffer(
560 Buffer->getBuffer(), Buffer->getBufferIdentifier()));
561}
562
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000563static ErrorOr<detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000564lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
565 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000566 SmallString<128> Path;
567 P.toVector(Path);
568
569 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000570 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000571 assert(!EC);
572 (void)EC;
573
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000574 if (FS.useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000575 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer4ad1c432015-10-12 13:30:38 +0000576
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000577 if (Path.empty())
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000578 return Dir;
579
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000580 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000581 while (true) {
582 detail::InMemoryNode *Node = Dir->getChild(*I);
583 ++I;
584 if (!Node)
585 return errc::no_such_file_or_directory;
586
587 // Return the file if it's at the end of the path.
588 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
589 if (I == E)
590 return File;
591 return errc::no_such_file_or_directory;
592 }
593
594 // Traverse directories.
595 Dir = cast<detail::InMemoryDirectory>(Node);
596 if (I == E)
597 return Dir;
598 }
599}
600
601llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000602 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000603 if (Node)
604 return (*Node)->getStatus();
605 return Node.getError();
606}
607
608llvm::ErrorOr<std::unique_ptr<File>>
609InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000610 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000611 if (!Node)
612 return Node.getError();
613
614 // When we have a file provide a heap-allocated wrapper for the memory buffer
615 // to match the ownership semantics for File.
616 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
617 return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
618
619 // FIXME: errc::not_a_file?
620 return make_error_code(llvm::errc::invalid_argument);
621}
622
623namespace {
624/// Adaptor from InMemoryDir::iterator to directory_iterator.
625class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
626 detail::InMemoryDirectory::const_iterator I;
627 detail::InMemoryDirectory::const_iterator E;
628
629public:
630 InMemoryDirIterator() {}
631 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
632 : I(Dir.begin()), E(Dir.end()) {
633 if (I != E)
634 CurrentEntry = I->second->getStatus();
635 }
636
637 std::error_code increment() override {
638 ++I;
639 // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
640 // the rest.
641 CurrentEntry = I != E ? I->second->getStatus() : Status();
642 return std::error_code();
643 }
644};
645} // end anonymous namespace
646
647directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
648 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000649 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000650 if (!Node) {
651 EC = Node.getError();
652 return directory_iterator(std::make_shared<InMemoryDirIterator>());
653 }
654
655 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
656 return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
657
658 EC = make_error_code(llvm::errc::not_a_directory);
659 return directory_iterator(std::make_shared<InMemoryDirIterator>());
660}
Benjamin Kramere9e76072016-01-09 16:33:16 +0000661
662std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
663 SmallString<128> Path;
664 P.toVector(Path);
665
666 // Fix up relative paths. This just prepends the current working directory.
667 std::error_code EC = makeAbsolute(Path);
668 assert(!EC);
669 (void)EC;
670
671 if (useNormalizedPaths())
672 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
673
674 if (!Path.empty())
675 WorkingDirectory = Path.str();
676 return std::error_code();
677}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000678}
679}
680
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000681//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000682// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000683//===-----------------------------------------------------------------------===/
684
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000685namespace {
686
687enum EntryKind {
688 EK_Directory,
689 EK_File
690};
691
692/// \brief A single file or directory in the VFS.
693class Entry {
694 EntryKind Kind;
695 std::string Name;
696
697public:
698 virtual ~Entry();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000699 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
700 StringRef getName() const { return Name; }
701 EntryKind getKind() const { return Kind; }
702};
703
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000704class RedirectingDirectoryEntry : public Entry {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000705 std::vector<std::unique_ptr<Entry>> Contents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000706 Status S;
707
708public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000709 RedirectingDirectoryEntry(StringRef Name,
710 std::vector<std::unique_ptr<Entry>> Contents,
711 Status S)
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000712 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000713 S(std::move(S)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000714 Status getStatus() { return S; }
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000715 typedef decltype(Contents)::iterator iterator;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000716 iterator contents_begin() { return Contents.begin(); }
717 iterator contents_end() { return Contents.end(); }
718 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
719};
720
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000721class RedirectingFileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000722public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000723 enum NameKind {
724 NK_NotSet,
725 NK_External,
726 NK_Virtual
727 };
728private:
729 std::string ExternalContentsPath;
730 NameKind UseName;
731public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000732 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
733 NameKind UseName)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000734 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
735 UseName(UseName) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000736 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Ben Langmuirb59cf672014-02-27 00:25:12 +0000737 /// \brief whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000738 bool useExternalName(bool GlobalUseExternalName) const {
739 return UseName == NK_NotSet ? GlobalUseExternalName
740 : (UseName == NK_External);
741 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000742 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
743};
744
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000745class RedirectingFileSystem;
Ben Langmuir740812b2014-06-24 19:37:16 +0000746
747class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
748 std::string Dir;
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000749 RedirectingFileSystem &FS;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000750 RedirectingDirectoryEntry::iterator Current, End;
751
Ben Langmuir740812b2014-06-24 19:37:16 +0000752public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000753 VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000754 RedirectingDirectoryEntry::iterator Begin,
755 RedirectingDirectoryEntry::iterator End,
756 std::error_code &EC);
Ben Langmuir740812b2014-06-24 19:37:16 +0000757 std::error_code increment() override;
758};
759
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000760/// \brief A virtual file system parsed from a YAML file.
761///
762/// Currently, this class allows creating virtual directories and mapping
763/// virtual file paths to existing external files, available in \c ExternalFS.
764///
765/// The basic structure of the parsed file is:
766/// \verbatim
767/// {
768/// 'version': <version number>,
769/// <optional configuration>
770/// 'roots': [
771/// <directory entries>
772/// ]
773/// }
774/// \endverbatim
775///
776/// All configuration options are optional.
777/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000778/// 'use-external-names': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000779///
780/// Virtual directories are represented as
781/// \verbatim
782/// {
783/// 'type': 'directory',
784/// 'name': <string>,
785/// 'contents': [ <file or directory entries> ]
786/// }
787/// \endverbatim
788///
789/// The default attributes for virtual directories are:
790/// \verbatim
791/// MTime = now() when created
792/// Perms = 0777
793/// User = Group = 0
794/// Size = 0
795/// UniqueID = unspecified unique value
796/// \endverbatim
797///
798/// Re-mapped files are represented as
799/// \verbatim
800/// {
801/// 'type': 'file',
802/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000803/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000804/// 'external-contents': <path to external file>)
805/// }
806/// \endverbatim
807///
808/// and inherit their attributes from the external contents.
809///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000810/// In both cases, the 'name' field may contain multiple path components (e.g.
811/// /path/to/file). However, any directory that contains more than one child
812/// must be uniquely represented by a directory entry.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000813class RedirectingFileSystem : public vfs::FileSystem {
814 /// The root(s) of the virtual file system.
815 std::vector<std::unique_ptr<Entry>> Roots;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000816 /// \brief The file system to use for external references.
817 IntrusiveRefCntPtr<FileSystem> ExternalFS;
818
819 /// @name Configuration
820 /// @{
821
822 /// \brief Whether to perform case-sensitive comparisons.
823 ///
824 /// Currently, case-insensitive matching only works correctly with ASCII.
Ben Langmuirb59cf672014-02-27 00:25:12 +0000825 bool CaseSensitive;
826
827 /// \brief Whether to use to use the value of 'external-contents' for the
828 /// names of files. This global value is overridable on a per-file basis.
829 bool UseExternalNames;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000830 /// @}
831
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000832 friend class RedirectingFileSystemParser;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000833
834private:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000835 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000836 : ExternalFS(ExternalFS), CaseSensitive(true), UseExternalNames(true) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000837
838 /// \brief Looks up \p Path in \c Roots.
839 ErrorOr<Entry *> lookupPath(const Twine &Path);
840
841 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
842 /// recursing into the contents of \p From if it is a directory.
843 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
844 sys::path::const_iterator End, Entry *From);
845
Ben Langmuir740812b2014-06-24 19:37:16 +0000846 /// \brief Get the status of a given an \c Entry.
847 ErrorOr<Status> status(const Twine &Path, Entry *E);
848
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000849public:
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000850 /// \brief Parses \p Buffer, which is expected to be in YAML format and
851 /// returns a virtual file system representing its contents.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000852 static RedirectingFileSystem *
853 create(std::unique_ptr<MemoryBuffer> Buffer,
854 SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext,
855 IntrusiveRefCntPtr<FileSystem> ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000856
Craig Toppera798a9d2014-03-02 09:32:10 +0000857 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000858 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000859
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000860 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
861 return ExternalFS->getCurrentWorkingDirectory();
862 }
863 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
864 return ExternalFS->setCurrentWorkingDirectory(Path);
865 }
866
Ben Langmuir740812b2014-06-24 19:37:16 +0000867 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
868 ErrorOr<Entry *> E = lookupPath(Dir);
869 if (!E) {
870 EC = E.getError();
871 return directory_iterator();
872 }
873 ErrorOr<Status> S = status(Dir, *E);
874 if (!S) {
875 EC = S.getError();
876 return directory_iterator();
877 }
878 if (!S->isDirectory()) {
879 EC = std::error_code(static_cast<int>(errc::not_a_directory),
880 std::system_category());
881 return directory_iterator();
882 }
883
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000884 auto *D = cast<RedirectingDirectoryEntry>(*E);
Ben Langmuir740812b2014-06-24 19:37:16 +0000885 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
886 *this, D->contents_begin(), D->contents_end(), EC));
887 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000888};
889
890/// \brief A helper class to hold the common YAML parsing state.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000891class RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000892 yaml::Stream &Stream;
893
894 void error(yaml::Node *N, const Twine &Msg) {
895 Stream.printError(N, Msg);
896 }
897
898 // false on error
899 bool parseScalarString(yaml::Node *N, StringRef &Result,
900 SmallVectorImpl<char> &Storage) {
901 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
902 if (!S) {
903 error(N, "expected string");
904 return false;
905 }
906 Result = S->getValue(Storage);
907 return true;
908 }
909
910 // false on error
911 bool parseScalarBool(yaml::Node *N, bool &Result) {
912 SmallString<5> Storage;
913 StringRef Value;
914 if (!parseScalarString(N, Value, Storage))
915 return false;
916
917 if (Value.equals_lower("true") || Value.equals_lower("on") ||
918 Value.equals_lower("yes") || Value == "1") {
919 Result = true;
920 return true;
921 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
922 Value.equals_lower("no") || Value == "0") {
923 Result = false;
924 return true;
925 }
926
927 error(N, "expected boolean value");
928 return false;
929 }
930
931 struct KeyStatus {
932 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
933 bool Required;
934 bool Seen;
935 };
936 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
937
938 // false on error
939 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
940 DenseMap<StringRef, KeyStatus> &Keys) {
941 if (!Keys.count(Key)) {
942 error(KeyNode, "unknown key");
943 return false;
944 }
945 KeyStatus &S = Keys[Key];
946 if (S.Seen) {
947 error(KeyNode, Twine("duplicate key '") + Key + "'");
948 return false;
949 }
950 S.Seen = true;
951 return true;
952 }
953
954 // false on error
955 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
956 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
957 E = Keys.end();
958 I != E; ++I) {
959 if (I->second.Required && !I->second.Seen) {
960 error(Obj, Twine("missing key '") + I->first + "'");
961 return false;
962 }
963 }
964 return true;
965 }
966
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000967 std::unique_ptr<Entry> parseEntry(yaml::Node *N) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000968 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
969 if (!M) {
970 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +0000971 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000972 }
973
974 KeyStatusPair Fields[] = {
975 KeyStatusPair("name", true),
976 KeyStatusPair("type", true),
977 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +0000978 KeyStatusPair("external-contents", false),
979 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000980 };
981
Craig Topperac67c052015-11-30 03:11:10 +0000982 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000983
984 bool HasContents = false; // external or otherwise
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000985 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000986 std::string ExternalContentsPath;
987 std::string Name;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000988 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000989 EntryKind Kind;
990
991 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
992 ++I) {
993 StringRef Key;
994 // Reuse the buffer for key and value, since we don't look at key after
995 // parsing value.
996 SmallString<256> Buffer;
997 if (!parseScalarString(I->getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000998 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000999
1000 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001001 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001002
1003 StringRef Value;
1004 if (Key == "name") {
1005 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001006 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001007 Name = Value;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001008 } else if (Key == "type") {
1009 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001010 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001011 if (Value == "file")
1012 Kind = EK_File;
1013 else if (Value == "directory")
1014 Kind = EK_Directory;
1015 else {
1016 error(I->getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +00001017 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001018 }
1019 } else if (Key == "contents") {
1020 if (HasContents) {
1021 error(I->getKey(),
1022 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001023 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001024 }
1025 HasContents = true;
1026 yaml::SequenceNode *Contents =
1027 dyn_cast<yaml::SequenceNode>(I->getValue());
1028 if (!Contents) {
1029 // FIXME: this is only for directories, what about files?
1030 error(I->getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +00001031 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001032 }
1033
1034 for (yaml::SequenceNode::iterator I = Contents->begin(),
1035 E = Contents->end();
1036 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001037 if (std::unique_ptr<Entry> E = parseEntry(&*I))
1038 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001039 else
Craig Topperf1186c52014-05-08 06:41:40 +00001040 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001041 }
1042 } else if (Key == "external-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 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001050 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001051 ExternalContentsPath = Value;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001052 } else if (Key == "use-external-name") {
1053 bool Val;
1054 if (!parseScalarBool(I->getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001055 return nullptr;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001056 UseExternalName = Val ? RedirectingFileEntry::NK_External
1057 : RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001058 } else {
1059 llvm_unreachable("key missing from Keys");
1060 }
1061 }
1062
1063 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001064 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001065
1066 // check for missing keys
1067 if (!HasContents) {
1068 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001069 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001070 }
1071 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001072 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001073
Ben Langmuirb59cf672014-02-27 00:25:12 +00001074 // check invalid configuration
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001075 if (Kind == EK_Directory &&
1076 UseExternalName != RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001077 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001078 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001079 }
1080
Ben Langmuir93853232014-03-05 21:32:20 +00001081 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001082 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001083 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1084 while (Trimmed.size() > RootPathLen &&
1085 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001086 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1087 // Get the last component
1088 StringRef LastComponent = sys::path::filename(Trimmed);
1089
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001090 std::unique_ptr<Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001091 switch (Kind) {
1092 case EK_File:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001093 Result = llvm::make_unique<RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001094 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001095 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001096 case EK_Directory:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001097 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001098 LastComponent, std::move(EntryArrayContents),
1099 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1100 file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001101 break;
1102 }
1103
1104 StringRef Parent = sys::path::parent_path(Trimmed);
1105 if (Parent.empty())
1106 return Result;
1107
1108 // if 'name' contains multiple components, create implicit directory entries
1109 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1110 E = sys::path::rend(Parent);
1111 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001112 std::vector<std::unique_ptr<Entry>> Entries;
1113 Entries.push_back(std::move(Result));
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001114 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001115 *I, std::move(Entries),
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001116 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1117 file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001118 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001119 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001120 }
1121
1122public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001123 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001124
1125 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001126 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001127 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
1128 if (!Top) {
1129 error(Root, "expected mapping node");
1130 return false;
1131 }
1132
1133 KeyStatusPair Fields[] = {
1134 KeyStatusPair("version", true),
1135 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001136 KeyStatusPair("use-external-names", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001137 KeyStatusPair("roots", true),
1138 };
1139
Craig Topperac67c052015-11-30 03:11:10 +00001140 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001141
1142 // Parse configuration and 'roots'
1143 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
1144 ++I) {
1145 SmallString<10> KeyBuffer;
1146 StringRef Key;
1147 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
1148 return false;
1149
1150 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1151 return false;
1152
1153 if (Key == "roots") {
1154 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
1155 if (!Roots) {
1156 error(I->getValue(), "expected array");
1157 return false;
1158 }
1159
1160 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
1161 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001162 if (std::unique_ptr<Entry> E = parseEntry(&*I))
1163 FS->Roots.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001164 else
1165 return false;
1166 }
1167 } else if (Key == "version") {
1168 StringRef VersionString;
1169 SmallString<4> Storage;
1170 if (!parseScalarString(I->getValue(), VersionString, Storage))
1171 return false;
1172 int Version;
1173 if (VersionString.getAsInteger<int>(10, Version)) {
1174 error(I->getValue(), "expected integer");
1175 return false;
1176 }
1177 if (Version < 0) {
1178 error(I->getValue(), "invalid version number");
1179 return false;
1180 }
1181 if (Version != 0) {
1182 error(I->getValue(), "version mismatch, expected 0");
1183 return false;
1184 }
1185 } else if (Key == "case-sensitive") {
1186 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
1187 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001188 } else if (Key == "use-external-names") {
1189 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
1190 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001191 } else {
1192 llvm_unreachable("key missing from Keys");
1193 }
1194 }
1195
1196 if (Stream.failed())
1197 return false;
1198
1199 if (!checkMissingKeys(Top, Keys))
1200 return false;
1201 return true;
1202 }
1203};
1204} // end of anonymous namespace
1205
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001206Entry::~Entry() = default;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001207
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001208RedirectingFileSystem *RedirectingFileSystem::create(
1209 std::unique_ptr<MemoryBuffer> Buffer, SourceMgr::DiagHandlerTy DiagHandler,
1210 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001211
1212 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001213 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001214
Ben Langmuir97882e72014-02-24 20:56:37 +00001215 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001216 yaml::document_iterator DI = Stream.begin();
1217 yaml::Node *Root = DI->getRoot();
1218 if (DI == Stream.end() || !Root) {
1219 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001220 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001221 }
1222
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001223 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001224
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001225 std::unique_ptr<RedirectingFileSystem> FS(
1226 new RedirectingFileSystem(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001227 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001228 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001229
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001230 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001231}
1232
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001233ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001234 SmallString<256> Path;
1235 Path_.toVector(Path);
1236
1237 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001238 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001239 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001240
1241 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001242 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001243
1244 sys::path::const_iterator Start = sys::path::begin(Path);
1245 sys::path::const_iterator End = sys::path::end(Path);
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001246 for (const std::unique_ptr<Entry> &Root : Roots) {
1247 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001248 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001249 return Result;
1250 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001251 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001252}
1253
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001254ErrorOr<Entry *>
1255RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1256 sys::path::const_iterator End, Entry *From) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001257 if (Start->equals("."))
1258 ++Start;
1259
1260 // FIXME: handle ..
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001261 if (CaseSensitive ? !Start->equals(From->getName())
1262 : !Start->equals_lower(From->getName()))
1263 // failure to match
Rafael Espindola71de0b62014-06-13 17:20:50 +00001264 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001265
1266 ++Start;
1267
1268 if (Start == End) {
1269 // Match!
1270 return From;
1271 }
1272
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001273 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001274 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001275 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001276
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001277 for (const std::unique_ptr<Entry> &DirEntry :
1278 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1279 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001280 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001281 return Result;
1282 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001283 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001284}
1285
Ben Langmuirf13302e2015-12-10 23:41:39 +00001286static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1287 Status ExternalStatus) {
1288 Status S = ExternalStatus;
1289 if (!UseExternalNames)
1290 S = Status::copyWithNewName(S, Path.str());
1291 S.IsVFSMapped = true;
1292 return S;
1293}
1294
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001295ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001296 assert(E != nullptr);
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001297 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001298 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001299 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuir5de00f32014-05-23 18:15:47 +00001300 if (S)
Ben Langmuirf13302e2015-12-10 23:41:39 +00001301 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1302 *S);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001303 return S;
1304 } else { // directory
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001305 auto *DE = cast<RedirectingDirectoryEntry>(E);
Ben Langmuirf13302e2015-12-10 23:41:39 +00001306 return Status::copyWithNewName(DE->getStatus(), Path.str());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001307 }
1308}
1309
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001310ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001311 ErrorOr<Entry *> Result = lookupPath(Path);
1312 if (!Result)
1313 return Result.getError();
1314 return status(Path, *Result);
1315}
1316
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001317namespace {
Ben Langmuirf13302e2015-12-10 23:41:39 +00001318/// Provide a file wrapper with an overriden status.
1319class FileWithFixedStatus : public File {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001320 std::unique_ptr<File> InnerFile;
Ben Langmuirf13302e2015-12-10 23:41:39 +00001321 Status S;
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001322
1323public:
Ben Langmuirf13302e2015-12-10 23:41:39 +00001324 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
1325 : InnerFile(std::move(InnerFile)), S(S) {}
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001326
Ben Langmuirf13302e2015-12-10 23:41:39 +00001327 ErrorOr<Status> status() override { return S; }
1328 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +00001329 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1330 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001331 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1332 IsVolatile);
1333 }
1334 std::error_code close() override { return InnerFile->close(); }
1335};
1336} // end anonymous namespace
1337
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001338ErrorOr<std::unique_ptr<File>>
1339RedirectingFileSystem::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001340 ErrorOr<Entry *> E = lookupPath(Path);
1341 if (!E)
1342 return E.getError();
1343
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001344 auto *F = dyn_cast<RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001345 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001346 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001347
Benjamin Kramera8857962014-10-26 22:44:13 +00001348 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1349 if (!Result)
1350 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001351
Ben Langmuirf13302e2015-12-10 23:41:39 +00001352 auto ExternalStatus = (*Result)->status();
1353 if (!ExternalStatus)
1354 return ExternalStatus.getError();
Ben Langmuird066d4c2014-02-28 21:16:07 +00001355
Ben Langmuirf13302e2015-12-10 23:41:39 +00001356 // FIXME: Update the status with the name and VFSMapped.
1357 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1358 *ExternalStatus);
1359 return std::unique_ptr<File>(
1360 llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001361}
1362
1363IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001364vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1365 SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001366 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001367 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
1368 DiagContext, ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001369}
1370
1371UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001372 static std::atomic<unsigned> UID;
1373 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001374 // The following assumes that uint64_t max will never collide with a real
1375 // dev_t value from the OS.
1376 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1377}
Justin Bogner9c785292014-05-20 21:43:27 +00001378
1379#ifndef NDEBUG
1380static bool pathHasTraversal(StringRef Path) {
1381 using namespace llvm::sys;
1382 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
1383 if (Comp == "." || Comp == "..")
1384 return true;
1385 return false;
1386}
1387#endif
1388
1389void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1390 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1391 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1392 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1393 Mappings.emplace_back(VirtualPath, RealPath);
1394}
1395
Justin Bogner44fa450342014-05-21 22:46:51 +00001396namespace {
1397class JSONWriter {
1398 llvm::raw_ostream &OS;
1399 SmallVector<StringRef, 16> DirStack;
1400 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
1401 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1402 bool containedIn(StringRef Parent, StringRef Path);
1403 StringRef containedPart(StringRef Parent, StringRef Path);
1404 void startDirectory(StringRef Path);
1405 void endDirectory();
1406 void writeEntry(StringRef VPath, StringRef RPath);
1407
1408public:
1409 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
1410 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive);
1411};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001412}
Justin Bogner9c785292014-05-20 21:43:27 +00001413
Justin Bogner44fa450342014-05-21 22:46:51 +00001414bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001415 using namespace llvm::sys;
1416 // Compare each path component.
1417 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1418 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1419 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1420 if (*IParent != *IChild)
1421 return false;
1422 }
1423 // Have we exhausted the parent path?
1424 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001425}
1426
Justin Bogner44fa450342014-05-21 22:46:51 +00001427StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1428 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001429 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001430 return Path.slice(Parent.size() + 1, StringRef::npos);
1431}
1432
Justin Bogner44fa450342014-05-21 22:46:51 +00001433void JSONWriter::startDirectory(StringRef Path) {
1434 StringRef Name =
1435 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1436 DirStack.push_back(Path);
1437 unsigned Indent = getDirIndent();
1438 OS.indent(Indent) << "{\n";
1439 OS.indent(Indent + 2) << "'type': 'directory',\n";
1440 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1441 OS.indent(Indent + 2) << "'contents': [\n";
1442}
1443
1444void JSONWriter::endDirectory() {
1445 unsigned Indent = getDirIndent();
1446 OS.indent(Indent + 2) << "]\n";
1447 OS.indent(Indent) << "}";
1448
1449 DirStack.pop_back();
1450}
1451
1452void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1453 unsigned Indent = getFileIndent();
1454 OS.indent(Indent) << "{\n";
1455 OS.indent(Indent + 2) << "'type': 'file',\n";
1456 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1457 OS.indent(Indent + 2) << "'external-contents': \""
1458 << llvm::yaml::escape(RPath) << "\"\n";
1459 OS.indent(Indent) << "}";
1460}
1461
1462void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
1463 Optional<bool> IsCaseSensitive) {
1464 using namespace llvm::sys;
1465
1466 OS << "{\n"
1467 " 'version': 0,\n";
1468 if (IsCaseSensitive.hasValue())
1469 OS << " 'case-sensitive': '"
1470 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
1471 OS << " 'roots': [\n";
1472
Justin Bogner73466402014-07-15 01:24:35 +00001473 if (!Entries.empty()) {
1474 const YAMLVFSEntry &Entry = Entries.front();
1475 startDirectory(path::parent_path(Entry.VPath));
Justin Bogner44fa450342014-05-21 22:46:51 +00001476 writeEntry(path::filename(Entry.VPath), Entry.RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001477
Justin Bogner73466402014-07-15 01:24:35 +00001478 for (const auto &Entry : Entries.slice(1)) {
1479 StringRef Dir = path::parent_path(Entry.VPath);
1480 if (Dir == DirStack.back())
1481 OS << ",\n";
1482 else {
1483 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1484 OS << "\n";
1485 endDirectory();
1486 }
1487 OS << ",\n";
1488 startDirectory(Dir);
1489 }
1490 writeEntry(path::filename(Entry.VPath), Entry.RPath);
1491 }
1492
1493 while (!DirStack.empty()) {
1494 OS << "\n";
1495 endDirectory();
1496 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001497 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001498 }
1499
Justin Bogner73466402014-07-15 01:24:35 +00001500 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001501 << "}\n";
1502}
1503
Justin Bogner9c785292014-05-20 21:43:27 +00001504void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1505 std::sort(Mappings.begin(), Mappings.end(),
Justin Bogner44fa450342014-05-21 22:46:51 +00001506 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001507 return LHS.VPath < RHS.VPath;
1508 });
1509
Justin Bogner44fa450342014-05-21 22:46:51 +00001510 JSONWriter(OS).write(Mappings, IsCaseSensitive);
Justin Bogner9c785292014-05-20 21:43:27 +00001511}
Ben Langmuir740812b2014-06-24 19:37:16 +00001512
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001513VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1514 const Twine &_Path, RedirectingFileSystem &FS,
1515 RedirectingDirectoryEntry::iterator Begin,
1516 RedirectingDirectoryEntry::iterator End, std::error_code &EC)
Ben Langmuir740812b2014-06-24 19:37:16 +00001517 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
1518 if (Current != End) {
1519 SmallString<128> PathStr(Dir);
1520 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001521 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001522 if (S)
1523 CurrentEntry = *S;
1524 else
1525 EC = S.getError();
1526 }
1527}
1528
1529std::error_code VFSFromYamlDirIterImpl::increment() {
1530 assert(Current != End && "cannot iterate past end");
1531 if (++Current != End) {
1532 SmallString<128> PathStr(Dir);
1533 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001534 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001535 if (!S)
1536 return S.getError();
1537 CurrentEntry = *S;
1538 } else {
1539 CurrentEntry = Status();
1540 }
1541 return std::error_code();
1542}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001543
1544vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1545 const Twine &Path,
1546 std::error_code &EC)
1547 : FS(&FS_) {
1548 directory_iterator I = FS->dir_begin(Path, EC);
1549 if (!EC && I != directory_iterator()) {
1550 State = std::make_shared<IterState>();
1551 State->push(I);
1552 }
1553}
1554
1555vfs::recursive_directory_iterator &
1556recursive_directory_iterator::increment(std::error_code &EC) {
1557 assert(FS && State && !State->empty() && "incrementing past end");
1558 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1559 vfs::directory_iterator End;
1560 if (State->top()->isDirectory()) {
1561 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
1562 if (EC)
1563 return *this;
1564 if (I != End) {
1565 State->push(I);
1566 return *this;
1567 }
1568 }
1569
1570 while (!State->empty() && State->top().increment(EC) == End)
1571 State->pop();
1572
1573 if (State->empty())
1574 State.reset(); // end iterator
1575
1576 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001577}