blob: 7cffabc67de0d6fadf0a97ce049b31c345301b50 [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"
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +000019#include "llvm/Support/Debug.h"
Rafael Espindola71de0b62014-06-13 17:20:50 +000020#include "llvm/Support/Errc.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000021#include "llvm/Support/MemoryBuffer.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000022#include "llvm/Support/Path.h"
David Majnemer6a6206d2016-03-04 05:26:14 +000023#include "llvm/Support/Process.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000024#include "llvm/Support/YAMLParser.h"
Benjamin Kramerd6bbee72015-10-05 14:06:36 +000025#include "llvm/Config/llvm-config.h"
Benjamin Kramer4527fb22014-03-02 17:08:31 +000026#include <atomic>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000027#include <memory>
Ben Langmuirc8130a72014-02-20 21:59:23 +000028
Benjamin Kramerd6bbee72015-10-05 14:06:36 +000029// For chdir.
30#ifdef LLVM_ON_WIN32
31# include <direct.h>
32#else
33# include <unistd.h>
34#endif
35
Ben Langmuirc8130a72014-02-20 21:59:23 +000036using namespace clang;
37using namespace clang::vfs;
38using namespace llvm;
39using llvm::sys::fs::file_status;
40using llvm::sys::fs::file_type;
41using llvm::sys::fs::perms;
42using llvm::sys::fs::UniqueID;
43
44Status::Status(const file_status &Status)
45 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
46 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
Ben Langmuir5de00f32014-05-23 18:15:47 +000047 Type(Status.type()), Perms(Status.permissions()), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000048
Benjamin Kramer268b51a2015-10-05 13:15:33 +000049Status::Status(StringRef Name, UniqueID UID, sys::TimeValue MTime,
50 uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
51 perms Perms)
Ben Langmuirb59cf672014-02-27 00:25:12 +000052 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
Ben Langmuir5de00f32014-05-23 18:15:47 +000053 Type(Type), Perms(Perms), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000054
Benjamin Kramer268b51a2015-10-05 13:15:33 +000055Status Status::copyWithNewName(const Status &In, StringRef NewName) {
56 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
57 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
58 In.getPermissions());
59}
60
61Status Status::copyWithNewName(const file_status &In, StringRef NewName) {
62 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
63 In.getUser(), In.getGroup(), In.getSize(), In.type(),
64 In.permissions());
65}
66
Ben Langmuirc8130a72014-02-20 21:59:23 +000067bool Status::equivalent(const Status &Other) const {
68 return getUniqueID() == Other.getUniqueID();
69}
70bool Status::isDirectory() const {
71 return Type == file_type::directory_file;
72}
73bool Status::isRegularFile() const {
74 return Type == file_type::regular_file;
75}
76bool Status::isOther() const {
77 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
78}
79bool Status::isSymlink() const {
80 return Type == file_type::symlink_file;
81}
82bool Status::isStatusKnown() const {
83 return Type != file_type::status_error;
84}
85bool Status::exists() const {
86 return isStatusKnown() && Type != file_type::file_not_found;
87}
88
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000089File::~File() {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000090
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000091FileSystem::~FileSystem() {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000092
Benjamin Kramera8857962014-10-26 22:44:13 +000093ErrorOr<std::unique_ptr<MemoryBuffer>>
94FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
95 bool RequiresNullTerminator, bool IsVolatile) {
96 auto F = openFileForRead(Name);
97 if (!F)
98 return F.getError();
Ben Langmuirc8130a72014-02-20 21:59:23 +000099
Benjamin Kramera8857962014-10-26 22:44:13 +0000100 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000101}
102
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000103std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
Bob Wilsonf43354f2016-03-26 18:55:13 +0000104 if (llvm::sys::path::is_absolute(Path))
105 return std::error_code();
106
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000107 auto WorkingDir = getCurrentWorkingDirectory();
108 if (!WorkingDir)
109 return WorkingDir.getError();
110
111 return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
112}
113
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000114bool FileSystem::exists(const Twine &Path) {
115 auto Status = status(Path);
116 return Status && Status->exists();
117}
118
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000119#ifndef NDEBUG
120static bool isTraversalComponent(StringRef Component) {
121 return Component.equals("..") || Component.equals(".");
122}
123
124static bool pathHasTraversal(StringRef Path) {
125 using namespace llvm::sys;
126 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
127 if (isTraversalComponent(Comp))
128 return true;
129 return false;
130}
131#endif
132
Ben Langmuirc8130a72014-02-20 21:59:23 +0000133//===-----------------------------------------------------------------------===/
134// RealFileSystem implementation
135//===-----------------------------------------------------------------------===/
136
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000137namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000138/// \brief Wrapper around a raw file descriptor.
139class RealFile : public File {
140 int FD;
Ben Langmuird066d4c2014-02-28 21:16:07 +0000141 Status S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000142 friend class RealFileSystem;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000143 RealFile(int FD, StringRef NewName)
144 : FD(FD), S(NewName, {}, {}, {}, {}, {},
145 llvm::sys::fs::file_type::status_error, {}) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000146 assert(FD >= 0 && "Invalid or inactive file descriptor");
147 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000148
Ben Langmuirc8130a72014-02-20 21:59:23 +0000149public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000150 ~RealFile() override;
Craig Toppera798a9d2014-03-02 09:32:10 +0000151 ErrorOr<Status> status() override;
Benjamin Kramer737501c2015-10-05 21:20:19 +0000152 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
153 int64_t FileSize,
154 bool RequiresNullTerminator,
155 bool IsVolatile) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000156 std::error_code close() override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000157};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000158} // end anonymous namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000159RealFile::~RealFile() { close(); }
Ben Langmuirc8130a72014-02-20 21:59:23 +0000160
161ErrorOr<Status> RealFile::status() {
162 assert(FD != -1 && "cannot stat closed file");
Ben Langmuird066d4c2014-02-28 21:16:07 +0000163 if (!S.isStatusKnown()) {
164 file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000165 if (std::error_code EC = sys::fs::status(FD, RealStatus))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000166 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000167 S = Status::copyWithNewName(RealStatus, S.getName());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000168 }
169 return S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000170}
171
Benjamin Kramera8857962014-10-26 22:44:13 +0000172ErrorOr<std::unique_ptr<MemoryBuffer>>
173RealFile::getBuffer(const Twine &Name, int64_t FileSize,
174 bool RequiresNullTerminator, bool IsVolatile) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000175 assert(FD != -1 && "cannot get buffer for closed file");
Benjamin Kramera8857962014-10-26 22:44:13 +0000176 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
177 IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000178}
179
Rafael Espindola8e650d72014-06-12 20:37:59 +0000180std::error_code RealFile::close() {
David Majnemer6a6206d2016-03-04 05:26:14 +0000181 std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000182 FD = -1;
David Majnemer6a6206d2016-03-04 05:26:14 +0000183 return EC;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000184}
185
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000186namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000187/// \brief The file system according to your operating system.
188class RealFileSystem : public FileSystem {
189public:
Craig Toppera798a9d2014-03-02 09:32:10 +0000190 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000191 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000192 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000193
194 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
195 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000196};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000197} // end anonymous namespace
Ben Langmuirc8130a72014-02-20 21:59:23 +0000198
199ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
200 sys::fs::file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000201 if (std::error_code EC = sys::fs::status(Path, RealStatus))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000202 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000203 return Status::copyWithNewName(RealStatus, Path.str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000204}
205
Benjamin Kramera8857962014-10-26 22:44:13 +0000206ErrorOr<std::unique_ptr<File>>
207RealFileSystem::openFileForRead(const Twine &Name) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000208 int FD;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000209 if (std::error_code EC = sys::fs::openFileForRead(Name, FD))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000210 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000211 return std::unique_ptr<File>(new RealFile(FD, Name.str()));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000212}
213
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000214llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
215 SmallString<256> Dir;
216 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
217 return EC;
218 return Dir.str().str();
219}
220
221std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
222 // FIXME: chdir is thread hostile; on the other hand, creating the same
223 // behavior as chdir is complex: chdir resolves the path once, thus
224 // guaranteeing that all subsequent relative path operations work
225 // on the same path the original chdir resulted in. This makes a
226 // difference for example on network filesystems, where symlinks might be
227 // switched during runtime of the tool. Fixing this depends on having a
228 // file system abstraction that allows openat() style interactions.
229 SmallString<256> Storage;
230 StringRef Dir = Path.toNullTerminatedStringRef(Storage);
231 if (int Err = ::chdir(Dir.data()))
232 return std::error_code(Err, std::generic_category());
233 return std::error_code();
234}
235
Ben Langmuirc8130a72014-02-20 21:59:23 +0000236IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
237 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
238 return FS;
239}
240
Ben Langmuir740812b2014-06-24 19:37:16 +0000241namespace {
242class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
243 std::string Path;
244 llvm::sys::fs::directory_iterator Iter;
245public:
246 RealFSDirIter(const Twine &_Path, std::error_code &EC)
247 : Path(_Path.str()), Iter(Path, EC) {
248 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
249 llvm::sys::fs::file_status S;
250 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000251 if (!EC)
252 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000253 }
254 }
255
256 std::error_code increment() override {
257 std::error_code EC;
258 Iter.increment(EC);
259 if (EC) {
260 return EC;
261 } else if (Iter == llvm::sys::fs::directory_iterator()) {
262 CurrentEntry = Status();
263 } else {
264 llvm::sys::fs::file_status S;
265 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000266 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000267 }
268 return EC;
269 }
270};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000271}
Ben Langmuir740812b2014-06-24 19:37:16 +0000272
273directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
274 std::error_code &EC) {
275 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
276}
277
Ben Langmuirc8130a72014-02-20 21:59:23 +0000278//===-----------------------------------------------------------------------===/
279// OverlayFileSystem implementation
280//===-----------------------------------------------------------------------===/
281OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000282 FSList.push_back(BaseFS);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000283}
284
285void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
286 FSList.push_back(FS);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000287 // Synchronize added file systems by duplicating the working directory from
288 // the first one in the list.
289 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000290}
291
292ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
293 // FIXME: handle symlinks that cross file systems
294 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
295 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000296 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000297 return Status;
298 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000299 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000300}
301
Benjamin Kramera8857962014-10-26 22:44:13 +0000302ErrorOr<std::unique_ptr<File>>
303OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000304 // FIXME: handle symlinks that cross file systems
305 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000306 auto Result = (*I)->openFileForRead(Path);
307 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
308 return Result;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000309 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000310 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000311}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000312
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000313llvm::ErrorOr<std::string>
314OverlayFileSystem::getCurrentWorkingDirectory() const {
315 // All file systems are synchronized, just take the first working directory.
316 return FSList.front()->getCurrentWorkingDirectory();
317}
318std::error_code
319OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
320 for (auto &FS : FSList)
321 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
322 return EC;
323 return std::error_code();
324}
325
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000326clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
Ben Langmuir740812b2014-06-24 19:37:16 +0000327
328namespace {
329class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
330 OverlayFileSystem &Overlays;
331 std::string Path;
332 OverlayFileSystem::iterator CurrentFS;
333 directory_iterator CurrentDirIter;
334 llvm::StringSet<> SeenNames;
335
336 std::error_code incrementFS() {
337 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
338 ++CurrentFS;
339 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
340 std::error_code EC;
341 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
342 if (EC && EC != errc::no_such_file_or_directory)
343 return EC;
344 if (CurrentDirIter != directory_iterator())
345 break; // found
346 }
347 return std::error_code();
348 }
349
350 std::error_code incrementDirIter(bool IsFirstTime) {
351 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
352 "incrementing past end");
353 std::error_code EC;
354 if (!IsFirstTime)
355 CurrentDirIter.increment(EC);
356 if (!EC && CurrentDirIter == directory_iterator())
357 EC = incrementFS();
358 return EC;
359 }
360
361 std::error_code incrementImpl(bool IsFirstTime) {
362 while (true) {
363 std::error_code EC = incrementDirIter(IsFirstTime);
364 if (EC || CurrentDirIter == directory_iterator()) {
365 CurrentEntry = Status();
366 return EC;
367 }
368 CurrentEntry = *CurrentDirIter;
369 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
David Blaikie61b86d42014-11-19 02:56:13 +0000370 if (SeenNames.insert(Name).second)
Ben Langmuir740812b2014-06-24 19:37:16 +0000371 return EC; // name not seen before
372 }
373 llvm_unreachable("returned above");
374 }
375
376public:
377 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
378 std::error_code &EC)
379 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
380 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
381 EC = incrementImpl(true);
382 }
383
384 std::error_code increment() override { return incrementImpl(false); }
385};
386} // end anonymous namespace
387
388directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
389 std::error_code &EC) {
390 return directory_iterator(
391 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
392}
393
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000394namespace clang {
395namespace vfs {
396namespace detail {
397
398enum InMemoryNodeKind { IME_File, IME_Directory };
399
400/// The in memory file system is a tree of Nodes. Every node can either be a
401/// file or a directory.
402class InMemoryNode {
403 Status Stat;
404 InMemoryNodeKind Kind;
405
406public:
407 InMemoryNode(Status Stat, InMemoryNodeKind Kind)
408 : Stat(std::move(Stat)), Kind(Kind) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000409 virtual ~InMemoryNode() {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000410 const Status &getStatus() const { return Stat; }
411 InMemoryNodeKind getKind() const { return Kind; }
412 virtual std::string toString(unsigned Indent) const = 0;
413};
414
415namespace {
416class InMemoryFile : public InMemoryNode {
417 std::unique_ptr<llvm::MemoryBuffer> Buffer;
418
419public:
420 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
421 : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
422
423 llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
424 std::string toString(unsigned Indent) const override {
425 return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
426 }
427 static bool classof(const InMemoryNode *N) {
428 return N->getKind() == IME_File;
429 }
430};
431
432/// Adapt a InMemoryFile for VFS' File interface.
433class InMemoryFileAdaptor : public File {
434 InMemoryFile &Node;
435
436public:
437 explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
438
439 llvm::ErrorOr<Status> status() override { return Node.getStatus(); }
440 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +0000441 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
442 bool IsVolatile) override {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000443 llvm::MemoryBuffer *Buf = Node.getBuffer();
444 return llvm::MemoryBuffer::getMemBuffer(
445 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
446 }
447 std::error_code close() override { return std::error_code(); }
448};
449} // end anonymous namespace
450
451class InMemoryDirectory : public InMemoryNode {
452 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
453
454public:
455 InMemoryDirectory(Status Stat)
456 : InMemoryNode(std::move(Stat), IME_Directory) {}
457 InMemoryNode *getChild(StringRef Name) {
458 auto I = Entries.find(Name);
459 if (I != Entries.end())
460 return I->second.get();
461 return nullptr;
462 }
463 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
464 return Entries.insert(make_pair(Name, std::move(Child)))
465 .first->second.get();
466 }
467
468 typedef decltype(Entries)::const_iterator const_iterator;
469 const_iterator begin() const { return Entries.begin(); }
470 const_iterator end() const { return Entries.end(); }
471
472 std::string toString(unsigned Indent) const override {
473 std::string Result =
474 (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
475 for (const auto &Entry : Entries) {
476 Result += Entry.second->toString(Indent + 2);
477 }
478 return Result;
479 }
480 static bool classof(const InMemoryNode *N) {
481 return N->getKind() == IME_Directory;
482 }
483};
484}
485
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000486InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000487 : Root(new detail::InMemoryDirectory(
488 Status("", getNextVirtualUniqueID(), llvm::sys::TimeValue::MinTime(),
489 0, 0, 0, llvm::sys::fs::file_type::directory_file,
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000490 llvm::sys::fs::perms::all_all))),
491 UseNormalizedPaths(UseNormalizedPaths) {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000492
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000493InMemoryFileSystem::~InMemoryFileSystem() {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000494
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000495std::string InMemoryFileSystem::toString() const {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000496 return Root->toString(/*Indent=*/0);
497}
498
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000499bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000500 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
501 SmallString<128> Path;
502 P.toVector(Path);
503
504 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000505 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000506 assert(!EC);
507 (void)EC;
508
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000509 if (useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000510 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000511
512 if (Path.empty())
513 return false;
514
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000515 detail::InMemoryDirectory *Dir = Root.get();
516 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
517 while (true) {
518 StringRef Name = *I;
519 detail::InMemoryNode *Node = Dir->getChild(Name);
520 ++I;
521 if (!Node) {
522 if (I == E) {
523 // End of the path, create a new file.
524 // FIXME: expose the status details in the interface.
Benjamin Kramer1b8dbe32015-10-06 14:45:16 +0000525 Status Stat(P.str(), getNextVirtualUniqueID(),
Benjamin Kramer6b618052015-10-05 14:02:15 +0000526 llvm::sys::TimeValue(ModificationTime, 0), 0, 0,
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000527 Buffer->getBufferSize(),
528 llvm::sys::fs::file_type::regular_file,
529 llvm::sys::fs::all_all);
530 Dir->addChild(Name, llvm::make_unique<detail::InMemoryFile>(
531 std::move(Stat), std::move(Buffer)));
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000532 return true;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000533 }
534
535 // Create a new directory. Use the path up to here.
536 // FIXME: expose the status details in the interface.
537 Status Stat(
538 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Benjamin Kramer6b618052015-10-05 14:02:15 +0000539 getNextVirtualUniqueID(), llvm::sys::TimeValue(ModificationTime, 0),
540 0, 0, Buffer->getBufferSize(),
541 llvm::sys::fs::file_type::directory_file, llvm::sys::fs::all_all);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000542 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
543 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
544 continue;
545 }
546
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000547 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000548 Dir = NewDir;
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000549 } else {
550 assert(isa<detail::InMemoryFile>(Node) &&
551 "Must be either file or directory!");
552
553 // Trying to insert a directory in place of a file.
554 if (I != E)
555 return false;
556
557 // Return false only if the new file is different from the existing one.
558 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
559 Buffer->getBuffer();
560 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000561 }
562}
563
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000564bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000565 llvm::MemoryBuffer *Buffer) {
566 return addFile(P, ModificationTime,
567 llvm::MemoryBuffer::getMemBuffer(
568 Buffer->getBuffer(), Buffer->getBufferIdentifier()));
569}
570
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000571static ErrorOr<detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000572lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
573 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000574 SmallString<128> Path;
575 P.toVector(Path);
576
577 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000578 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000579 assert(!EC);
580 (void)EC;
581
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000582 if (FS.useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000583 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer4ad1c432015-10-12 13:30:38 +0000584
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000585 if (Path.empty())
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000586 return Dir;
587
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000588 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000589 while (true) {
590 detail::InMemoryNode *Node = Dir->getChild(*I);
591 ++I;
592 if (!Node)
593 return errc::no_such_file_or_directory;
594
595 // Return the file if it's at the end of the path.
596 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
597 if (I == E)
598 return File;
599 return errc::no_such_file_or_directory;
600 }
601
602 // Traverse directories.
603 Dir = cast<detail::InMemoryDirectory>(Node);
604 if (I == E)
605 return Dir;
606 }
607}
608
609llvm::ErrorOr<Status> InMemoryFileSystem::status(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)->getStatus();
613 return Node.getError();
614}
615
616llvm::ErrorOr<std::unique_ptr<File>>
617InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000618 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000619 if (!Node)
620 return Node.getError();
621
622 // When we have a file provide a heap-allocated wrapper for the memory buffer
623 // to match the ownership semantics for File.
624 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
625 return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
626
627 // FIXME: errc::not_a_file?
628 return make_error_code(llvm::errc::invalid_argument);
629}
630
631namespace {
632/// Adaptor from InMemoryDir::iterator to directory_iterator.
633class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
634 detail::InMemoryDirectory::const_iterator I;
635 detail::InMemoryDirectory::const_iterator E;
636
637public:
638 InMemoryDirIterator() {}
639 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
640 : I(Dir.begin()), E(Dir.end()) {
641 if (I != E)
642 CurrentEntry = I->second->getStatus();
643 }
644
645 std::error_code increment() override {
646 ++I;
647 // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
648 // the rest.
649 CurrentEntry = I != E ? I->second->getStatus() : Status();
650 return std::error_code();
651 }
652};
653} // end anonymous namespace
654
655directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
656 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000657 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000658 if (!Node) {
659 EC = Node.getError();
660 return directory_iterator(std::make_shared<InMemoryDirIterator>());
661 }
662
663 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
664 return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
665
666 EC = make_error_code(llvm::errc::not_a_directory);
667 return directory_iterator(std::make_shared<InMemoryDirIterator>());
668}
Benjamin Kramere9e76072016-01-09 16:33:16 +0000669
670std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
671 SmallString<128> Path;
672 P.toVector(Path);
673
674 // Fix up relative paths. This just prepends the current working directory.
675 std::error_code EC = makeAbsolute(Path);
676 assert(!EC);
677 (void)EC;
678
679 if (useNormalizedPaths())
680 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
681
682 if (!Path.empty())
683 WorkingDirectory = Path.str();
684 return std::error_code();
685}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000686}
687}
688
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000689//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000690// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000691//===-----------------------------------------------------------------------===/
692
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000693namespace {
694
695enum EntryKind {
696 EK_Directory,
697 EK_File
698};
699
700/// \brief A single file or directory in the VFS.
701class Entry {
702 EntryKind Kind;
703 std::string Name;
704
705public:
706 virtual ~Entry();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000707 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
708 StringRef getName() const { return Name; }
709 EntryKind getKind() const { return Kind; }
710};
711
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000712class RedirectingDirectoryEntry : public Entry {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000713 std::vector<std::unique_ptr<Entry>> Contents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000714 Status S;
715
716public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000717 RedirectingDirectoryEntry(StringRef Name,
718 std::vector<std::unique_ptr<Entry>> Contents,
719 Status S)
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000720 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000721 S(std::move(S)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000722 Status getStatus() { return S; }
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000723 typedef decltype(Contents)::iterator iterator;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000724 iterator contents_begin() { return Contents.begin(); }
725 iterator contents_end() { return Contents.end(); }
726 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
727};
728
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000729class RedirectingFileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000730public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000731 enum NameKind {
732 NK_NotSet,
733 NK_External,
734 NK_Virtual
735 };
736private:
737 std::string ExternalContentsPath;
738 NameKind UseName;
739public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000740 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
741 NameKind UseName)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000742 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
743 UseName(UseName) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000744 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Ben Langmuirb59cf672014-02-27 00:25:12 +0000745 /// \brief whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000746 bool useExternalName(bool GlobalUseExternalName) const {
747 return UseName == NK_NotSet ? GlobalUseExternalName
748 : (UseName == NK_External);
749 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000750 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
751};
752
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000753class RedirectingFileSystem;
Ben Langmuir740812b2014-06-24 19:37:16 +0000754
755class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
756 std::string Dir;
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000757 RedirectingFileSystem &FS;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000758 RedirectingDirectoryEntry::iterator Current, End;
759
Ben Langmuir740812b2014-06-24 19:37:16 +0000760public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000761 VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000762 RedirectingDirectoryEntry::iterator Begin,
763 RedirectingDirectoryEntry::iterator End,
764 std::error_code &EC);
Ben Langmuir740812b2014-06-24 19:37:16 +0000765 std::error_code increment() override;
766};
767
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000768/// \brief A virtual file system parsed from a YAML file.
769///
770/// Currently, this class allows creating virtual directories and mapping
771/// virtual file paths to existing external files, available in \c ExternalFS.
772///
773/// The basic structure of the parsed file is:
774/// \verbatim
775/// {
776/// 'version': <version number>,
777/// <optional configuration>
778/// 'roots': [
779/// <directory entries>
780/// ]
781/// }
782/// \endverbatim
783///
784/// All configuration options are optional.
785/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000786/// 'use-external-names': <boolean, default=true>
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000787/// 'overlay-relative': <boolean, default=false>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000788///
789/// Virtual directories are represented as
790/// \verbatim
791/// {
792/// 'type': 'directory',
793/// 'name': <string>,
794/// 'contents': [ <file or directory entries> ]
795/// }
796/// \endverbatim
797///
798/// The default attributes for virtual directories are:
799/// \verbatim
800/// MTime = now() when created
801/// Perms = 0777
802/// User = Group = 0
803/// Size = 0
804/// UniqueID = unspecified unique value
805/// \endverbatim
806///
807/// Re-mapped files are represented as
808/// \verbatim
809/// {
810/// 'type': 'file',
811/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000812/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000813/// 'external-contents': <path to external file>)
814/// }
815/// \endverbatim
816///
817/// and inherit their attributes from the external contents.
818///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000819/// In both cases, the 'name' field may contain multiple path components (e.g.
820/// /path/to/file). However, any directory that contains more than one child
821/// must be uniquely represented by a directory entry.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000822class RedirectingFileSystem : public vfs::FileSystem {
823 /// The root(s) of the virtual file system.
824 std::vector<std::unique_ptr<Entry>> Roots;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000825 /// \brief The file system to use for external references.
826 IntrusiveRefCntPtr<FileSystem> ExternalFS;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000827 /// If IsRelativeOverlay is set, this represents the directory
828 /// path that should be prefixed to each 'external-contents' entry
829 /// when reading from YAML files.
830 std::string ExternalContentsPrefixDir;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000831
832 /// @name Configuration
833 /// @{
834
835 /// \brief Whether to perform case-sensitive comparisons.
836 ///
837 /// Currently, case-insensitive matching only works correctly with ASCII.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000838 bool CaseSensitive = true;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000839
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000840 /// IsRelativeOverlay marks whether a IsExternalContentsPrefixDir path must
841 /// be prefixed in every 'external-contents' when reading from YAML files.
842 bool IsRelativeOverlay = false;
843
Ben Langmuirb59cf672014-02-27 00:25:12 +0000844 /// \brief Whether to use to use the value of 'external-contents' for the
845 /// names of files. This global value is overridable on a per-file basis.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000846 bool UseExternalNames = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000847 /// @}
848
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000849 /// Virtual file paths and external files could be canonicalized without "..",
850 /// "." and "./" in their paths. FIXME: some unittests currently fail on
851 /// win32 when using remove_dots and remove_leading_dotslash on paths.
852 bool UseCanonicalizedPaths =
853#ifdef LLVM_ON_WIN32
854 false;
855#else
856 true;
857#endif
858
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000859 friend class RedirectingFileSystemParser;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000860
861private:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000862 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000863 : ExternalFS(ExternalFS) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000864
865 /// \brief Looks up \p Path in \c Roots.
866 ErrorOr<Entry *> lookupPath(const Twine &Path);
867
868 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
869 /// recursing into the contents of \p From if it is a directory.
870 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
871 sys::path::const_iterator End, Entry *From);
872
Ben Langmuir740812b2014-06-24 19:37:16 +0000873 /// \brief Get the status of a given an \c Entry.
874 ErrorOr<Status> status(const Twine &Path, Entry *E);
875
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000876public:
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000877 /// \brief Parses \p Buffer, which is expected to be in YAML format and
878 /// returns a virtual file system representing its contents.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000879 static RedirectingFileSystem *
880 create(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000881 SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
882 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000883
Craig Toppera798a9d2014-03-02 09:32:10 +0000884 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000885 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000886
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000887 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
888 return ExternalFS->getCurrentWorkingDirectory();
889 }
890 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
891 return ExternalFS->setCurrentWorkingDirectory(Path);
892 }
893
Ben Langmuir740812b2014-06-24 19:37:16 +0000894 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
895 ErrorOr<Entry *> E = lookupPath(Dir);
896 if (!E) {
897 EC = E.getError();
898 return directory_iterator();
899 }
900 ErrorOr<Status> S = status(Dir, *E);
901 if (!S) {
902 EC = S.getError();
903 return directory_iterator();
904 }
905 if (!S->isDirectory()) {
906 EC = std::error_code(static_cast<int>(errc::not_a_directory),
907 std::system_category());
908 return directory_iterator();
909 }
910
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000911 auto *D = cast<RedirectingDirectoryEntry>(*E);
Ben Langmuir740812b2014-06-24 19:37:16 +0000912 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
913 *this, D->contents_begin(), D->contents_end(), EC));
914 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000915
916 void setExternalContentsPrefixDir(StringRef PrefixDir) {
917 ExternalContentsPrefixDir = PrefixDir.str();
918 }
919
920 StringRef getExternalContentsPrefixDir() const {
921 return ExternalContentsPrefixDir;
922 }
923
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +0000924#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
925LLVM_DUMP_METHOD void dump() const {
926 for (const std::unique_ptr<Entry> &Root : Roots)
927 dumpEntry(Root.get());
928 }
929
930LLVM_DUMP_METHOD void dumpEntry(Entry *E, int NumSpaces = 0) const {
931 StringRef Name = E->getName();
932 for (int i = 0, e = NumSpaces; i < e; ++i)
933 dbgs() << " ";
934 dbgs() << "'" << Name.str().c_str() << "'" << "\n";
935
936 if (E->getKind() == EK_Directory) {
937 auto *DE = dyn_cast<RedirectingDirectoryEntry>(E);
938 assert(DE && "Should be a directory");
939
940 for (std::unique_ptr<Entry> &SubEntry :
941 llvm::make_range(DE->contents_begin(), DE->contents_end()))
942 dumpEntry(SubEntry.get(), NumSpaces+2);
943 }
944 }
945#endif
946
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000947};
948
949/// \brief A helper class to hold the common YAML parsing state.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000950class RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000951 yaml::Stream &Stream;
952
953 void error(yaml::Node *N, const Twine &Msg) {
954 Stream.printError(N, Msg);
955 }
956
957 // false on error
958 bool parseScalarString(yaml::Node *N, StringRef &Result,
959 SmallVectorImpl<char> &Storage) {
960 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
961 if (!S) {
962 error(N, "expected string");
963 return false;
964 }
965 Result = S->getValue(Storage);
966 return true;
967 }
968
969 // false on error
970 bool parseScalarBool(yaml::Node *N, bool &Result) {
971 SmallString<5> Storage;
972 StringRef Value;
973 if (!parseScalarString(N, Value, Storage))
974 return false;
975
976 if (Value.equals_lower("true") || Value.equals_lower("on") ||
977 Value.equals_lower("yes") || Value == "1") {
978 Result = true;
979 return true;
980 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
981 Value.equals_lower("no") || Value == "0") {
982 Result = false;
983 return true;
984 }
985
986 error(N, "expected boolean value");
987 return false;
988 }
989
990 struct KeyStatus {
991 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
992 bool Required;
993 bool Seen;
994 };
995 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
996
997 // false on error
998 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
999 DenseMap<StringRef, KeyStatus> &Keys) {
1000 if (!Keys.count(Key)) {
1001 error(KeyNode, "unknown key");
1002 return false;
1003 }
1004 KeyStatus &S = Keys[Key];
1005 if (S.Seen) {
1006 error(KeyNode, Twine("duplicate key '") + Key + "'");
1007 return false;
1008 }
1009 S.Seen = true;
1010 return true;
1011 }
1012
1013 // false on error
1014 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
1015 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
1016 E = Keys.end();
1017 I != E; ++I) {
1018 if (I->second.Required && !I->second.Seen) {
1019 error(Obj, Twine("missing key '") + I->first + "'");
1020 return false;
1021 }
1022 }
1023 return true;
1024 }
1025
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001026 std::unique_ptr<Entry> parseEntry(yaml::Node *N, RedirectingFileSystem *FS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001027 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
1028 if (!M) {
1029 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +00001030 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001031 }
1032
1033 KeyStatusPair Fields[] = {
1034 KeyStatusPair("name", true),
1035 KeyStatusPair("type", true),
1036 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001037 KeyStatusPair("external-contents", false),
1038 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001039 };
1040
Craig Topperac67c052015-11-30 03:11:10 +00001041 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001042
1043 bool HasContents = false; // external or otherwise
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001044 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001045 std::string ExternalContentsPath;
1046 std::string Name;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001047 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001048 EntryKind Kind;
1049
1050 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
1051 ++I) {
1052 StringRef Key;
1053 // Reuse the buffer for key and value, since we don't look at key after
1054 // parsing value.
1055 SmallString<256> Buffer;
1056 if (!parseScalarString(I->getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001057 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001058
1059 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001060 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001061
1062 StringRef Value;
1063 if (Key == "name") {
1064 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001065 return nullptr;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001066
1067 if (FS->UseCanonicalizedPaths) {
1068 SmallString<256> Path(Value);
1069 // Guarantee that old YAML files containing paths with ".." and "."
1070 // are properly canonicalized before read into the VFS.
1071 Path = sys::path::remove_leading_dotslash(Path);
1072 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1073 Name = Path.str();
1074 } else {
1075 Name = Value;
1076 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001077 } else if (Key == "type") {
1078 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001079 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001080 if (Value == "file")
1081 Kind = EK_File;
1082 else if (Value == "directory")
1083 Kind = EK_Directory;
1084 else {
1085 error(I->getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +00001086 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001087 }
1088 } else if (Key == "contents") {
1089 if (HasContents) {
1090 error(I->getKey(),
1091 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001092 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001093 }
1094 HasContents = true;
1095 yaml::SequenceNode *Contents =
1096 dyn_cast<yaml::SequenceNode>(I->getValue());
1097 if (!Contents) {
1098 // FIXME: this is only for directories, what about files?
1099 error(I->getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +00001100 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001101 }
1102
1103 for (yaml::SequenceNode::iterator I = Contents->begin(),
1104 E = Contents->end();
1105 I != E; ++I) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001106 if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001107 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001108 else
Craig Topperf1186c52014-05-08 06:41:40 +00001109 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001110 }
1111 } else if (Key == "external-contents") {
1112 if (HasContents) {
1113 error(I->getKey(),
1114 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001115 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001116 }
1117 HasContents = true;
1118 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001119 return nullptr;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001120
1121 SmallString<256> FullPath;
1122 if (FS->IsRelativeOverlay) {
1123 FullPath = FS->getExternalContentsPrefixDir();
1124 assert(!FullPath.empty() &&
1125 "External contents prefix directory must exist");
1126 llvm::sys::path::append(FullPath, Value);
1127 } else {
1128 FullPath = Value;
1129 }
1130
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001131 if (FS->UseCanonicalizedPaths) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001132 // Guarantee that old YAML files containing paths with ".." and "."
1133 // are properly canonicalized before read into the VFS.
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001134 FullPath = sys::path::remove_leading_dotslash(FullPath);
1135 sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001136 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001137 ExternalContentsPath = FullPath.str();
Ben Langmuirb59cf672014-02-27 00:25:12 +00001138 } else if (Key == "use-external-name") {
1139 bool Val;
1140 if (!parseScalarBool(I->getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001141 return nullptr;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001142 UseExternalName = Val ? RedirectingFileEntry::NK_External
1143 : RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001144 } else {
1145 llvm_unreachable("key missing from Keys");
1146 }
1147 }
1148
1149 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001150 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001151
1152 // check for missing keys
1153 if (!HasContents) {
1154 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001155 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001156 }
1157 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001158 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001159
Ben Langmuirb59cf672014-02-27 00:25:12 +00001160 // check invalid configuration
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001161 if (Kind == EK_Directory &&
1162 UseExternalName != RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001163 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001164 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001165 }
1166
Ben Langmuir93853232014-03-05 21:32:20 +00001167 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001168 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001169 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1170 while (Trimmed.size() > RootPathLen &&
1171 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001172 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1173 // Get the last component
1174 StringRef LastComponent = sys::path::filename(Trimmed);
1175
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001176 std::unique_ptr<Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001177 switch (Kind) {
1178 case EK_File:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001179 Result = llvm::make_unique<RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001180 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001181 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001182 case EK_Directory:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001183 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001184 LastComponent, std::move(EntryArrayContents),
1185 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1186 file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001187 break;
1188 }
1189
1190 StringRef Parent = sys::path::parent_path(Trimmed);
1191 if (Parent.empty())
1192 return Result;
1193
1194 // if 'name' contains multiple components, create implicit directory entries
1195 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1196 E = sys::path::rend(Parent);
1197 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001198 std::vector<std::unique_ptr<Entry>> Entries;
1199 Entries.push_back(std::move(Result));
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001200 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001201 *I, std::move(Entries),
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001202 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1203 file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001204 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001205 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001206 }
1207
1208public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001209 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001210
1211 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001212 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001213 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
1214 if (!Top) {
1215 error(Root, "expected mapping node");
1216 return false;
1217 }
1218
1219 KeyStatusPair Fields[] = {
1220 KeyStatusPair("version", true),
1221 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001222 KeyStatusPair("use-external-names", false),
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001223 KeyStatusPair("overlay-relative", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001224 KeyStatusPair("roots", true),
1225 };
1226
Craig Topperac67c052015-11-30 03:11:10 +00001227 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001228
1229 // Parse configuration and 'roots'
1230 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
1231 ++I) {
1232 SmallString<10> KeyBuffer;
1233 StringRef Key;
1234 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
1235 return false;
1236
1237 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1238 return false;
1239
1240 if (Key == "roots") {
1241 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
1242 if (!Roots) {
1243 error(I->getValue(), "expected array");
1244 return false;
1245 }
1246
1247 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
1248 I != E; ++I) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001249 if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001250 FS->Roots.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001251 else
1252 return false;
1253 }
1254 } else if (Key == "version") {
1255 StringRef VersionString;
1256 SmallString<4> Storage;
1257 if (!parseScalarString(I->getValue(), VersionString, Storage))
1258 return false;
1259 int Version;
1260 if (VersionString.getAsInteger<int>(10, Version)) {
1261 error(I->getValue(), "expected integer");
1262 return false;
1263 }
1264 if (Version < 0) {
1265 error(I->getValue(), "invalid version number");
1266 return false;
1267 }
1268 if (Version != 0) {
1269 error(I->getValue(), "version mismatch, expected 0");
1270 return false;
1271 }
1272 } else if (Key == "case-sensitive") {
1273 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
1274 return false;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001275 } else if (Key == "overlay-relative") {
1276 if (!parseScalarBool(I->getValue(), FS->IsRelativeOverlay))
1277 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001278 } else if (Key == "use-external-names") {
1279 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
1280 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001281 } else {
1282 llvm_unreachable("key missing from Keys");
1283 }
1284 }
1285
1286 if (Stream.failed())
1287 return false;
1288
1289 if (!checkMissingKeys(Top, Keys))
1290 return false;
1291 return true;
1292 }
1293};
1294} // end of anonymous namespace
1295
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001296Entry::~Entry() = default;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001297
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001298RedirectingFileSystem *
1299RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1300 SourceMgr::DiagHandlerTy DiagHandler,
1301 StringRef YAMLFilePath, void *DiagContext,
1302 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001303
1304 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001305 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001306
Ben Langmuir97882e72014-02-24 20:56:37 +00001307 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001308 yaml::document_iterator DI = Stream.begin();
1309 yaml::Node *Root = DI->getRoot();
1310 if (DI == Stream.end() || !Root) {
1311 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001312 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001313 }
1314
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001315 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001316
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001317 std::unique_ptr<RedirectingFileSystem> FS(
1318 new RedirectingFileSystem(ExternalFS));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001319
1320 if (!YAMLFilePath.empty()) {
1321 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1322 // to each 'external-contents' path.
1323 //
1324 // Example:
1325 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
1326 // yields:
1327 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1328 //
1329 SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1330 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1331 assert(!EC && "Overlay dir final path must be absolute");
1332 (void)EC;
1333 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1334 }
1335
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001336 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001337 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001338
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001339 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001340}
1341
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001342ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001343 SmallString<256> Path;
1344 Path_.toVector(Path);
1345
1346 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001347 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001348 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001349
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001350 // Canonicalize path by removing ".", "..", "./", etc components. This is
1351 // a VFS request, do bot bother about symlinks in the path components
1352 // but canonicalize in order to perform the correct entry search.
1353 if (UseCanonicalizedPaths) {
1354 Path = sys::path::remove_leading_dotslash(Path);
1355 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1356 }
1357
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001358 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001359 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001360
1361 sys::path::const_iterator Start = sys::path::begin(Path);
1362 sys::path::const_iterator End = sys::path::end(Path);
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001363 for (const std::unique_ptr<Entry> &Root : Roots) {
1364 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001365 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001366 return Result;
1367 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001368 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001369}
1370
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001371ErrorOr<Entry *>
1372RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1373 sys::path::const_iterator End, Entry *From) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001374#ifndef LLVM_ON_WIN32
1375 assert(!isTraversalComponent(*Start) &&
1376 !isTraversalComponent(From->getName()) &&
1377 "Paths should not contain traversal components");
1378#else
1379 // FIXME: this is here to support windows, remove it once canonicalized
1380 // paths become globally default.
Bruno Cardoso Lopesbe056b12016-02-23 17:06:50 +00001381 if (Start->equals("."))
1382 ++Start;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001383#endif
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001384
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001385 StringRef FromName = From->getName();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001386
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001387 // Forward the search to the next component in case this is an empty one.
1388 if (!FromName.empty()) {
1389 if (CaseSensitive ? !Start->equals(FromName)
1390 : !Start->equals_lower(FromName))
1391 // failure to match
1392 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001393
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001394 ++Start;
1395
1396 if (Start == End) {
1397 // Match!
1398 return From;
1399 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001400 }
1401
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001402 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001403 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001404 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001405
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001406 for (const std::unique_ptr<Entry> &DirEntry :
1407 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1408 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001409 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001410 return Result;
1411 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001412 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001413}
1414
Ben Langmuirf13302e2015-12-10 23:41:39 +00001415static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1416 Status ExternalStatus) {
1417 Status S = ExternalStatus;
1418 if (!UseExternalNames)
1419 S = Status::copyWithNewName(S, Path.str());
1420 S.IsVFSMapped = true;
1421 return S;
1422}
1423
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001424ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001425 assert(E != nullptr);
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001426 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001427 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001428 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuir5de00f32014-05-23 18:15:47 +00001429 if (S)
Ben Langmuirf13302e2015-12-10 23:41:39 +00001430 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1431 *S);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001432 return S;
1433 } else { // directory
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001434 auto *DE = cast<RedirectingDirectoryEntry>(E);
Ben Langmuirf13302e2015-12-10 23:41:39 +00001435 return Status::copyWithNewName(DE->getStatus(), Path.str());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001436 }
1437}
1438
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001439ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001440 ErrorOr<Entry *> Result = lookupPath(Path);
1441 if (!Result)
1442 return Result.getError();
1443 return status(Path, *Result);
1444}
1445
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001446namespace {
Ben Langmuirf13302e2015-12-10 23:41:39 +00001447/// Provide a file wrapper with an overriden status.
1448class FileWithFixedStatus : public File {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001449 std::unique_ptr<File> InnerFile;
Ben Langmuirf13302e2015-12-10 23:41:39 +00001450 Status S;
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001451
1452public:
Ben Langmuirf13302e2015-12-10 23:41:39 +00001453 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
1454 : InnerFile(std::move(InnerFile)), S(S) {}
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001455
Ben Langmuirf13302e2015-12-10 23:41:39 +00001456 ErrorOr<Status> status() override { return S; }
1457 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +00001458 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1459 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001460 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1461 IsVolatile);
1462 }
1463 std::error_code close() override { return InnerFile->close(); }
1464};
1465} // end anonymous namespace
1466
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001467ErrorOr<std::unique_ptr<File>>
1468RedirectingFileSystem::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001469 ErrorOr<Entry *> E = lookupPath(Path);
1470 if (!E)
1471 return E.getError();
1472
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001473 auto *F = dyn_cast<RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001474 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001475 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001476
Benjamin Kramera8857962014-10-26 22:44:13 +00001477 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1478 if (!Result)
1479 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001480
Ben Langmuirf13302e2015-12-10 23:41:39 +00001481 auto ExternalStatus = (*Result)->status();
1482 if (!ExternalStatus)
1483 return ExternalStatus.getError();
Ben Langmuird066d4c2014-02-28 21:16:07 +00001484
Ben Langmuirf13302e2015-12-10 23:41:39 +00001485 // FIXME: Update the status with the name and VFSMapped.
1486 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1487 *ExternalStatus);
1488 return std::unique_ptr<File>(
1489 llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001490}
1491
1492IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001493vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001494 SourceMgr::DiagHandlerTy DiagHandler,
1495 StringRef YAMLFilePath,
1496 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001497 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001498 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001499 YAMLFilePath, DiagContext, ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001500}
1501
1502UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001503 static std::atomic<unsigned> UID;
1504 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001505 // The following assumes that uint64_t max will never collide with a real
1506 // dev_t value from the OS.
1507 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1508}
Justin Bogner9c785292014-05-20 21:43:27 +00001509
Justin Bogner9c785292014-05-20 21:43:27 +00001510void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1511 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1512 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1513 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1514 Mappings.emplace_back(VirtualPath, RealPath);
1515}
1516
Justin Bogner44fa450342014-05-21 22:46:51 +00001517namespace {
1518class JSONWriter {
1519 llvm::raw_ostream &OS;
1520 SmallVector<StringRef, 16> DirStack;
1521 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
1522 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1523 bool containedIn(StringRef Parent, StringRef Path);
1524 StringRef containedPart(StringRef Parent, StringRef Path);
1525 void startDirectory(StringRef Path);
1526 void endDirectory();
1527 void writeEntry(StringRef VPath, StringRef RPath);
1528
1529public:
1530 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001531 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
1532 Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
1533 StringRef OverlayDir);
Justin Bogner44fa450342014-05-21 22:46:51 +00001534};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001535}
Justin Bogner9c785292014-05-20 21:43:27 +00001536
Justin Bogner44fa450342014-05-21 22:46:51 +00001537bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001538 using namespace llvm::sys;
1539 // Compare each path component.
1540 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1541 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1542 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1543 if (*IParent != *IChild)
1544 return false;
1545 }
1546 // Have we exhausted the parent path?
1547 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001548}
1549
Justin Bogner44fa450342014-05-21 22:46:51 +00001550StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1551 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001552 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001553 return Path.slice(Parent.size() + 1, StringRef::npos);
1554}
1555
Justin Bogner44fa450342014-05-21 22:46:51 +00001556void JSONWriter::startDirectory(StringRef Path) {
1557 StringRef Name =
1558 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1559 DirStack.push_back(Path);
1560 unsigned Indent = getDirIndent();
1561 OS.indent(Indent) << "{\n";
1562 OS.indent(Indent + 2) << "'type': 'directory',\n";
1563 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1564 OS.indent(Indent + 2) << "'contents': [\n";
1565}
1566
1567void JSONWriter::endDirectory() {
1568 unsigned Indent = getDirIndent();
1569 OS.indent(Indent + 2) << "]\n";
1570 OS.indent(Indent) << "}";
1571
1572 DirStack.pop_back();
1573}
1574
1575void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1576 unsigned Indent = getFileIndent();
1577 OS.indent(Indent) << "{\n";
1578 OS.indent(Indent + 2) << "'type': 'file',\n";
1579 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1580 OS.indent(Indent + 2) << "'external-contents': \""
1581 << llvm::yaml::escape(RPath) << "\"\n";
1582 OS.indent(Indent) << "}";
1583}
1584
1585void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001586 Optional<bool> UseExternalNames,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001587 Optional<bool> IsCaseSensitive,
1588 Optional<bool> IsOverlayRelative,
1589 StringRef OverlayDir) {
Justin Bogner44fa450342014-05-21 22:46:51 +00001590 using namespace llvm::sys;
1591
1592 OS << "{\n"
1593 " 'version': 0,\n";
1594 if (IsCaseSensitive.hasValue())
1595 OS << " 'case-sensitive': '"
1596 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001597 if (UseExternalNames.hasValue())
1598 OS << " 'use-external-names': '"
1599 << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001600 bool UseOverlayRelative = false;
1601 if (IsOverlayRelative.hasValue()) {
1602 UseOverlayRelative = IsOverlayRelative.getValue();
1603 OS << " 'overlay-relative': '"
1604 << (UseOverlayRelative ? "true" : "false") << "',\n";
1605 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001606 OS << " 'roots': [\n";
1607
Justin Bogner73466402014-07-15 01:24:35 +00001608 if (!Entries.empty()) {
1609 const YAMLVFSEntry &Entry = Entries.front();
1610 startDirectory(path::parent_path(Entry.VPath));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001611
1612 StringRef RPath = Entry.RPath;
1613 if (UseOverlayRelative) {
1614 unsigned OverlayDirLen = OverlayDir.size();
1615 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1616 "Overlay dir must be contained in RPath");
1617 RPath = RPath.slice(OverlayDirLen, RPath.size());
1618 }
1619
1620 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001621
Justin Bogner73466402014-07-15 01:24:35 +00001622 for (const auto &Entry : Entries.slice(1)) {
1623 StringRef Dir = path::parent_path(Entry.VPath);
1624 if (Dir == DirStack.back())
1625 OS << ",\n";
1626 else {
1627 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1628 OS << "\n";
1629 endDirectory();
1630 }
1631 OS << ",\n";
1632 startDirectory(Dir);
1633 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001634 StringRef RPath = Entry.RPath;
1635 if (UseOverlayRelative) {
1636 unsigned OverlayDirLen = OverlayDir.size();
1637 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1638 "Overlay dir must be contained in RPath");
1639 RPath = RPath.slice(OverlayDirLen, RPath.size());
1640 }
1641 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner73466402014-07-15 01:24:35 +00001642 }
1643
1644 while (!DirStack.empty()) {
1645 OS << "\n";
1646 endDirectory();
1647 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001648 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001649 }
1650
Justin Bogner73466402014-07-15 01:24:35 +00001651 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001652 << "}\n";
1653}
1654
Justin Bogner9c785292014-05-20 21:43:27 +00001655void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1656 std::sort(Mappings.begin(), Mappings.end(),
Justin Bogner44fa450342014-05-21 22:46:51 +00001657 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001658 return LHS.VPath < RHS.VPath;
1659 });
1660
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001661 JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
1662 IsOverlayRelative, OverlayDir);
Justin Bogner9c785292014-05-20 21:43:27 +00001663}
Ben Langmuir740812b2014-06-24 19:37:16 +00001664
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001665VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1666 const Twine &_Path, RedirectingFileSystem &FS,
1667 RedirectingDirectoryEntry::iterator Begin,
1668 RedirectingDirectoryEntry::iterator End, std::error_code &EC)
Ben Langmuir740812b2014-06-24 19:37:16 +00001669 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
1670 if (Current != End) {
1671 SmallString<128> PathStr(Dir);
1672 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001673 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001674 if (S)
1675 CurrentEntry = *S;
1676 else
1677 EC = S.getError();
1678 }
1679}
1680
1681std::error_code VFSFromYamlDirIterImpl::increment() {
1682 assert(Current != End && "cannot iterate past end");
1683 if (++Current != End) {
1684 SmallString<128> PathStr(Dir);
1685 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001686 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001687 if (!S)
1688 return S.getError();
1689 CurrentEntry = *S;
1690 } else {
1691 CurrentEntry = Status();
1692 }
1693 return std::error_code();
1694}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001695
1696vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1697 const Twine &Path,
1698 std::error_code &EC)
1699 : FS(&FS_) {
1700 directory_iterator I = FS->dir_begin(Path, EC);
1701 if (!EC && I != directory_iterator()) {
1702 State = std::make_shared<IterState>();
1703 State->push(I);
1704 }
1705}
1706
1707vfs::recursive_directory_iterator &
1708recursive_directory_iterator::increment(std::error_code &EC) {
1709 assert(FS && State && !State->empty() && "incrementing past end");
1710 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1711 vfs::directory_iterator End;
1712 if (State->top()->isDirectory()) {
1713 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
1714 if (EC)
1715 return *this;
1716 if (I != End) {
1717 State->push(I);
1718 return *this;
1719 }
1720 }
1721
1722 while (!State->empty() && State->top().increment(EC) == End)
1723 State->pop();
1724
1725 if (State->empty())
1726 State.reset(); // end iterator
1727
1728 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001729}