blob: a8545769593d3a836a7d73e7bd189c8bdd9c60a6 [file] [log] [blame]
Eugene Zelenko5a520112018-03-28 22:09:09 +00001//===- VirtualFileSystem.cpp - Virtual File System Layer ------------------===//
Ben Langmuirc8130a72014-02-20 21:59:23 +00002//
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//===----------------------------------------------------------------------===//
Eugene Zelenko5a520112018-03-28 22:09:09 +00009//
Ben Langmuirc8130a72014-02-20 21:59:23 +000010// This file implements the VirtualFileSystem interface.
Eugene Zelenko5a520112018-03-28 22:09:09 +000011//
Ben Langmuirc8130a72014-02-20 21:59:23 +000012//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/VirtualFileSystem.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000015#include "clang/Basic/LLVM.h"
16#include "llvm/ADT/ArrayRef.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000017#include "llvm/ADT/DenseMap.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000018#include "llvm/ADT/IntrusiveRefCntPtr.h"
19#include "llvm/ADT/Optional.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000020#include "llvm/ADT/STLExtras.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000021#include "llvm/ADT/SmallString.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringRef.h"
Ben Langmuir740812b2014-06-24 19:37:16 +000024#include "llvm/ADT/StringSet.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000025#include "llvm/ADT/Twine.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000026#include "llvm/ADT/iterator_range.h"
Benjamin Kramercfeacf52016-05-27 14:27:13 +000027#include "llvm/Config/llvm-config.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000028#include "llvm/Support/Compiler.h"
29#include "llvm/Support/Casting.h"
30#include "llvm/Support/Chrono.h"
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +000031#include "llvm/Support/Debug.h"
Rafael Espindola71de0b62014-06-13 17:20:50 +000032#include "llvm/Support/Errc.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000033#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/ErrorOr.h"
35#include "llvm/Support/FileSystem.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000036#include "llvm/Support/MemoryBuffer.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000037#include "llvm/Support/Path.h"
David Majnemer6a6206d2016-03-04 05:26:14 +000038#include "llvm/Support/Process.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000039#include "llvm/Support/SMLoc.h"
40#include "llvm/Support/SourceMgr.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000041#include "llvm/Support/YAMLParser.h"
Eugene Zelenko5a520112018-03-28 22:09:09 +000042#include "llvm/Support/raw_ostream.h"
43#include <algorithm>
Benjamin Kramer4527fb22014-03-02 17:08:31 +000044#include <atomic>
Eugene Zelenko5a520112018-03-28 22:09:09 +000045#include <cassert>
46#include <cstdint>
47#include <iterator>
48#include <limits>
49#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000050#include <memory>
Eugene Zelenko5a520112018-03-28 22:09:09 +000051#include <string>
52#include <system_error>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000053#include <utility>
Eugene Zelenko5a520112018-03-28 22:09:09 +000054#include <vector>
Ben Langmuirc8130a72014-02-20 21:59:23 +000055
56using namespace clang;
Eugene Zelenko5a520112018-03-28 22:09:09 +000057using namespace vfs;
Ben Langmuirc8130a72014-02-20 21:59:23 +000058using namespace llvm;
Eugene Zelenko5a520112018-03-28 22:09:09 +000059
Ben Langmuirc8130a72014-02-20 21:59:23 +000060using llvm::sys::fs::file_status;
61using llvm::sys::fs::file_type;
62using llvm::sys::fs::perms;
63using llvm::sys::fs::UniqueID;
64
65Status::Status(const file_status &Status)
66 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
67 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
Eugene Zelenko5a520112018-03-28 22:09:09 +000068 Type(Status.type()), Perms(Status.permissions()) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000069
Pavel Labathac71c8e2016-11-09 10:52:22 +000070Status::Status(StringRef Name, UniqueID UID, sys::TimePoint<> MTime,
Benjamin Kramer268b51a2015-10-05 13:15:33 +000071 uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
72 perms Perms)
Ben Langmuirb59cf672014-02-27 00:25:12 +000073 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
Eugene Zelenko5a520112018-03-28 22:09:09 +000074 Type(Type), Perms(Perms) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000075
Benjamin Kramer268b51a2015-10-05 13:15:33 +000076Status Status::copyWithNewName(const Status &In, StringRef NewName) {
77 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
78 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
79 In.getPermissions());
80}
81
82Status Status::copyWithNewName(const file_status &In, StringRef NewName) {
83 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
84 In.getUser(), In.getGroup(), In.getSize(), In.type(),
85 In.permissions());
86}
87
Ben Langmuirc8130a72014-02-20 21:59:23 +000088bool Status::equivalent(const Status &Other) const {
Benjamin Kramerd5152912017-07-20 11:57:02 +000089 assert(isStatusKnown() && Other.isStatusKnown());
Ben Langmuirc8130a72014-02-20 21:59:23 +000090 return getUniqueID() == Other.getUniqueID();
91}
Eugene Zelenko5a520112018-03-28 22:09:09 +000092
Ben Langmuirc8130a72014-02-20 21:59:23 +000093bool Status::isDirectory() const {
94 return Type == file_type::directory_file;
95}
Eugene Zelenko5a520112018-03-28 22:09:09 +000096
Ben Langmuirc8130a72014-02-20 21:59:23 +000097bool Status::isRegularFile() const {
98 return Type == file_type::regular_file;
99}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000100
Ben Langmuirc8130a72014-02-20 21:59:23 +0000101bool Status::isOther() const {
102 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
103}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000104
Ben Langmuirc8130a72014-02-20 21:59:23 +0000105bool Status::isSymlink() const {
106 return Type == file_type::symlink_file;
107}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000108
Ben Langmuirc8130a72014-02-20 21:59:23 +0000109bool Status::isStatusKnown() const {
110 return Type != file_type::status_error;
111}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000112
Ben Langmuirc8130a72014-02-20 21:59:23 +0000113bool Status::exists() const {
114 return isStatusKnown() && Type != file_type::file_not_found;
115}
116
Eugene Zelenko5a520112018-03-28 22:09:09 +0000117File::~File() = default;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000118
Eugene Zelenko5a520112018-03-28 22:09:09 +0000119FileSystem::~FileSystem() = default;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000120
Benjamin Kramera8857962014-10-26 22:44:13 +0000121ErrorOr<std::unique_ptr<MemoryBuffer>>
122FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
123 bool RequiresNullTerminator, bool IsVolatile) {
124 auto F = openFileForRead(Name);
125 if (!F)
126 return F.getError();
Ben Langmuirc8130a72014-02-20 21:59:23 +0000127
Benjamin Kramera8857962014-10-26 22:44:13 +0000128 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000129}
130
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000131std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
Bob Wilsonf43354f2016-03-26 18:55:13 +0000132 if (llvm::sys::path::is_absolute(Path))
Eugene Zelenko5a520112018-03-28 22:09:09 +0000133 return {};
Bob Wilsonf43354f2016-03-26 18:55:13 +0000134
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000135 auto WorkingDir = getCurrentWorkingDirectory();
136 if (!WorkingDir)
137 return WorkingDir.getError();
138
139 return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
140}
141
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000142bool FileSystem::exists(const Twine &Path) {
143 auto Status = status(Path);
144 return Status && Status->exists();
145}
146
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000147#ifndef NDEBUG
148static bool isTraversalComponent(StringRef Component) {
149 return Component.equals("..") || Component.equals(".");
150}
151
152static bool pathHasTraversal(StringRef Path) {
153 using namespace llvm::sys;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000154
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000155 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
156 if (isTraversalComponent(Comp))
157 return true;
158 return false;
159}
160#endif
161
Ben Langmuirc8130a72014-02-20 21:59:23 +0000162//===-----------------------------------------------------------------------===/
163// RealFileSystem implementation
164//===-----------------------------------------------------------------------===/
165
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000166namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000167
Ben Langmuirc8130a72014-02-20 21:59:23 +0000168/// \brief Wrapper around a raw file descriptor.
169class RealFile : public File {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000170 friend class RealFileSystem;
171
Ben Langmuirc8130a72014-02-20 21:59:23 +0000172 int FD;
Ben Langmuird066d4c2014-02-28 21:16:07 +0000173 Status S;
Taewook Ohf42103c2016-06-13 20:40:21 +0000174 std::string RealName;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000175
Taewook Ohf42103c2016-06-13 20:40:21 +0000176 RealFile(int FD, StringRef NewName, StringRef NewRealPathName)
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000177 : FD(FD), S(NewName, {}, {}, {}, {}, {},
Taewook Ohf42103c2016-06-13 20:40:21 +0000178 llvm::sys::fs::file_type::status_error, {}),
179 RealName(NewRealPathName.str()) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000180 assert(FD >= 0 && "Invalid or inactive file descriptor");
181 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000182
Ben Langmuirc8130a72014-02-20 21:59:23 +0000183public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000184 ~RealFile() override;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000185
Craig Toppera798a9d2014-03-02 09:32:10 +0000186 ErrorOr<Status> status() override;
Taewook Ohf42103c2016-06-13 20:40:21 +0000187 ErrorOr<std::string> getName() override;
Benjamin Kramer737501c2015-10-05 21:20:19 +0000188 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
189 int64_t FileSize,
190 bool RequiresNullTerminator,
191 bool IsVolatile) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000192 std::error_code close() override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000193};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000194
195} // namespace
196
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000197RealFile::~RealFile() { close(); }
Ben Langmuirc8130a72014-02-20 21:59:23 +0000198
199ErrorOr<Status> RealFile::status() {
200 assert(FD != -1 && "cannot stat closed file");
Ben Langmuird066d4c2014-02-28 21:16:07 +0000201 if (!S.isStatusKnown()) {
202 file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000203 if (std::error_code EC = sys::fs::status(FD, RealStatus))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000204 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000205 S = Status::copyWithNewName(RealStatus, S.getName());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000206 }
207 return S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000208}
209
Taewook Ohf42103c2016-06-13 20:40:21 +0000210ErrorOr<std::string> RealFile::getName() {
211 return RealName.empty() ? S.getName().str() : RealName;
212}
213
Benjamin Kramera8857962014-10-26 22:44:13 +0000214ErrorOr<std::unique_ptr<MemoryBuffer>>
215RealFile::getBuffer(const Twine &Name, int64_t FileSize,
216 bool RequiresNullTerminator, bool IsVolatile) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000217 assert(FD != -1 && "cannot get buffer for closed file");
Benjamin Kramera8857962014-10-26 22:44:13 +0000218 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
219 IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000220}
221
Rafael Espindola8e650d72014-06-12 20:37:59 +0000222std::error_code RealFile::close() {
David Majnemer6a6206d2016-03-04 05:26:14 +0000223 std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000224 FD = -1;
David Majnemer6a6206d2016-03-04 05:26:14 +0000225 return EC;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000226}
227
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000228namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000229
Ben Langmuirc8130a72014-02-20 21:59:23 +0000230/// \brief The file system according to your operating system.
231class RealFileSystem : public FileSystem {
232public:
Craig Toppera798a9d2014-03-02 09:32:10 +0000233 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000234 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000235 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000236
237 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
238 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000239};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000240
241} // namespace
Ben Langmuirc8130a72014-02-20 21:59:23 +0000242
243ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
244 sys::fs::file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000245 if (std::error_code EC = sys::fs::status(Path, RealStatus))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000246 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000247 return Status::copyWithNewName(RealStatus, Path.str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000248}
249
Benjamin Kramera8857962014-10-26 22:44:13 +0000250ErrorOr<std::unique_ptr<File>>
251RealFileSystem::openFileForRead(const Twine &Name) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000252 int FD;
Taewook Ohf42103c2016-06-13 20:40:21 +0000253 SmallString<256> RealName;
254 if (std::error_code EC = sys::fs::openFileForRead(Name, FD, &RealName))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000255 return EC;
Taewook Ohf42103c2016-06-13 20:40:21 +0000256 return std::unique_ptr<File>(new RealFile(FD, Name.str(), RealName.str()));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000257}
258
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000259llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
260 SmallString<256> Dir;
261 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
262 return EC;
263 return Dir.str().str();
264}
265
266std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
267 // FIXME: chdir is thread hostile; on the other hand, creating the same
268 // behavior as chdir is complex: chdir resolves the path once, thus
269 // guaranteeing that all subsequent relative path operations work
270 // on the same path the original chdir resulted in. This makes a
271 // difference for example on network filesystems, where symlinks might be
272 // switched during runtime of the tool. Fixing this depends on having a
273 // file system abstraction that allows openat() style interactions.
Pavel Labathdcbd6142017-01-24 11:14:29 +0000274 return llvm::sys::fs::set_current_path(Path);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000275}
276
Ben Langmuirc8130a72014-02-20 21:59:23 +0000277IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
278 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
279 return FS;
280}
281
Ben Langmuir740812b2014-06-24 19:37:16 +0000282namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000283
Ben Langmuir740812b2014-06-24 19:37:16 +0000284class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
Ben Langmuir740812b2014-06-24 19:37:16 +0000285 llvm::sys::fs::directory_iterator Iter;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000286
Ben Langmuir740812b2014-06-24 19:37:16 +0000287public:
Juergen Ributzka4a259562017-03-10 21:23:29 +0000288 RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) {
Ben Langmuir740812b2014-06-24 19:37:16 +0000289 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
290 llvm::sys::fs::file_status S;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000291 EC = llvm::sys::fs::status(Iter->path(), S, true);
Juergen Ributzkaf9787432017-03-14 00:14:40 +0000292 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000293 }
294 }
295
296 std::error_code increment() override {
297 std::error_code EC;
298 Iter.increment(EC);
299 if (EC) {
300 return EC;
301 } else if (Iter == llvm::sys::fs::directory_iterator()) {
302 CurrentEntry = Status();
303 } else {
304 llvm::sys::fs::file_status S;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000305 EC = llvm::sys::fs::status(Iter->path(), S, true);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000306 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000307 }
308 return EC;
309 }
310};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000311
312} // namespace
Ben Langmuir740812b2014-06-24 19:37:16 +0000313
314directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
315 std::error_code &EC) {
316 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
317}
318
Ben Langmuirc8130a72014-02-20 21:59:23 +0000319//===-----------------------------------------------------------------------===/
320// OverlayFileSystem implementation
321//===-----------------------------------------------------------------------===/
Eugene Zelenko5a520112018-03-28 22:09:09 +0000322
Ben Langmuirc8130a72014-02-20 21:59:23 +0000323OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000324 FSList.push_back(std::move(BaseFS));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000325}
326
327void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
328 FSList.push_back(FS);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000329 // Synchronize added file systems by duplicating the working directory from
330 // the first one in the list.
331 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000332}
333
334ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
335 // FIXME: handle symlinks that cross file systems
336 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
337 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000338 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000339 return Status;
340 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000341 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000342}
343
Benjamin Kramera8857962014-10-26 22:44:13 +0000344ErrorOr<std::unique_ptr<File>>
345OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000346 // FIXME: handle symlinks that cross file systems
347 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000348 auto Result = (*I)->openFileForRead(Path);
349 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
350 return Result;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000351 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000352 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000353}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000354
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000355llvm::ErrorOr<std::string>
356OverlayFileSystem::getCurrentWorkingDirectory() const {
357 // All file systems are synchronized, just take the first working directory.
358 return FSList.front()->getCurrentWorkingDirectory();
359}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000360
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000361std::error_code
362OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
363 for (auto &FS : FSList)
364 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
365 return EC;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000366 return {};
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000367}
368
Eugene Zelenko5a520112018-03-28 22:09:09 +0000369clang::vfs::detail::DirIterImpl::~DirIterImpl() = default;
Ben Langmuir740812b2014-06-24 19:37:16 +0000370
371namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000372
Ben Langmuir740812b2014-06-24 19:37:16 +0000373class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
374 OverlayFileSystem &Overlays;
375 std::string Path;
376 OverlayFileSystem::iterator CurrentFS;
377 directory_iterator CurrentDirIter;
378 llvm::StringSet<> SeenNames;
379
380 std::error_code incrementFS() {
381 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
382 ++CurrentFS;
383 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
384 std::error_code EC;
385 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
386 if (EC && EC != errc::no_such_file_or_directory)
387 return EC;
388 if (CurrentDirIter != directory_iterator())
389 break; // found
390 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000391 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +0000392 }
393
394 std::error_code incrementDirIter(bool IsFirstTime) {
395 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
396 "incrementing past end");
397 std::error_code EC;
398 if (!IsFirstTime)
399 CurrentDirIter.increment(EC);
400 if (!EC && CurrentDirIter == directory_iterator())
401 EC = incrementFS();
402 return EC;
403 }
404
405 std::error_code incrementImpl(bool IsFirstTime) {
406 while (true) {
407 std::error_code EC = incrementDirIter(IsFirstTime);
408 if (EC || CurrentDirIter == directory_iterator()) {
409 CurrentEntry = Status();
410 return EC;
411 }
412 CurrentEntry = *CurrentDirIter;
413 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
David Blaikie61b86d42014-11-19 02:56:13 +0000414 if (SeenNames.insert(Name).second)
Ben Langmuir740812b2014-06-24 19:37:16 +0000415 return EC; // name not seen before
416 }
417 llvm_unreachable("returned above");
418 }
419
420public:
421 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
422 std::error_code &EC)
423 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
424 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
425 EC = incrementImpl(true);
426 }
427
428 std::error_code increment() override { return incrementImpl(false); }
429};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000430
431} // namespace
Ben Langmuir740812b2014-06-24 19:37:16 +0000432
433directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
434 std::error_code &EC) {
435 return directory_iterator(
436 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
437}
438
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000439namespace clang {
440namespace vfs {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000441
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000442namespace detail {
443
444enum InMemoryNodeKind { IME_File, IME_Directory };
445
446/// The in memory file system is a tree of Nodes. Every node can either be a
447/// file or a directory.
448class InMemoryNode {
449 Status Stat;
450 InMemoryNodeKind Kind;
451
452public:
453 InMemoryNode(Status Stat, InMemoryNodeKind Kind)
454 : Stat(std::move(Stat)), Kind(Kind) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000455 virtual ~InMemoryNode() = default;
456
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000457 const Status &getStatus() const { return Stat; }
458 InMemoryNodeKind getKind() const { return Kind; }
459 virtual std::string toString(unsigned Indent) const = 0;
460};
461
462namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000463
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000464class InMemoryFile : public InMemoryNode {
465 std::unique_ptr<llvm::MemoryBuffer> Buffer;
466
467public:
468 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
469 : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
470
471 llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000472
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000473 std::string toString(unsigned Indent) const override {
474 return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
475 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000476
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000477 static bool classof(const InMemoryNode *N) {
478 return N->getKind() == IME_File;
479 }
480};
481
482/// Adapt a InMemoryFile for VFS' File interface.
483class InMemoryFileAdaptor : public File {
484 InMemoryFile &Node;
485
486public:
487 explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
488
489 llvm::ErrorOr<Status> status() override { return Node.getStatus(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000490
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000491 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +0000492 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
493 bool IsVolatile) override {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000494 llvm::MemoryBuffer *Buf = Node.getBuffer();
495 return llvm::MemoryBuffer::getMemBuffer(
496 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
497 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000498
499 std::error_code close() override { return {}; }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000500};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000501
502} // namespace
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000503
504class InMemoryDirectory : public InMemoryNode {
505 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
506
507public:
508 InMemoryDirectory(Status Stat)
509 : InMemoryNode(std::move(Stat), IME_Directory) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000510
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000511 InMemoryNode *getChild(StringRef Name) {
512 auto I = Entries.find(Name);
513 if (I != Entries.end())
514 return I->second.get();
515 return nullptr;
516 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000517
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000518 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
519 return Entries.insert(make_pair(Name, std::move(Child)))
520 .first->second.get();
521 }
522
Eugene Zelenko5a520112018-03-28 22:09:09 +0000523 using const_iterator = decltype(Entries)::const_iterator;
524
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000525 const_iterator begin() const { return Entries.begin(); }
526 const_iterator end() const { return Entries.end(); }
527
528 std::string toString(unsigned Indent) const override {
529 std::string Result =
530 (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000531 for (const auto &Entry : Entries)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000532 Result += Entry.second->toString(Indent + 2);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000533 return Result;
534 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000535
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000536 static bool classof(const InMemoryNode *N) {
537 return N->getKind() == IME_Directory;
538 }
539};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000540
541} // namespace detail
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000542
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000543InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000544 : Root(new detail::InMemoryDirectory(
Pavel Labathac71c8e2016-11-09 10:52:22 +0000545 Status("", getNextVirtualUniqueID(), llvm::sys::TimePoint<>(), 0, 0,
546 0, llvm::sys::fs::file_type::directory_file,
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000547 llvm::sys::fs::perms::all_all))),
548 UseNormalizedPaths(UseNormalizedPaths) {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000549
Eugene Zelenko5a520112018-03-28 22:09:09 +0000550InMemoryFileSystem::~InMemoryFileSystem() = default;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000551
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000552std::string InMemoryFileSystem::toString() const {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000553 return Root->toString(/*Indent=*/0);
554}
555
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000556bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000557 std::unique_ptr<llvm::MemoryBuffer> Buffer,
558 Optional<uint32_t> User,
559 Optional<uint32_t> Group,
560 Optional<llvm::sys::fs::file_type> Type,
561 Optional<llvm::sys::fs::perms> Perms) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000562 SmallString<128> Path;
563 P.toVector(Path);
564
565 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000566 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000567 assert(!EC);
568 (void)EC;
569
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000570 if (useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000571 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000572
573 if (Path.empty())
574 return false;
575
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000576 detail::InMemoryDirectory *Dir = Root.get();
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000577 auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path);
578 const auto ResolvedUser = User.getValueOr(0);
579 const auto ResolvedGroup = Group.getValueOr(0);
580 const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file);
581 const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all);
582 // Any intermediate directories we create should be accessible by
583 // the owner, even if Perms says otherwise for the final path.
584 const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000585 while (true) {
586 StringRef Name = *I;
587 detail::InMemoryNode *Node = Dir->getChild(Name);
588 ++I;
589 if (!Node) {
590 if (I == E) {
Ben Hamilton78381012017-11-16 19:34:08 +0000591 // End of the path, create a new file or directory.
Benjamin Kramer1b8dbe32015-10-06 14:45:16 +0000592 Status Stat(P.str(), getNextVirtualUniqueID(),
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000593 llvm::sys::toTimePoint(ModificationTime), ResolvedUser,
594 ResolvedGroup, Buffer->getBufferSize(), ResolvedType,
595 ResolvedPerms);
Ben Hamilton78381012017-11-16 19:34:08 +0000596 std::unique_ptr<detail::InMemoryNode> Child;
597 if (ResolvedType == sys::fs::file_type::directory_file) {
598 Child.reset(new detail::InMemoryDirectory(std::move(Stat)));
599 } else {
600 Child.reset(new detail::InMemoryFile(std::move(Stat),
601 std::move(Buffer)));
602 }
603 Dir->addChild(Name, std::move(Child));
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000604 return true;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000605 }
606
607 // Create a new directory. Use the path up to here.
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000608 Status Stat(
609 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000610 getNextVirtualUniqueID(), llvm::sys::toTimePoint(ModificationTime),
611 ResolvedUser, ResolvedGroup, Buffer->getBufferSize(),
612 sys::fs::file_type::directory_file, NewDirectoryPerms);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000613 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
614 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
615 continue;
616 }
617
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000618 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000619 Dir = NewDir;
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000620 } else {
621 assert(isa<detail::InMemoryFile>(Node) &&
622 "Must be either file or directory!");
623
624 // Trying to insert a directory in place of a file.
625 if (I != E)
626 return false;
627
628 // Return false only if the new file is different from the existing one.
629 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
630 Buffer->getBuffer();
631 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000632 }
633}
634
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000635bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000636 llvm::MemoryBuffer *Buffer,
637 Optional<uint32_t> User,
638 Optional<uint32_t> Group,
639 Optional<llvm::sys::fs::file_type> Type,
640 Optional<llvm::sys::fs::perms> Perms) {
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000641 return addFile(P, ModificationTime,
642 llvm::MemoryBuffer::getMemBuffer(
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000643 Buffer->getBuffer(), Buffer->getBufferIdentifier()),
644 std::move(User), std::move(Group), std::move(Type),
645 std::move(Perms));
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000646}
647
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000648static ErrorOr<detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000649lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
650 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000651 SmallString<128> Path;
652 P.toVector(Path);
653
654 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000655 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000656 assert(!EC);
657 (void)EC;
658
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000659 if (FS.useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000660 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer4ad1c432015-10-12 13:30:38 +0000661
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000662 if (Path.empty())
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000663 return Dir;
664
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000665 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000666 while (true) {
667 detail::InMemoryNode *Node = Dir->getChild(*I);
668 ++I;
669 if (!Node)
670 return errc::no_such_file_or_directory;
671
672 // Return the file if it's at the end of the path.
673 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
674 if (I == E)
675 return File;
676 return errc::no_such_file_or_directory;
677 }
678
679 // Traverse directories.
680 Dir = cast<detail::InMemoryDirectory>(Node);
681 if (I == E)
682 return Dir;
683 }
684}
685
686llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000687 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000688 if (Node)
689 return (*Node)->getStatus();
690 return Node.getError();
691}
692
693llvm::ErrorOr<std::unique_ptr<File>>
694InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000695 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000696 if (!Node)
697 return Node.getError();
698
699 // When we have a file provide a heap-allocated wrapper for the memory buffer
700 // to match the ownership semantics for File.
701 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
702 return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
703
704 // FIXME: errc::not_a_file?
705 return make_error_code(llvm::errc::invalid_argument);
706}
707
708namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000709
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000710/// Adaptor from InMemoryDir::iterator to directory_iterator.
711class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
712 detail::InMemoryDirectory::const_iterator I;
713 detail::InMemoryDirectory::const_iterator E;
714
715public:
Eugene Zelenko5a520112018-03-28 22:09:09 +0000716 InMemoryDirIterator() = default;
717
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000718 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
719 : I(Dir.begin()), E(Dir.end()) {
720 if (I != E)
721 CurrentEntry = I->second->getStatus();
722 }
723
724 std::error_code increment() override {
725 ++I;
726 // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
727 // the rest.
728 CurrentEntry = I != E ? I->second->getStatus() : Status();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000729 return {};
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000730 }
731};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000732
733} // namespace
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000734
735directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
736 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000737 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000738 if (!Node) {
739 EC = Node.getError();
740 return directory_iterator(std::make_shared<InMemoryDirIterator>());
741 }
742
743 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
744 return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
745
746 EC = make_error_code(llvm::errc::not_a_directory);
747 return directory_iterator(std::make_shared<InMemoryDirIterator>());
748}
Benjamin Kramere9e76072016-01-09 16:33:16 +0000749
750std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
751 SmallString<128> Path;
752 P.toVector(Path);
753
754 // Fix up relative paths. This just prepends the current working directory.
755 std::error_code EC = makeAbsolute(Path);
756 assert(!EC);
757 (void)EC;
758
759 if (useNormalizedPaths())
760 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
761
762 if (!Path.empty())
763 WorkingDirectory = Path.str();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000764 return {};
Benjamin Kramere9e76072016-01-09 16:33:16 +0000765}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000766
767} // namespace vfs
768} // namespace clang
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000769
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000770//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000771// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000772//===-----------------------------------------------------------------------===/
773
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000774namespace {
775
776enum EntryKind {
777 EK_Directory,
778 EK_File
779};
780
781/// \brief A single file or directory in the VFS.
782class Entry {
783 EntryKind Kind;
784 std::string Name;
785
786public:
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000787 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000788 virtual ~Entry() = default;
789
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000790 StringRef getName() const { return Name; }
791 EntryKind getKind() const { return Kind; }
792};
793
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000794class RedirectingDirectoryEntry : public Entry {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000795 std::vector<std::unique_ptr<Entry>> Contents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000796 Status S;
797
798public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000799 RedirectingDirectoryEntry(StringRef Name,
800 std::vector<std::unique_ptr<Entry>> Contents,
801 Status S)
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000802 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000803 S(std::move(S)) {}
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000804 RedirectingDirectoryEntry(StringRef Name, Status S)
805 : Entry(EK_Directory, Name), S(std::move(S)) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000806
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000807 Status getStatus() { return S; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000808
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000809 void addContent(std::unique_ptr<Entry> Content) {
810 Contents.push_back(std::move(Content));
811 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000812
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000813 Entry *getLastContent() const { return Contents.back().get(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000814
815 using iterator = decltype(Contents)::iterator;
816
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000817 iterator contents_begin() { return Contents.begin(); }
818 iterator contents_end() { return Contents.end(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000819
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000820 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
821};
822
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000823class RedirectingFileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000824public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000825 enum NameKind {
826 NK_NotSet,
827 NK_External,
828 NK_Virtual
829 };
Eugene Zelenko5a520112018-03-28 22:09:09 +0000830
Ben Langmuirb59cf672014-02-27 00:25:12 +0000831private:
832 std::string ExternalContentsPath;
833 NameKind UseName;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000834
Ben Langmuirb59cf672014-02-27 00:25:12 +0000835public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000836 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
837 NameKind UseName)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000838 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
839 UseName(UseName) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000840
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000841 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000842
Ben Langmuirb59cf672014-02-27 00:25:12 +0000843 /// \brief whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000844 bool useExternalName(bool GlobalUseExternalName) const {
845 return UseName == NK_NotSet ? GlobalUseExternalName
846 : (UseName == NK_External);
847 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000848
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000849 NameKind getUseName() const { return UseName; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000850
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000851 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
852};
853
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000854class RedirectingFileSystem;
Ben Langmuir740812b2014-06-24 19:37:16 +0000855
856class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
857 std::string Dir;
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000858 RedirectingFileSystem &FS;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000859 RedirectingDirectoryEntry::iterator Current, End;
860
Ben Langmuir740812b2014-06-24 19:37:16 +0000861public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000862 VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000863 RedirectingDirectoryEntry::iterator Begin,
864 RedirectingDirectoryEntry::iterator End,
865 std::error_code &EC);
Eugene Zelenko5a520112018-03-28 22:09:09 +0000866
Ben Langmuir740812b2014-06-24 19:37:16 +0000867 std::error_code increment() override;
868};
869
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000870/// \brief A virtual file system parsed from a YAML file.
871///
872/// Currently, this class allows creating virtual directories and mapping
873/// virtual file paths to existing external files, available in \c ExternalFS.
874///
875/// The basic structure of the parsed file is:
876/// \verbatim
877/// {
878/// 'version': <version number>,
879/// <optional configuration>
880/// 'roots': [
881/// <directory entries>
882/// ]
883/// }
884/// \endverbatim
885///
886/// All configuration options are optional.
887/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000888/// 'use-external-names': <boolean, default=true>
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000889/// 'overlay-relative': <boolean, default=false>
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000890/// 'ignore-non-existent-contents': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000891///
892/// Virtual directories are represented as
893/// \verbatim
894/// {
895/// 'type': 'directory',
896/// 'name': <string>,
897/// 'contents': [ <file or directory entries> ]
898/// }
899/// \endverbatim
900///
901/// The default attributes for virtual directories are:
902/// \verbatim
903/// MTime = now() when created
904/// Perms = 0777
905/// User = Group = 0
906/// Size = 0
907/// UniqueID = unspecified unique value
908/// \endverbatim
909///
910/// Re-mapped files are represented as
911/// \verbatim
912/// {
913/// 'type': 'file',
914/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000915/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000916/// 'external-contents': <path to external file>)
917/// }
918/// \endverbatim
919///
920/// and inherit their attributes from the external contents.
921///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000922/// In both cases, the 'name' field may contain multiple path components (e.g.
923/// /path/to/file). However, any directory that contains more than one child
924/// must be uniquely represented by a directory entry.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000925class RedirectingFileSystem : public vfs::FileSystem {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000926 friend class RedirectingFileSystemParser;
927
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000928 /// The root(s) of the virtual file system.
929 std::vector<std::unique_ptr<Entry>> Roots;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000930
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000931 /// \brief The file system to use for external references.
932 IntrusiveRefCntPtr<FileSystem> ExternalFS;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000933
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000934 /// If IsRelativeOverlay is set, this represents the directory
935 /// path that should be prefixed to each 'external-contents' entry
936 /// when reading from YAML files.
937 std::string ExternalContentsPrefixDir;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000938
939 /// @name Configuration
940 /// @{
941
942 /// \brief Whether to perform case-sensitive comparisons.
943 ///
944 /// Currently, case-insensitive matching only works correctly with ASCII.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000945 bool CaseSensitive = true;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000946
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000947 /// IsRelativeOverlay marks whether a IsExternalContentsPrefixDir path must
948 /// be prefixed in every 'external-contents' when reading from YAML files.
949 bool IsRelativeOverlay = false;
950
Ben Langmuirb59cf672014-02-27 00:25:12 +0000951 /// \brief Whether to use to use the value of 'external-contents' for the
952 /// names of files. This global value is overridable on a per-file basis.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000953 bool UseExternalNames = true;
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000954
955 /// \brief Whether an invalid path obtained via 'external-contents' should
956 /// cause iteration on the VFS to stop. If 'true', the VFS should ignore
957 /// the entry and continue with the next. Allows YAML files to be shared
958 /// across multiple compiler invocations regardless of prior existent
959 /// paths in 'external-contents'. This global value is overridable on a
960 /// per-file basis.
961 bool IgnoreNonExistentContents = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000962 /// @}
963
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000964 /// Virtual file paths and external files could be canonicalized without "..",
965 /// "." and "./" in their paths. FIXME: some unittests currently fail on
966 /// win32 when using remove_dots and remove_leading_dotslash on paths.
967 bool UseCanonicalizedPaths =
968#ifdef LLVM_ON_WIN32
969 false;
970#else
971 true;
972#endif
973
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000974private:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000975 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000976 : ExternalFS(std::move(ExternalFS)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000977
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000978 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
979 /// recursing into the contents of \p From if it is a directory.
980 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
981 sys::path::const_iterator End, Entry *From);
982
Ben Langmuir740812b2014-06-24 19:37:16 +0000983 /// \brief Get the status of a given an \c Entry.
984 ErrorOr<Status> status(const Twine &Path, Entry *E);
985
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000986public:
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +0000987 /// \brief Looks up \p Path in \c Roots.
988 ErrorOr<Entry *> lookupPath(const Twine &Path);
989
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000990 /// \brief Parses \p Buffer, which is expected to be in YAML format and
991 /// returns a virtual file system representing its contents.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000992 static RedirectingFileSystem *
993 create(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000994 SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
995 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000996
Craig Toppera798a9d2014-03-02 09:32:10 +0000997 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000998 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000999
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001000 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
1001 return ExternalFS->getCurrentWorkingDirectory();
1002 }
Eugene Zelenko5a520112018-03-28 22:09:09 +00001003
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001004 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
1005 return ExternalFS->setCurrentWorkingDirectory(Path);
1006 }
1007
Ben Langmuir740812b2014-06-24 19:37:16 +00001008 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
1009 ErrorOr<Entry *> E = lookupPath(Dir);
1010 if (!E) {
1011 EC = E.getError();
Eugene Zelenko5a520112018-03-28 22:09:09 +00001012 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001013 }
1014 ErrorOr<Status> S = status(Dir, *E);
1015 if (!S) {
1016 EC = S.getError();
Eugene Zelenko5a520112018-03-28 22:09:09 +00001017 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001018 }
1019 if (!S->isDirectory()) {
1020 EC = std::error_code(static_cast<int>(errc::not_a_directory),
1021 std::system_category());
Eugene Zelenko5a520112018-03-28 22:09:09 +00001022 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001023 }
1024
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001025 auto *D = cast<RedirectingDirectoryEntry>(*E);
Ben Langmuir740812b2014-06-24 19:37:16 +00001026 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
1027 *this, D->contents_begin(), D->contents_end(), EC));
1028 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001029
1030 void setExternalContentsPrefixDir(StringRef PrefixDir) {
1031 ExternalContentsPrefixDir = PrefixDir.str();
1032 }
1033
1034 StringRef getExternalContentsPrefixDir() const {
1035 return ExternalContentsPrefixDir;
1036 }
1037
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001038 bool ignoreNonExistentContents() const {
1039 return IgnoreNonExistentContents;
1040 }
1041
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001042#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1043LLVM_DUMP_METHOD void dump() const {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001044 for (const auto &Root : Roots)
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001045 dumpEntry(Root.get());
1046 }
1047
1048LLVM_DUMP_METHOD void dumpEntry(Entry *E, int NumSpaces = 0) const {
1049 StringRef Name = E->getName();
1050 for (int i = 0, e = NumSpaces; i < e; ++i)
1051 dbgs() << " ";
1052 dbgs() << "'" << Name.str().c_str() << "'" << "\n";
1053
1054 if (E->getKind() == EK_Directory) {
1055 auto *DE = dyn_cast<RedirectingDirectoryEntry>(E);
1056 assert(DE && "Should be a directory");
1057
1058 for (std::unique_ptr<Entry> &SubEntry :
1059 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1060 dumpEntry(SubEntry.get(), NumSpaces+2);
1061 }
1062 }
1063#endif
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001064};
1065
1066/// \brief A helper class to hold the common YAML parsing state.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001067class RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001068 yaml::Stream &Stream;
1069
1070 void error(yaml::Node *N, const Twine &Msg) {
1071 Stream.printError(N, Msg);
1072 }
1073
1074 // false on error
1075 bool parseScalarString(yaml::Node *N, StringRef &Result,
1076 SmallVectorImpl<char> &Storage) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001077 const auto *S = dyn_cast<yaml::ScalarNode>(N);
1078
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001079 if (!S) {
1080 error(N, "expected string");
1081 return false;
1082 }
1083 Result = S->getValue(Storage);
1084 return true;
1085 }
1086
1087 // false on error
1088 bool parseScalarBool(yaml::Node *N, bool &Result) {
1089 SmallString<5> Storage;
1090 StringRef Value;
1091 if (!parseScalarString(N, Value, Storage))
1092 return false;
1093
1094 if (Value.equals_lower("true") || Value.equals_lower("on") ||
1095 Value.equals_lower("yes") || Value == "1") {
1096 Result = true;
1097 return true;
1098 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
1099 Value.equals_lower("no") || Value == "0") {
1100 Result = false;
1101 return true;
1102 }
1103
1104 error(N, "expected boolean value");
1105 return false;
1106 }
1107
1108 struct KeyStatus {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001109 bool Required;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001110 bool Seen = false;
1111
1112 KeyStatus(bool Required = false) : Required(Required) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001113 };
Eugene Zelenko5a520112018-03-28 22:09:09 +00001114
1115 using KeyStatusPair = std::pair<StringRef, KeyStatus>;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001116
1117 // false on error
1118 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1119 DenseMap<StringRef, KeyStatus> &Keys) {
1120 if (!Keys.count(Key)) {
1121 error(KeyNode, "unknown key");
1122 return false;
1123 }
1124 KeyStatus &S = Keys[Key];
1125 if (S.Seen) {
1126 error(KeyNode, Twine("duplicate key '") + Key + "'");
1127 return false;
1128 }
1129 S.Seen = true;
1130 return true;
1131 }
1132
1133 // false on error
1134 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001135 for (const auto &I : Keys) {
1136 if (I.second.Required && !I.second.Seen) {
1137 error(Obj, Twine("missing key '") + I.first + "'");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001138 return false;
1139 }
1140 }
1141 return true;
1142 }
1143
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001144 Entry *lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1145 Entry *ParentEntry = nullptr) {
1146 if (!ParentEntry) { // Look for a existent root
Eugene Zelenko5a520112018-03-28 22:09:09 +00001147 for (const auto &Root : FS->Roots) {
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001148 if (Name.equals(Root->getName())) {
1149 ParentEntry = Root.get();
1150 return ParentEntry;
1151 }
1152 }
1153 } else { // Advance to the next component
1154 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1155 for (std::unique_ptr<Entry> &Content :
1156 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1157 auto *DirContent = dyn_cast<RedirectingDirectoryEntry>(Content.get());
1158 if (DirContent && Name.equals(Content->getName()))
1159 return DirContent;
1160 }
1161 }
1162
1163 // ... or create a new one
1164 std::unique_ptr<Entry> E = llvm::make_unique<RedirectingDirectoryEntry>(
Pavel Labathac71c8e2016-11-09 10:52:22 +00001165 Name,
1166 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1167 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001168
1169 if (!ParentEntry) { // Add a new root to the overlay
1170 FS->Roots.push_back(std::move(E));
1171 ParentEntry = FS->Roots.back().get();
1172 return ParentEntry;
1173 }
1174
1175 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1176 DE->addContent(std::move(E));
1177 return DE->getLastContent();
1178 }
1179
1180 void uniqueOverlayTree(RedirectingFileSystem *FS, Entry *SrcE,
1181 Entry *NewParentE = nullptr) {
1182 StringRef Name = SrcE->getName();
1183 switch (SrcE->getKind()) {
1184 case EK_Directory: {
1185 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1186 assert(DE && "Must be a directory");
1187 // Empty directories could be present in the YAML as a way to
1188 // describe a file for a current directory after some of its subdir
1189 // is parsed. This only leads to redundant walks, ignore it.
1190 if (!Name.empty())
1191 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1192 for (std::unique_ptr<Entry> &SubEntry :
1193 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1194 uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1195 break;
1196 }
1197 case EK_File: {
1198 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1199 assert(FE && "Must be a file");
1200 assert(NewParentE && "Parent entry must exist");
1201 auto *DE = dyn_cast<RedirectingDirectoryEntry>(NewParentE);
1202 DE->addContent(llvm::make_unique<RedirectingFileEntry>(
1203 Name, FE->getExternalContentsPath(), FE->getUseName()));
1204 break;
1205 }
1206 }
1207 }
1208
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001209 std::unique_ptr<Entry> parseEntry(yaml::Node *N, RedirectingFileSystem *FS) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001210 auto *M = dyn_cast<yaml::MappingNode>(N);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001211 if (!M) {
1212 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +00001213 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001214 }
1215
1216 KeyStatusPair Fields[] = {
1217 KeyStatusPair("name", true),
1218 KeyStatusPair("type", true),
1219 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001220 KeyStatusPair("external-contents", false),
1221 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001222 };
1223
Craig Topperac67c052015-11-30 03:11:10 +00001224 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001225
1226 bool HasContents = false; // external or otherwise
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001227 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001228 std::string ExternalContentsPath;
1229 std::string Name;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001230 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001231 EntryKind Kind;
1232
Eugene Zelenko5a520112018-03-28 22:09:09 +00001233 for (auto &I : *M) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001234 StringRef Key;
1235 // Reuse the buffer for key and value, since we don't look at key after
1236 // parsing value.
1237 SmallString<256> Buffer;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001238 if (!parseScalarString(I.getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001239 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001240
Eugene Zelenko5a520112018-03-28 22:09:09 +00001241 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001242 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001243
1244 StringRef Value;
1245 if (Key == "name") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001246 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001247 return nullptr;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001248
1249 if (FS->UseCanonicalizedPaths) {
1250 SmallString<256> Path(Value);
1251 // Guarantee that old YAML files containing paths with ".." and "."
1252 // are properly canonicalized before read into the VFS.
1253 Path = sys::path::remove_leading_dotslash(Path);
1254 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1255 Name = Path.str();
1256 } else {
1257 Name = Value;
1258 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001259 } else if (Key == "type") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001260 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001261 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001262 if (Value == "file")
1263 Kind = EK_File;
1264 else if (Value == "directory")
1265 Kind = EK_Directory;
1266 else {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001267 error(I.getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +00001268 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001269 }
1270 } else if (Key == "contents") {
1271 if (HasContents) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001272 error(I.getKey(),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001273 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001274 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001275 }
1276 HasContents = true;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001277 auto *Contents = dyn_cast<yaml::SequenceNode>(I.getValue());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001278 if (!Contents) {
1279 // FIXME: this is only for directories, what about files?
Eugene Zelenko5a520112018-03-28 22:09:09 +00001280 error(I.getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +00001281 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001282 }
1283
Eugene Zelenko5a520112018-03-28 22:09:09 +00001284 for (auto &I : *Contents) {
1285 if (std::unique_ptr<Entry> E = parseEntry(&I, FS))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001286 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001287 else
Craig Topperf1186c52014-05-08 06:41:40 +00001288 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001289 }
1290 } else if (Key == "external-contents") {
1291 if (HasContents) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001292 error(I.getKey(),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001293 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001294 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001295 }
1296 HasContents = true;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001297 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001298 return nullptr;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001299
1300 SmallString<256> FullPath;
1301 if (FS->IsRelativeOverlay) {
1302 FullPath = FS->getExternalContentsPrefixDir();
1303 assert(!FullPath.empty() &&
1304 "External contents prefix directory must exist");
1305 llvm::sys::path::append(FullPath, Value);
1306 } else {
1307 FullPath = Value;
1308 }
1309
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001310 if (FS->UseCanonicalizedPaths) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001311 // Guarantee that old YAML files containing paths with ".." and "."
1312 // are properly canonicalized before read into the VFS.
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001313 FullPath = sys::path::remove_leading_dotslash(FullPath);
1314 sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001315 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001316 ExternalContentsPath = FullPath.str();
Ben Langmuirb59cf672014-02-27 00:25:12 +00001317 } else if (Key == "use-external-name") {
1318 bool Val;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001319 if (!parseScalarBool(I.getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001320 return nullptr;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001321 UseExternalName = Val ? RedirectingFileEntry::NK_External
1322 : RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001323 } else {
1324 llvm_unreachable("key missing from Keys");
1325 }
1326 }
1327
1328 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001329 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001330
1331 // check for missing keys
1332 if (!HasContents) {
1333 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001334 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001335 }
1336 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001337 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001338
Ben Langmuirb59cf672014-02-27 00:25:12 +00001339 // check invalid configuration
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001340 if (Kind == EK_Directory &&
1341 UseExternalName != RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001342 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001343 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001344 }
1345
Ben Langmuir93853232014-03-05 21:32:20 +00001346 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001347 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001348 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1349 while (Trimmed.size() > RootPathLen &&
1350 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001351 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1352 // Get the last component
1353 StringRef LastComponent = sys::path::filename(Trimmed);
1354
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001355 std::unique_ptr<Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001356 switch (Kind) {
1357 case EK_File:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001358 Result = llvm::make_unique<RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001359 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001360 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001361 case EK_Directory:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001362 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001363 LastComponent, std::move(EntryArrayContents),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001364 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1365 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001366 break;
1367 }
1368
1369 StringRef Parent = sys::path::parent_path(Trimmed);
1370 if (Parent.empty())
1371 return Result;
1372
1373 // if 'name' contains multiple components, create implicit directory entries
1374 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1375 E = sys::path::rend(Parent);
1376 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001377 std::vector<std::unique_ptr<Entry>> Entries;
1378 Entries.push_back(std::move(Result));
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001379 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001380 *I, std::move(Entries),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001381 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1382 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001383 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001384 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001385 }
1386
1387public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001388 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001389
1390 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001391 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001392 auto *Top = dyn_cast<yaml::MappingNode>(Root);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001393 if (!Top) {
1394 error(Root, "expected mapping node");
1395 return false;
1396 }
1397
1398 KeyStatusPair Fields[] = {
1399 KeyStatusPair("version", true),
1400 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001401 KeyStatusPair("use-external-names", false),
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001402 KeyStatusPair("overlay-relative", false),
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001403 KeyStatusPair("ignore-non-existent-contents", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001404 KeyStatusPair("roots", true),
1405 };
1406
Craig Topperac67c052015-11-30 03:11:10 +00001407 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001408 std::vector<std::unique_ptr<Entry>> RootEntries;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001409
1410 // Parse configuration and 'roots'
Eugene Zelenko5a520112018-03-28 22:09:09 +00001411 for (auto &I : *Top) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001412 SmallString<10> KeyBuffer;
1413 StringRef Key;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001414 if (!parseScalarString(I.getKey(), Key, KeyBuffer))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001415 return false;
1416
Eugene Zelenko5a520112018-03-28 22:09:09 +00001417 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001418 return false;
1419
1420 if (Key == "roots") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001421 auto *Roots = dyn_cast<yaml::SequenceNode>(I.getValue());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001422 if (!Roots) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001423 error(I.getValue(), "expected array");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001424 return false;
1425 }
1426
Eugene Zelenko5a520112018-03-28 22:09:09 +00001427 for (auto &I : *Roots) {
1428 if (std::unique_ptr<Entry> E = parseEntry(&I, FS))
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001429 RootEntries.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001430 else
1431 return false;
1432 }
1433 } else if (Key == "version") {
1434 StringRef VersionString;
1435 SmallString<4> Storage;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001436 if (!parseScalarString(I.getValue(), VersionString, Storage))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001437 return false;
1438 int Version;
1439 if (VersionString.getAsInteger<int>(10, Version)) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001440 error(I.getValue(), "expected integer");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001441 return false;
1442 }
1443 if (Version < 0) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001444 error(I.getValue(), "invalid version number");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001445 return false;
1446 }
1447 if (Version != 0) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001448 error(I.getValue(), "version mismatch, expected 0");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001449 return false;
1450 }
1451 } else if (Key == "case-sensitive") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001452 if (!parseScalarBool(I.getValue(), FS->CaseSensitive))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001453 return false;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001454 } else if (Key == "overlay-relative") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001455 if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay))
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001456 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001457 } else if (Key == "use-external-names") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001458 if (!parseScalarBool(I.getValue(), FS->UseExternalNames))
Ben Langmuirb59cf672014-02-27 00:25:12 +00001459 return false;
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001460 } else if (Key == "ignore-non-existent-contents") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001461 if (!parseScalarBool(I.getValue(), FS->IgnoreNonExistentContents))
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001462 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001463 } else {
1464 llvm_unreachable("key missing from Keys");
1465 }
1466 }
1467
1468 if (Stream.failed())
1469 return false;
1470
1471 if (!checkMissingKeys(Top, Keys))
1472 return false;
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001473
1474 // Now that we sucessefully parsed the YAML file, canonicalize the internal
1475 // representation to a proper directory tree so that we can search faster
1476 // inside the VFS.
Eugene Zelenko5a520112018-03-28 22:09:09 +00001477 for (auto &E : RootEntries)
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001478 uniqueOverlayTree(FS, E.get());
1479
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001480 return true;
1481 }
1482};
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001483
Eugene Zelenko5a520112018-03-28 22:09:09 +00001484} // namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001485
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001486RedirectingFileSystem *
1487RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1488 SourceMgr::DiagHandlerTy DiagHandler,
1489 StringRef YAMLFilePath, void *DiagContext,
1490 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001491 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001492 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001493
Ben Langmuir97882e72014-02-24 20:56:37 +00001494 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001495 yaml::document_iterator DI = Stream.begin();
1496 yaml::Node *Root = DI->getRoot();
1497 if (DI == Stream.end() || !Root) {
1498 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001499 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001500 }
1501
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001502 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001503
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001504 std::unique_ptr<RedirectingFileSystem> FS(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001505 new RedirectingFileSystem(std::move(ExternalFS)));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001506
1507 if (!YAMLFilePath.empty()) {
1508 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1509 // to each 'external-contents' path.
1510 //
1511 // Example:
1512 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
1513 // yields:
1514 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1515 //
1516 SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1517 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1518 assert(!EC && "Overlay dir final path must be absolute");
1519 (void)EC;
1520 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1521 }
1522
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001523 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001524 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001525
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001526 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001527}
1528
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001529ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001530 SmallString<256> Path;
1531 Path_.toVector(Path);
1532
1533 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001534 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001535 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001536
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001537 // Canonicalize path by removing ".", "..", "./", etc components. This is
1538 // a VFS request, do bot bother about symlinks in the path components
1539 // but canonicalize in order to perform the correct entry search.
1540 if (UseCanonicalizedPaths) {
1541 Path = sys::path::remove_leading_dotslash(Path);
1542 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1543 }
1544
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001545 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001546 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001547
1548 sys::path::const_iterator Start = sys::path::begin(Path);
1549 sys::path::const_iterator End = sys::path::end(Path);
Eugene Zelenko5a520112018-03-28 22:09:09 +00001550 for (const auto &Root : Roots) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001551 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001552 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001553 return Result;
1554 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001555 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001556}
1557
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001558ErrorOr<Entry *>
1559RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1560 sys::path::const_iterator End, Entry *From) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001561#ifndef LLVM_ON_WIN32
1562 assert(!isTraversalComponent(*Start) &&
1563 !isTraversalComponent(From->getName()) &&
1564 "Paths should not contain traversal components");
1565#else
1566 // FIXME: this is here to support windows, remove it once canonicalized
1567 // paths become globally default.
Bruno Cardoso Lopesbe056b12016-02-23 17:06:50 +00001568 if (Start->equals("."))
1569 ++Start;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001570#endif
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001571
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001572 StringRef FromName = From->getName();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001573
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001574 // Forward the search to the next component in case this is an empty one.
1575 if (!FromName.empty()) {
1576 if (CaseSensitive ? !Start->equals(FromName)
1577 : !Start->equals_lower(FromName))
1578 // failure to match
1579 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001580
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001581 ++Start;
1582
1583 if (Start == End) {
1584 // Match!
1585 return From;
1586 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001587 }
1588
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001589 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001590 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001591 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001592
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001593 for (const std::unique_ptr<Entry> &DirEntry :
1594 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1595 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001596 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001597 return Result;
1598 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001599 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001600}
1601
Ben Langmuirf13302e2015-12-10 23:41:39 +00001602static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1603 Status ExternalStatus) {
1604 Status S = ExternalStatus;
1605 if (!UseExternalNames)
1606 S = Status::copyWithNewName(S, Path.str());
1607 S.IsVFSMapped = true;
1608 return S;
1609}
1610
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001611ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001612 assert(E != nullptr);
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001613 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001614 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001615 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuir5de00f32014-05-23 18:15:47 +00001616 if (S)
Ben Langmuirf13302e2015-12-10 23:41:39 +00001617 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1618 *S);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001619 return S;
1620 } else { // directory
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001621 auto *DE = cast<RedirectingDirectoryEntry>(E);
Ben Langmuirf13302e2015-12-10 23:41:39 +00001622 return Status::copyWithNewName(DE->getStatus(), Path.str());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001623 }
1624}
1625
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001626ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001627 ErrorOr<Entry *> Result = lookupPath(Path);
1628 if (!Result)
1629 return Result.getError();
1630 return status(Path, *Result);
1631}
1632
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001633namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001634
Ben Langmuirf13302e2015-12-10 23:41:39 +00001635/// Provide a file wrapper with an overriden status.
1636class FileWithFixedStatus : public File {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001637 std::unique_ptr<File> InnerFile;
Ben Langmuirf13302e2015-12-10 23:41:39 +00001638 Status S;
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001639
1640public:
Ben Langmuirf13302e2015-12-10 23:41:39 +00001641 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
Benjamin Kramercfeacf52016-05-27 14:27:13 +00001642 : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001643
Ben Langmuirf13302e2015-12-10 23:41:39 +00001644 ErrorOr<Status> status() override { return S; }
1645 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Eugene Zelenko5a520112018-03-28 22:09:09 +00001646
Benjamin Kramer737501c2015-10-05 21:20:19 +00001647 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1648 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001649 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1650 IsVolatile);
1651 }
Eugene Zelenko5a520112018-03-28 22:09:09 +00001652
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001653 std::error_code close() override { return InnerFile->close(); }
1654};
Eugene Zelenko5a520112018-03-28 22:09:09 +00001655
1656} // namespace
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001657
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001658ErrorOr<std::unique_ptr<File>>
1659RedirectingFileSystem::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001660 ErrorOr<Entry *> E = lookupPath(Path);
1661 if (!E)
1662 return E.getError();
1663
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001664 auto *F = dyn_cast<RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001665 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001666 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001667
Benjamin Kramera8857962014-10-26 22:44:13 +00001668 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1669 if (!Result)
1670 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001671
Ben Langmuirf13302e2015-12-10 23:41:39 +00001672 auto ExternalStatus = (*Result)->status();
1673 if (!ExternalStatus)
1674 return ExternalStatus.getError();
Ben Langmuird066d4c2014-02-28 21:16:07 +00001675
Ben Langmuirf13302e2015-12-10 23:41:39 +00001676 // FIXME: Update the status with the name and VFSMapped.
1677 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1678 *ExternalStatus);
1679 return std::unique_ptr<File>(
1680 llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001681}
1682
1683IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001684vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001685 SourceMgr::DiagHandlerTy DiagHandler,
1686 StringRef YAMLFilePath,
1687 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001688 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001689 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001690 YAMLFilePath, DiagContext,
1691 std::move(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001692}
1693
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001694static void getVFSEntries(Entry *SrcE, SmallVectorImpl<StringRef> &Path,
1695 SmallVectorImpl<YAMLVFSEntry> &Entries) {
1696 auto Kind = SrcE->getKind();
1697 if (Kind == EK_Directory) {
1698 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1699 assert(DE && "Must be a directory");
1700 for (std::unique_ptr<Entry> &SubEntry :
1701 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1702 Path.push_back(SubEntry->getName());
1703 getVFSEntries(SubEntry.get(), Path, Entries);
1704 Path.pop_back();
1705 }
1706 return;
1707 }
1708
1709 assert(Kind == EK_File && "Must be a EK_File");
1710 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1711 assert(FE && "Must be a file");
1712 SmallString<128> VPath;
1713 for (auto &Comp : Path)
1714 llvm::sys::path::append(VPath, Comp);
1715 Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
1716}
1717
1718void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1719 SourceMgr::DiagHandlerTy DiagHandler,
1720 StringRef YAMLFilePath,
1721 SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
1722 void *DiagContext,
1723 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1724 RedirectingFileSystem *VFS = RedirectingFileSystem::create(
1725 std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
1726 std::move(ExternalFS));
1727 ErrorOr<Entry *> RootE = VFS->lookupPath("/");
1728 if (!RootE)
1729 return;
1730 SmallVector<StringRef, 8> Components;
1731 Components.push_back("/");
1732 getVFSEntries(*RootE, Components, CollectedEntries);
1733}
1734
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001735UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001736 static std::atomic<unsigned> UID;
1737 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001738 // The following assumes that uint64_t max will never collide with a real
1739 // dev_t value from the OS.
1740 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1741}
Justin Bogner9c785292014-05-20 21:43:27 +00001742
Justin Bogner9c785292014-05-20 21:43:27 +00001743void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1744 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1745 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1746 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1747 Mappings.emplace_back(VirtualPath, RealPath);
1748}
1749
Justin Bogner44fa450342014-05-21 22:46:51 +00001750namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001751
Justin Bogner44fa450342014-05-21 22:46:51 +00001752class JSONWriter {
1753 llvm::raw_ostream &OS;
1754 SmallVector<StringRef, 16> DirStack;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001755
1756 unsigned getDirIndent() { return 4 * DirStack.size(); }
1757 unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
Justin Bogner44fa450342014-05-21 22:46:51 +00001758 bool containedIn(StringRef Parent, StringRef Path);
1759 StringRef containedPart(StringRef Parent, StringRef Path);
1760 void startDirectory(StringRef Path);
1761 void endDirectory();
1762 void writeEntry(StringRef VPath, StringRef RPath);
1763
1764public:
1765 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +00001766
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001767 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
1768 Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001769 Optional<bool> IgnoreNonExistentContents, StringRef OverlayDir);
Justin Bogner44fa450342014-05-21 22:46:51 +00001770};
Eugene Zelenko5a520112018-03-28 22:09:09 +00001771
1772} // namespace
Justin Bogner9c785292014-05-20 21:43:27 +00001773
Justin Bogner44fa450342014-05-21 22:46:51 +00001774bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001775 using namespace llvm::sys;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001776
Justin Bogner1c078f22014-05-20 22:12:58 +00001777 // Compare each path component.
1778 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1779 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1780 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1781 if (*IParent != *IChild)
1782 return false;
1783 }
1784 // Have we exhausted the parent path?
1785 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001786}
1787
Justin Bogner44fa450342014-05-21 22:46:51 +00001788StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1789 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001790 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001791 return Path.slice(Parent.size() + 1, StringRef::npos);
1792}
1793
Justin Bogner44fa450342014-05-21 22:46:51 +00001794void JSONWriter::startDirectory(StringRef Path) {
1795 StringRef Name =
1796 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1797 DirStack.push_back(Path);
1798 unsigned Indent = getDirIndent();
1799 OS.indent(Indent) << "{\n";
1800 OS.indent(Indent + 2) << "'type': 'directory',\n";
1801 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1802 OS.indent(Indent + 2) << "'contents': [\n";
1803}
1804
1805void JSONWriter::endDirectory() {
1806 unsigned Indent = getDirIndent();
1807 OS.indent(Indent + 2) << "]\n";
1808 OS.indent(Indent) << "}";
1809
1810 DirStack.pop_back();
1811}
1812
1813void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1814 unsigned Indent = getFileIndent();
1815 OS.indent(Indent) << "{\n";
1816 OS.indent(Indent + 2) << "'type': 'file',\n";
1817 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1818 OS.indent(Indent + 2) << "'external-contents': \""
1819 << llvm::yaml::escape(RPath) << "\"\n";
1820 OS.indent(Indent) << "}";
1821}
1822
1823void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001824 Optional<bool> UseExternalNames,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001825 Optional<bool> IsCaseSensitive,
1826 Optional<bool> IsOverlayRelative,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001827 Optional<bool> IgnoreNonExistentContents,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001828 StringRef OverlayDir) {
Justin Bogner44fa450342014-05-21 22:46:51 +00001829 using namespace llvm::sys;
1830
1831 OS << "{\n"
1832 " 'version': 0,\n";
1833 if (IsCaseSensitive.hasValue())
1834 OS << " 'case-sensitive': '"
1835 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001836 if (UseExternalNames.hasValue())
1837 OS << " 'use-external-names': '"
1838 << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001839 bool UseOverlayRelative = false;
1840 if (IsOverlayRelative.hasValue()) {
1841 UseOverlayRelative = IsOverlayRelative.getValue();
1842 OS << " 'overlay-relative': '"
1843 << (UseOverlayRelative ? "true" : "false") << "',\n";
1844 }
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001845 if (IgnoreNonExistentContents.hasValue())
1846 OS << " 'ignore-non-existent-contents': '"
1847 << (IgnoreNonExistentContents.getValue() ? "true" : "false") << "',\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001848 OS << " 'roots': [\n";
1849
Justin Bogner73466402014-07-15 01:24:35 +00001850 if (!Entries.empty()) {
1851 const YAMLVFSEntry &Entry = Entries.front();
1852 startDirectory(path::parent_path(Entry.VPath));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001853
1854 StringRef RPath = Entry.RPath;
1855 if (UseOverlayRelative) {
1856 unsigned OverlayDirLen = OverlayDir.size();
1857 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1858 "Overlay dir must be contained in RPath");
1859 RPath = RPath.slice(OverlayDirLen, RPath.size());
1860 }
1861
1862 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001863
Justin Bogner73466402014-07-15 01:24:35 +00001864 for (const auto &Entry : Entries.slice(1)) {
1865 StringRef Dir = path::parent_path(Entry.VPath);
1866 if (Dir == DirStack.back())
1867 OS << ",\n";
1868 else {
1869 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1870 OS << "\n";
1871 endDirectory();
1872 }
1873 OS << ",\n";
1874 startDirectory(Dir);
1875 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001876 StringRef RPath = Entry.RPath;
1877 if (UseOverlayRelative) {
1878 unsigned OverlayDirLen = OverlayDir.size();
1879 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1880 "Overlay dir must be contained in RPath");
1881 RPath = RPath.slice(OverlayDirLen, RPath.size());
1882 }
1883 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner73466402014-07-15 01:24:35 +00001884 }
1885
1886 while (!DirStack.empty()) {
1887 OS << "\n";
1888 endDirectory();
1889 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001890 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001891 }
1892
Justin Bogner73466402014-07-15 01:24:35 +00001893 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001894 << "}\n";
1895}
1896
Justin Bogner9c785292014-05-20 21:43:27 +00001897void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001898 llvm::sort(Mappings.begin(), Mappings.end(),
1899 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001900 return LHS.VPath < RHS.VPath;
1901 });
1902
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001903 JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001904 IsOverlayRelative, IgnoreNonExistentContents,
1905 OverlayDir);
Justin Bogner9c785292014-05-20 21:43:27 +00001906}
Ben Langmuir740812b2014-06-24 19:37:16 +00001907
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001908VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1909 const Twine &_Path, RedirectingFileSystem &FS,
1910 RedirectingDirectoryEntry::iterator Begin,
1911 RedirectingDirectoryEntry::iterator End, std::error_code &EC)
Ben Langmuir740812b2014-06-24 19:37:16 +00001912 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001913 while (Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001914 SmallString<128> PathStr(Dir);
1915 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001916 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001917 if (S) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001918 CurrentEntry = *S;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001919 return;
1920 }
1921 // Skip entries which do not map to a reliable external content.
1922 if (FS.ignoreNonExistentContents() &&
1923 S.getError() == llvm::errc::no_such_file_or_directory) {
1924 ++Current;
1925 continue;
1926 } else {
Ben Langmuir740812b2014-06-24 19:37:16 +00001927 EC = S.getError();
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001928 break;
1929 }
Ben Langmuir740812b2014-06-24 19:37:16 +00001930 }
1931}
1932
1933std::error_code VFSFromYamlDirIterImpl::increment() {
1934 assert(Current != End && "cannot iterate past end");
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001935 while (++Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001936 SmallString<128> PathStr(Dir);
1937 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001938 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001939 if (!S) {
1940 // Skip entries which do not map to a reliable external content.
1941 if (FS.ignoreNonExistentContents() &&
1942 S.getError() == llvm::errc::no_such_file_or_directory) {
1943 continue;
1944 } else {
1945 return S.getError();
1946 }
1947 }
Ben Langmuir740812b2014-06-24 19:37:16 +00001948 CurrentEntry = *S;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001949 break;
Bruno Cardoso Lopese43e2632016-08-12 02:17:26 +00001950 }
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001951
1952 if (Current == End)
1953 CurrentEntry = Status();
Eugene Zelenko5a520112018-03-28 22:09:09 +00001954 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001955}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001956
1957vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1958 const Twine &Path,
1959 std::error_code &EC)
1960 : FS(&FS_) {
1961 directory_iterator I = FS->dir_begin(Path, EC);
Juergen Ributzkaf9787432017-03-14 00:14:40 +00001962 if (I != directory_iterator()) {
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001963 State = std::make_shared<IterState>();
1964 State->push(I);
1965 }
1966}
1967
1968vfs::recursive_directory_iterator &
1969recursive_directory_iterator::increment(std::error_code &EC) {
1970 assert(FS && State && !State->empty() && "incrementing past end");
1971 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1972 vfs::directory_iterator End;
1973 if (State->top()->isDirectory()) {
1974 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001975 if (I != End) {
1976 State->push(I);
1977 return *this;
1978 }
1979 }
1980
1981 while (!State->empty() && State->top().increment(EC) == End)
1982 State->pop();
1983
1984 if (State->empty())
1985 State.reset(); // end iterator
1986
1987 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001988}