blob: 413d43994a3e41231331776e201ed9bc4e8c1fc7 [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) {
Max Moroze0975672018-04-04 19:47:25 +0000289 if (Iter != llvm::sys::fs::directory_iterator()) {
Ben Langmuir740812b2014-06-24 19:37:16 +0000290 llvm::sys::fs::file_status S;
Max Moroze0975672018-04-04 19:47:25 +0000291 std::error_code ErrorCode = llvm::sys::fs::status(Iter->path(), S, true);
Juergen Ributzkaf9787432017-03-14 00:14:40 +0000292 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Max Moroze0975672018-04-04 19:47:25 +0000293 if (!EC)
294 EC = ErrorCode;
Ben Langmuir740812b2014-06-24 19:37:16 +0000295 }
296 }
297
298 std::error_code increment() override {
299 std::error_code EC;
300 Iter.increment(EC);
Max Moroze0975672018-04-04 19:47:25 +0000301 if (Iter == llvm::sys::fs::directory_iterator()) {
Ben Langmuir740812b2014-06-24 19:37:16 +0000302 CurrentEntry = Status();
303 } else {
304 llvm::sys::fs::file_status S;
Max Moroze0975672018-04-04 19:47:25 +0000305 std::error_code ErrorCode = llvm::sys::fs::status(Iter->path(), S, true);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000306 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Max Moroze0975672018-04-04 19:47:25 +0000307 if (!EC)
308 EC = ErrorCode;
Ben Langmuir740812b2014-06-24 19:37:16 +0000309 }
310 return EC;
311 }
312};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000313
314} // namespace
Ben Langmuir740812b2014-06-24 19:37:16 +0000315
316directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
317 std::error_code &EC) {
318 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
319}
320
Ben Langmuirc8130a72014-02-20 21:59:23 +0000321//===-----------------------------------------------------------------------===/
322// OverlayFileSystem implementation
323//===-----------------------------------------------------------------------===/
Eugene Zelenko5a520112018-03-28 22:09:09 +0000324
Ben Langmuirc8130a72014-02-20 21:59:23 +0000325OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000326 FSList.push_back(std::move(BaseFS));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000327}
328
329void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
330 FSList.push_back(FS);
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000331 // Synchronize added file systems by duplicating the working directory from
332 // the first one in the list.
333 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000334}
335
336ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
337 // FIXME: handle symlinks that cross file systems
338 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
339 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000340 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000341 return Status;
342 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000343 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000344}
345
Benjamin Kramera8857962014-10-26 22:44:13 +0000346ErrorOr<std::unique_ptr<File>>
347OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000348 // FIXME: handle symlinks that cross file systems
349 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000350 auto Result = (*I)->openFileForRead(Path);
351 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
352 return Result;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000353 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000354 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000355}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000356
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000357llvm::ErrorOr<std::string>
358OverlayFileSystem::getCurrentWorkingDirectory() const {
359 // All file systems are synchronized, just take the first working directory.
360 return FSList.front()->getCurrentWorkingDirectory();
361}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000362
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000363std::error_code
364OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
365 for (auto &FS : FSList)
366 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
367 return EC;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000368 return {};
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000369}
370
Eugene Zelenko5a520112018-03-28 22:09:09 +0000371clang::vfs::detail::DirIterImpl::~DirIterImpl() = default;
Ben Langmuir740812b2014-06-24 19:37:16 +0000372
373namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000374
Ben Langmuir740812b2014-06-24 19:37:16 +0000375class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
376 OverlayFileSystem &Overlays;
377 std::string Path;
378 OverlayFileSystem::iterator CurrentFS;
379 directory_iterator CurrentDirIter;
380 llvm::StringSet<> SeenNames;
381
382 std::error_code incrementFS() {
383 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
384 ++CurrentFS;
385 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
386 std::error_code EC;
387 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
388 if (EC && EC != errc::no_such_file_or_directory)
389 return EC;
390 if (CurrentDirIter != directory_iterator())
391 break; // found
392 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000393 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +0000394 }
395
396 std::error_code incrementDirIter(bool IsFirstTime) {
397 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
398 "incrementing past end");
399 std::error_code EC;
400 if (!IsFirstTime)
401 CurrentDirIter.increment(EC);
402 if (!EC && CurrentDirIter == directory_iterator())
403 EC = incrementFS();
404 return EC;
405 }
406
407 std::error_code incrementImpl(bool IsFirstTime) {
408 while (true) {
409 std::error_code EC = incrementDirIter(IsFirstTime);
410 if (EC || CurrentDirIter == directory_iterator()) {
411 CurrentEntry = Status();
412 return EC;
413 }
414 CurrentEntry = *CurrentDirIter;
415 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
David Blaikie61b86d42014-11-19 02:56:13 +0000416 if (SeenNames.insert(Name).second)
Ben Langmuir740812b2014-06-24 19:37:16 +0000417 return EC; // name not seen before
418 }
419 llvm_unreachable("returned above");
420 }
421
422public:
423 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
424 std::error_code &EC)
425 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
426 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
427 EC = incrementImpl(true);
428 }
429
430 std::error_code increment() override { return incrementImpl(false); }
431};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000432
433} // namespace
Ben Langmuir740812b2014-06-24 19:37:16 +0000434
435directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
436 std::error_code &EC) {
437 return directory_iterator(
438 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
439}
440
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000441namespace clang {
442namespace vfs {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000443
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000444namespace detail {
445
446enum InMemoryNodeKind { IME_File, IME_Directory };
447
448/// The in memory file system is a tree of Nodes. Every node can either be a
449/// file or a directory.
450class InMemoryNode {
451 Status Stat;
452 InMemoryNodeKind Kind;
453
454public:
455 InMemoryNode(Status Stat, InMemoryNodeKind Kind)
456 : Stat(std::move(Stat)), Kind(Kind) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000457 virtual ~InMemoryNode() = default;
458
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000459 const Status &getStatus() const { return Stat; }
460 InMemoryNodeKind getKind() const { return Kind; }
461 virtual std::string toString(unsigned Indent) const = 0;
462};
463
464namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000465
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000466class InMemoryFile : public InMemoryNode {
467 std::unique_ptr<llvm::MemoryBuffer> Buffer;
468
469public:
470 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
471 : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
472
473 llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000474
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000475 std::string toString(unsigned Indent) const override {
476 return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
477 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000478
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000479 static bool classof(const InMemoryNode *N) {
480 return N->getKind() == IME_File;
481 }
482};
483
484/// Adapt a InMemoryFile for VFS' File interface.
485class InMemoryFileAdaptor : public File {
486 InMemoryFile &Node;
487
488public:
489 explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
490
491 llvm::ErrorOr<Status> status() override { return Node.getStatus(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000492
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000493 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Benjamin Kramer737501c2015-10-05 21:20:19 +0000494 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
495 bool IsVolatile) override {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000496 llvm::MemoryBuffer *Buf = Node.getBuffer();
497 return llvm::MemoryBuffer::getMemBuffer(
498 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
499 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000500
501 std::error_code close() override { return {}; }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000502};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000503
504} // namespace
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000505
506class InMemoryDirectory : public InMemoryNode {
507 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
508
509public:
510 InMemoryDirectory(Status Stat)
511 : InMemoryNode(std::move(Stat), IME_Directory) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000512
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000513 InMemoryNode *getChild(StringRef Name) {
514 auto I = Entries.find(Name);
515 if (I != Entries.end())
516 return I->second.get();
517 return nullptr;
518 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000519
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000520 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
521 return Entries.insert(make_pair(Name, std::move(Child)))
522 .first->second.get();
523 }
524
Eugene Zelenko5a520112018-03-28 22:09:09 +0000525 using const_iterator = decltype(Entries)::const_iterator;
526
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000527 const_iterator begin() const { return Entries.begin(); }
528 const_iterator end() const { return Entries.end(); }
529
530 std::string toString(unsigned Indent) const override {
531 std::string Result =
532 (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000533 for (const auto &Entry : Entries)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000534 Result += Entry.second->toString(Indent + 2);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000535 return Result;
536 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000537
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000538 static bool classof(const InMemoryNode *N) {
539 return N->getKind() == IME_Directory;
540 }
541};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000542
543} // namespace detail
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000544
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000545InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000546 : Root(new detail::InMemoryDirectory(
Pavel Labathac71c8e2016-11-09 10:52:22 +0000547 Status("", getNextVirtualUniqueID(), llvm::sys::TimePoint<>(), 0, 0,
548 0, llvm::sys::fs::file_type::directory_file,
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000549 llvm::sys::fs::perms::all_all))),
550 UseNormalizedPaths(UseNormalizedPaths) {}
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000551
Eugene Zelenko5a520112018-03-28 22:09:09 +0000552InMemoryFileSystem::~InMemoryFileSystem() = default;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000553
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000554std::string InMemoryFileSystem::toString() const {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000555 return Root->toString(/*Indent=*/0);
556}
557
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000558bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000559 std::unique_ptr<llvm::MemoryBuffer> Buffer,
560 Optional<uint32_t> User,
561 Optional<uint32_t> Group,
562 Optional<llvm::sys::fs::file_type> Type,
563 Optional<llvm::sys::fs::perms> Perms) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000564 SmallString<128> Path;
565 P.toVector(Path);
566
567 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000568 std::error_code EC = makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000569 assert(!EC);
570 (void)EC;
571
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000572 if (useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000573 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000574
575 if (Path.empty())
576 return false;
577
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000578 detail::InMemoryDirectory *Dir = Root.get();
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000579 auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path);
580 const auto ResolvedUser = User.getValueOr(0);
581 const auto ResolvedGroup = Group.getValueOr(0);
582 const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file);
583 const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all);
584 // Any intermediate directories we create should be accessible by
585 // the owner, even if Perms says otherwise for the final path.
586 const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000587 while (true) {
588 StringRef Name = *I;
589 detail::InMemoryNode *Node = Dir->getChild(Name);
590 ++I;
591 if (!Node) {
592 if (I == E) {
Ben Hamilton78381012017-11-16 19:34:08 +0000593 // End of the path, create a new file or directory.
Benjamin Kramer1b8dbe32015-10-06 14:45:16 +0000594 Status Stat(P.str(), getNextVirtualUniqueID(),
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000595 llvm::sys::toTimePoint(ModificationTime), ResolvedUser,
596 ResolvedGroup, Buffer->getBufferSize(), ResolvedType,
597 ResolvedPerms);
Ben Hamilton78381012017-11-16 19:34:08 +0000598 std::unique_ptr<detail::InMemoryNode> Child;
599 if (ResolvedType == sys::fs::file_type::directory_file) {
600 Child.reset(new detail::InMemoryDirectory(std::move(Stat)));
601 } else {
602 Child.reset(new detail::InMemoryFile(std::move(Stat),
603 std::move(Buffer)));
604 }
605 Dir->addChild(Name, std::move(Child));
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000606 return true;
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000607 }
608
609 // Create a new directory. Use the path up to here.
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000610 Status Stat(
611 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000612 getNextVirtualUniqueID(), llvm::sys::toTimePoint(ModificationTime),
613 ResolvedUser, ResolvedGroup, Buffer->getBufferSize(),
614 sys::fs::file_type::directory_file, NewDirectoryPerms);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000615 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
616 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
617 continue;
618 }
619
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000620 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000621 Dir = NewDir;
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000622 } else {
623 assert(isa<detail::InMemoryFile>(Node) &&
624 "Must be either file or directory!");
625
626 // Trying to insert a directory in place of a file.
627 if (I != E)
628 return false;
629
630 // Return false only if the new file is different from the existing one.
631 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
632 Buffer->getBuffer();
633 }
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000634 }
635}
636
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000637bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000638 llvm::MemoryBuffer *Buffer,
639 Optional<uint32_t> User,
640 Optional<uint32_t> Group,
641 Optional<llvm::sys::fs::file_type> Type,
642 Optional<llvm::sys::fs::perms> Perms) {
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000643 return addFile(P, ModificationTime,
644 llvm::MemoryBuffer::getMemBuffer(
Ben Hamiltone5af5bd2017-11-09 16:01:16 +0000645 Buffer->getBuffer(), Buffer->getBufferIdentifier()),
646 std::move(User), std::move(Group), std::move(Type),
647 std::move(Perms));
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000648}
649
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000650static ErrorOr<detail::InMemoryNode *>
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000651lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
652 const Twine &P) {
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000653 SmallString<128> Path;
654 P.toVector(Path);
655
656 // Fix up relative paths. This just prepends the current working directory.
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000657 std::error_code EC = FS.makeAbsolute(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000658 assert(!EC);
659 (void)EC;
660
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000661 if (FS.useNormalizedPaths())
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000662 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Benjamin Kramer4ad1c432015-10-12 13:30:38 +0000663
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000664 if (Path.empty())
Benjamin Kramerdecb2ae2015-10-09 13:03:22 +0000665 return Dir;
666
Benjamin Kramer71ce3762015-10-12 16:16:39 +0000667 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000668 while (true) {
669 detail::InMemoryNode *Node = Dir->getChild(*I);
670 ++I;
671 if (!Node)
672 return errc::no_such_file_or_directory;
673
674 // Return the file if it's at the end of the path.
675 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
676 if (I == E)
677 return File;
678 return errc::no_such_file_or_directory;
679 }
680
681 // Traverse directories.
682 Dir = cast<detail::InMemoryDirectory>(Node);
683 if (I == E)
684 return Dir;
685 }
686}
687
688llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000689 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000690 if (Node)
691 return (*Node)->getStatus();
692 return Node.getError();
693}
694
695llvm::ErrorOr<std::unique_ptr<File>>
696InMemoryFileSystem::openFileForRead(const Twine &Path) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000697 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000698 if (!Node)
699 return Node.getError();
700
701 // When we have a file provide a heap-allocated wrapper for the memory buffer
702 // to match the ownership semantics for File.
703 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
704 return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
705
706 // FIXME: errc::not_a_file?
707 return make_error_code(llvm::errc::invalid_argument);
708}
709
710namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000711
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000712/// Adaptor from InMemoryDir::iterator to directory_iterator.
713class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
714 detail::InMemoryDirectory::const_iterator I;
715 detail::InMemoryDirectory::const_iterator E;
716
717public:
Eugene Zelenko5a520112018-03-28 22:09:09 +0000718 InMemoryDirIterator() = default;
719
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000720 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
721 : I(Dir.begin()), E(Dir.end()) {
722 if (I != E)
723 CurrentEntry = I->second->getStatus();
724 }
725
726 std::error_code increment() override {
727 ++I;
728 // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
729 // the rest.
730 CurrentEntry = I != E ? I->second->getStatus() : Status();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000731 return {};
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000732 }
733};
Eugene Zelenko5a520112018-03-28 22:09:09 +0000734
735} // namespace
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000736
737directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
738 std::error_code &EC) {
Benjamin Kramer7708b2a2015-10-05 13:55:20 +0000739 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000740 if (!Node) {
741 EC = Node.getError();
742 return directory_iterator(std::make_shared<InMemoryDirIterator>());
743 }
744
745 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
746 return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
747
748 EC = make_error_code(llvm::errc::not_a_directory);
749 return directory_iterator(std::make_shared<InMemoryDirIterator>());
750}
Benjamin Kramere9e76072016-01-09 16:33:16 +0000751
752std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
753 SmallString<128> Path;
754 P.toVector(Path);
755
756 // Fix up relative paths. This just prepends the current working directory.
757 std::error_code EC = makeAbsolute(Path);
758 assert(!EC);
759 (void)EC;
760
761 if (useNormalizedPaths())
762 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
763
764 if (!Path.empty())
765 WorkingDirectory = Path.str();
Eugene Zelenko5a520112018-03-28 22:09:09 +0000766 return {};
Benjamin Kramere9e76072016-01-09 16:33:16 +0000767}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000768
769} // namespace vfs
770} // namespace clang
Benjamin Kramera25dcfd2015-10-05 13:55:14 +0000771
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000772//===-----------------------------------------------------------------------===/
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000773// RedirectingFileSystem implementation
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000774//===-----------------------------------------------------------------------===/
775
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000776namespace {
777
778enum EntryKind {
779 EK_Directory,
780 EK_File
781};
782
783/// \brief A single file or directory in the VFS.
784class Entry {
785 EntryKind Kind;
786 std::string Name;
787
788public:
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000789 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000790 virtual ~Entry() = default;
791
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000792 StringRef getName() const { return Name; }
793 EntryKind getKind() const { return Kind; }
794};
795
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000796class RedirectingDirectoryEntry : public Entry {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000797 std::vector<std::unique_ptr<Entry>> Contents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000798 Status S;
799
800public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000801 RedirectingDirectoryEntry(StringRef Name,
802 std::vector<std::unique_ptr<Entry>> Contents,
803 Status S)
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000804 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000805 S(std::move(S)) {}
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000806 RedirectingDirectoryEntry(StringRef Name, Status S)
807 : Entry(EK_Directory, Name), S(std::move(S)) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000808
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000809 Status getStatus() { return S; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000810
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000811 void addContent(std::unique_ptr<Entry> Content) {
812 Contents.push_back(std::move(Content));
813 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000814
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000815 Entry *getLastContent() const { return Contents.back().get(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000816
817 using iterator = decltype(Contents)::iterator;
818
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000819 iterator contents_begin() { return Contents.begin(); }
820 iterator contents_end() { return Contents.end(); }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000821
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000822 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
823};
824
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000825class RedirectingFileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000826public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000827 enum NameKind {
828 NK_NotSet,
829 NK_External,
830 NK_Virtual
831 };
Eugene Zelenko5a520112018-03-28 22:09:09 +0000832
Ben Langmuirb59cf672014-02-27 00:25:12 +0000833private:
834 std::string ExternalContentsPath;
835 NameKind UseName;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000836
Ben Langmuirb59cf672014-02-27 00:25:12 +0000837public:
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000838 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
839 NameKind UseName)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000840 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
841 UseName(UseName) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +0000842
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000843 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000844
Ben Langmuirb59cf672014-02-27 00:25:12 +0000845 /// \brief whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000846 bool useExternalName(bool GlobalUseExternalName) const {
847 return UseName == NK_NotSet ? GlobalUseExternalName
848 : (UseName == NK_External);
849 }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000850
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +0000851 NameKind getUseName() const { return UseName; }
Eugene Zelenko5a520112018-03-28 22:09:09 +0000852
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000853 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
854};
855
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000856class RedirectingFileSystem;
Ben Langmuir740812b2014-06-24 19:37:16 +0000857
858class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
859 std::string Dir;
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000860 RedirectingFileSystem &FS;
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000861 RedirectingDirectoryEntry::iterator Current, End;
862
Ben Langmuir740812b2014-06-24 19:37:16 +0000863public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000864 VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
Benjamin Kramer49692ed2015-10-09 13:28:13 +0000865 RedirectingDirectoryEntry::iterator Begin,
866 RedirectingDirectoryEntry::iterator End,
867 std::error_code &EC);
Eugene Zelenko5a520112018-03-28 22:09:09 +0000868
Ben Langmuir740812b2014-06-24 19:37:16 +0000869 std::error_code increment() override;
870};
871
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000872/// \brief A virtual file system parsed from a YAML file.
873///
874/// Currently, this class allows creating virtual directories and mapping
875/// virtual file paths to existing external files, available in \c ExternalFS.
876///
877/// The basic structure of the parsed file is:
878/// \verbatim
879/// {
880/// 'version': <version number>,
881/// <optional configuration>
882/// 'roots': [
883/// <directory entries>
884/// ]
885/// }
886/// \endverbatim
887///
888/// All configuration options are optional.
889/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000890/// 'use-external-names': <boolean, default=true>
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000891/// 'overlay-relative': <boolean, default=false>
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000892/// 'ignore-non-existent-contents': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000893///
894/// Virtual directories are represented as
895/// \verbatim
896/// {
897/// 'type': 'directory',
898/// 'name': <string>,
899/// 'contents': [ <file or directory entries> ]
900/// }
901/// \endverbatim
902///
903/// The default attributes for virtual directories are:
904/// \verbatim
905/// MTime = now() when created
906/// Perms = 0777
907/// User = Group = 0
908/// Size = 0
909/// UniqueID = unspecified unique value
910/// \endverbatim
911///
912/// Re-mapped files are represented as
913/// \verbatim
914/// {
915/// 'type': 'file',
916/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000917/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000918/// 'external-contents': <path to external file>)
919/// }
920/// \endverbatim
921///
922/// and inherit their attributes from the external contents.
923///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000924/// In both cases, the 'name' field may contain multiple path components (e.g.
925/// /path/to/file). However, any directory that contains more than one child
926/// must be uniquely represented by a directory entry.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000927class RedirectingFileSystem : public vfs::FileSystem {
Eugene Zelenko5a520112018-03-28 22:09:09 +0000928 friend class RedirectingFileSystemParser;
929
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000930 /// The root(s) of the virtual file system.
931 std::vector<std::unique_ptr<Entry>> Roots;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000932
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000933 /// \brief The file system to use for external references.
934 IntrusiveRefCntPtr<FileSystem> ExternalFS;
Eugene Zelenko5a520112018-03-28 22:09:09 +0000935
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000936 /// If IsRelativeOverlay is set, this represents the directory
937 /// path that should be prefixed to each 'external-contents' entry
938 /// when reading from YAML files.
939 std::string ExternalContentsPrefixDir;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000940
941 /// @name Configuration
942 /// @{
943
944 /// \brief Whether to perform case-sensitive comparisons.
945 ///
946 /// Currently, case-insensitive matching only works correctly with ASCII.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000947 bool CaseSensitive = true;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000948
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000949 /// IsRelativeOverlay marks whether a IsExternalContentsPrefixDir path must
950 /// be prefixed in every 'external-contents' when reading from YAML files.
951 bool IsRelativeOverlay = false;
952
Ben Langmuirb59cf672014-02-27 00:25:12 +0000953 /// \brief Whether to use to use the value of 'external-contents' for the
954 /// names of files. This global value is overridable on a per-file basis.
Bruno Cardoso Lopesf6f1def2016-04-13 19:28:16 +0000955 bool UseExternalNames = true;
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +0000956
957 /// \brief Whether an invalid path obtained via 'external-contents' should
958 /// cause iteration on the VFS to stop. If 'true', the VFS should ignore
959 /// the entry and continue with the next. Allows YAML files to be shared
960 /// across multiple compiler invocations regardless of prior existent
961 /// paths in 'external-contents'. This global value is overridable on a
962 /// per-file basis.
963 bool IgnoreNonExistentContents = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000964 /// @}
965
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +0000966 /// Virtual file paths and external files could be canonicalized without "..",
967 /// "." and "./" in their paths. FIXME: some unittests currently fail on
968 /// win32 when using remove_dots and remove_leading_dotslash on paths.
969 bool UseCanonicalizedPaths =
970#ifdef LLVM_ON_WIN32
971 false;
972#else
973 true;
974#endif
975
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000976private:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000977 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000978 : ExternalFS(std::move(ExternalFS)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000979
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000980 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
981 /// recursing into the contents of \p From if it is a directory.
982 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
983 sys::path::const_iterator End, Entry *From);
984
Ben Langmuir740812b2014-06-24 19:37:16 +0000985 /// \brief Get the status of a given an \c Entry.
986 ErrorOr<Status> status(const Twine &Path, Entry *E);
987
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000988public:
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +0000989 /// \brief Looks up \p Path in \c Roots.
990 ErrorOr<Entry *> lookupPath(const Twine &Path);
991
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000992 /// \brief Parses \p Buffer, which is expected to be in YAML format and
993 /// returns a virtual file system representing its contents.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +0000994 static RedirectingFileSystem *
995 create(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +0000996 SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
997 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000998
Craig Toppera798a9d2014-03-02 09:32:10 +0000999 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +00001000 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +00001001
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001002 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
1003 return ExternalFS->getCurrentWorkingDirectory();
1004 }
Eugene Zelenko5a520112018-03-28 22:09:09 +00001005
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001006 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
1007 return ExternalFS->setCurrentWorkingDirectory(Path);
1008 }
1009
Ben Langmuir740812b2014-06-24 19:37:16 +00001010 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
1011 ErrorOr<Entry *> E = lookupPath(Dir);
1012 if (!E) {
1013 EC = E.getError();
Eugene Zelenko5a520112018-03-28 22:09:09 +00001014 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001015 }
1016 ErrorOr<Status> S = status(Dir, *E);
1017 if (!S) {
1018 EC = S.getError();
Eugene Zelenko5a520112018-03-28 22:09:09 +00001019 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001020 }
1021 if (!S->isDirectory()) {
1022 EC = std::error_code(static_cast<int>(errc::not_a_directory),
1023 std::system_category());
Eugene Zelenko5a520112018-03-28 22:09:09 +00001024 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001025 }
1026
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001027 auto *D = cast<RedirectingDirectoryEntry>(*E);
Ben Langmuir740812b2014-06-24 19:37:16 +00001028 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
1029 *this, D->contents_begin(), D->contents_end(), EC));
1030 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001031
1032 void setExternalContentsPrefixDir(StringRef PrefixDir) {
1033 ExternalContentsPrefixDir = PrefixDir.str();
1034 }
1035
1036 StringRef getExternalContentsPrefixDir() const {
1037 return ExternalContentsPrefixDir;
1038 }
1039
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001040 bool ignoreNonExistentContents() const {
1041 return IgnoreNonExistentContents;
1042 }
1043
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001044#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1045LLVM_DUMP_METHOD void dump() const {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001046 for (const auto &Root : Roots)
Bruno Cardoso Lopesb2e2e212016-05-06 23:21:57 +00001047 dumpEntry(Root.get());
1048 }
1049
1050LLVM_DUMP_METHOD void dumpEntry(Entry *E, int NumSpaces = 0) const {
1051 StringRef Name = E->getName();
1052 for (int i = 0, e = NumSpaces; i < e; ++i)
1053 dbgs() << " ";
1054 dbgs() << "'" << Name.str().c_str() << "'" << "\n";
1055
1056 if (E->getKind() == EK_Directory) {
1057 auto *DE = dyn_cast<RedirectingDirectoryEntry>(E);
1058 assert(DE && "Should be a directory");
1059
1060 for (std::unique_ptr<Entry> &SubEntry :
1061 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1062 dumpEntry(SubEntry.get(), NumSpaces+2);
1063 }
1064 }
1065#endif
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001066};
1067
1068/// \brief A helper class to hold the common YAML parsing state.
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001069class RedirectingFileSystemParser {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001070 yaml::Stream &Stream;
1071
1072 void error(yaml::Node *N, const Twine &Msg) {
1073 Stream.printError(N, Msg);
1074 }
1075
1076 // false on error
1077 bool parseScalarString(yaml::Node *N, StringRef &Result,
1078 SmallVectorImpl<char> &Storage) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001079 const auto *S = dyn_cast<yaml::ScalarNode>(N);
1080
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001081 if (!S) {
1082 error(N, "expected string");
1083 return false;
1084 }
1085 Result = S->getValue(Storage);
1086 return true;
1087 }
1088
1089 // false on error
1090 bool parseScalarBool(yaml::Node *N, bool &Result) {
1091 SmallString<5> Storage;
1092 StringRef Value;
1093 if (!parseScalarString(N, Value, Storage))
1094 return false;
1095
1096 if (Value.equals_lower("true") || Value.equals_lower("on") ||
1097 Value.equals_lower("yes") || Value == "1") {
1098 Result = true;
1099 return true;
1100 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
1101 Value.equals_lower("no") || Value == "0") {
1102 Result = false;
1103 return true;
1104 }
1105
1106 error(N, "expected boolean value");
1107 return false;
1108 }
1109
1110 struct KeyStatus {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001111 bool Required;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001112 bool Seen = false;
1113
1114 KeyStatus(bool Required = false) : Required(Required) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001115 };
Eugene Zelenko5a520112018-03-28 22:09:09 +00001116
1117 using KeyStatusPair = std::pair<StringRef, KeyStatus>;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001118
1119 // false on error
1120 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1121 DenseMap<StringRef, KeyStatus> &Keys) {
1122 if (!Keys.count(Key)) {
1123 error(KeyNode, "unknown key");
1124 return false;
1125 }
1126 KeyStatus &S = Keys[Key];
1127 if (S.Seen) {
1128 error(KeyNode, Twine("duplicate key '") + Key + "'");
1129 return false;
1130 }
1131 S.Seen = true;
1132 return true;
1133 }
1134
1135 // false on error
1136 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001137 for (const auto &I : Keys) {
1138 if (I.second.Required && !I.second.Seen) {
1139 error(Obj, Twine("missing key '") + I.first + "'");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001140 return false;
1141 }
1142 }
1143 return true;
1144 }
1145
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001146 Entry *lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1147 Entry *ParentEntry = nullptr) {
1148 if (!ParentEntry) { // Look for a existent root
Eugene Zelenko5a520112018-03-28 22:09:09 +00001149 for (const auto &Root : FS->Roots) {
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001150 if (Name.equals(Root->getName())) {
1151 ParentEntry = Root.get();
1152 return ParentEntry;
1153 }
1154 }
1155 } else { // Advance to the next component
1156 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1157 for (std::unique_ptr<Entry> &Content :
1158 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1159 auto *DirContent = dyn_cast<RedirectingDirectoryEntry>(Content.get());
1160 if (DirContent && Name.equals(Content->getName()))
1161 return DirContent;
1162 }
1163 }
1164
1165 // ... or create a new one
1166 std::unique_ptr<Entry> E = llvm::make_unique<RedirectingDirectoryEntry>(
Pavel Labathac71c8e2016-11-09 10:52:22 +00001167 Name,
1168 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1169 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001170
1171 if (!ParentEntry) { // Add a new root to the overlay
1172 FS->Roots.push_back(std::move(E));
1173 ParentEntry = FS->Roots.back().get();
1174 return ParentEntry;
1175 }
1176
1177 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1178 DE->addContent(std::move(E));
1179 return DE->getLastContent();
1180 }
1181
1182 void uniqueOverlayTree(RedirectingFileSystem *FS, Entry *SrcE,
1183 Entry *NewParentE = nullptr) {
1184 StringRef Name = SrcE->getName();
1185 switch (SrcE->getKind()) {
1186 case EK_Directory: {
1187 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1188 assert(DE && "Must be a directory");
1189 // Empty directories could be present in the YAML as a way to
1190 // describe a file for a current directory after some of its subdir
1191 // is parsed. This only leads to redundant walks, ignore it.
1192 if (!Name.empty())
1193 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1194 for (std::unique_ptr<Entry> &SubEntry :
1195 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1196 uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1197 break;
1198 }
1199 case EK_File: {
1200 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1201 assert(FE && "Must be a file");
1202 assert(NewParentE && "Parent entry must exist");
1203 auto *DE = dyn_cast<RedirectingDirectoryEntry>(NewParentE);
1204 DE->addContent(llvm::make_unique<RedirectingFileEntry>(
1205 Name, FE->getExternalContentsPath(), FE->getUseName()));
1206 break;
1207 }
1208 }
1209 }
1210
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001211 std::unique_ptr<Entry> parseEntry(yaml::Node *N, RedirectingFileSystem *FS) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001212 auto *M = dyn_cast<yaml::MappingNode>(N);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001213 if (!M) {
1214 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +00001215 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001216 }
1217
1218 KeyStatusPair Fields[] = {
1219 KeyStatusPair("name", true),
1220 KeyStatusPair("type", true),
1221 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001222 KeyStatusPair("external-contents", false),
1223 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001224 };
1225
Craig Topperac67c052015-11-30 03:11:10 +00001226 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001227
1228 bool HasContents = false; // external or otherwise
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001229 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001230 std::string ExternalContentsPath;
1231 std::string Name;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001232 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001233 EntryKind Kind;
1234
Eugene Zelenko5a520112018-03-28 22:09:09 +00001235 for (auto &I : *M) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001236 StringRef Key;
1237 // Reuse the buffer for key and value, since we don't look at key after
1238 // parsing value.
1239 SmallString<256> Buffer;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001240 if (!parseScalarString(I.getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001241 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001242
Eugene Zelenko5a520112018-03-28 22:09:09 +00001243 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001244 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001245
1246 StringRef Value;
1247 if (Key == "name") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001248 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001249 return nullptr;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001250
1251 if (FS->UseCanonicalizedPaths) {
1252 SmallString<256> Path(Value);
1253 // Guarantee that old YAML files containing paths with ".." and "."
1254 // are properly canonicalized before read into the VFS.
1255 Path = sys::path::remove_leading_dotslash(Path);
1256 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1257 Name = Path.str();
1258 } else {
1259 Name = Value;
1260 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001261 } else if (Key == "type") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001262 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001263 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001264 if (Value == "file")
1265 Kind = EK_File;
1266 else if (Value == "directory")
1267 Kind = EK_Directory;
1268 else {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001269 error(I.getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +00001270 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001271 }
1272 } else if (Key == "contents") {
1273 if (HasContents) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001274 error(I.getKey(),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001275 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001276 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001277 }
1278 HasContents = true;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001279 auto *Contents = dyn_cast<yaml::SequenceNode>(I.getValue());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001280 if (!Contents) {
1281 // FIXME: this is only for directories, what about files?
Eugene Zelenko5a520112018-03-28 22:09:09 +00001282 error(I.getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +00001283 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001284 }
1285
Eugene Zelenko5a520112018-03-28 22:09:09 +00001286 for (auto &I : *Contents) {
1287 if (std::unique_ptr<Entry> E = parseEntry(&I, FS))
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001288 EntryArrayContents.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001289 else
Craig Topperf1186c52014-05-08 06:41:40 +00001290 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001291 }
1292 } else if (Key == "external-contents") {
1293 if (HasContents) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001294 error(I.getKey(),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001295 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001296 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001297 }
1298 HasContents = true;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001299 if (!parseScalarString(I.getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +00001300 return nullptr;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001301
1302 SmallString<256> FullPath;
1303 if (FS->IsRelativeOverlay) {
1304 FullPath = FS->getExternalContentsPrefixDir();
1305 assert(!FullPath.empty() &&
1306 "External contents prefix directory must exist");
1307 llvm::sys::path::append(FullPath, Value);
1308 } else {
1309 FullPath = Value;
1310 }
1311
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001312 if (FS->UseCanonicalizedPaths) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001313 // Guarantee that old YAML files containing paths with ".." and "."
1314 // are properly canonicalized before read into the VFS.
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001315 FullPath = sys::path::remove_leading_dotslash(FullPath);
1316 sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001317 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001318 ExternalContentsPath = FullPath.str();
Ben Langmuirb59cf672014-02-27 00:25:12 +00001319 } else if (Key == "use-external-name") {
1320 bool Val;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001321 if (!parseScalarBool(I.getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +00001322 return nullptr;
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001323 UseExternalName = Val ? RedirectingFileEntry::NK_External
1324 : RedirectingFileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001325 } else {
1326 llvm_unreachable("key missing from Keys");
1327 }
1328 }
1329
1330 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +00001331 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001332
1333 // check for missing keys
1334 if (!HasContents) {
1335 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +00001336 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001337 }
1338 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +00001339 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001340
Ben Langmuirb59cf672014-02-27 00:25:12 +00001341 // check invalid configuration
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001342 if (Kind == EK_Directory &&
1343 UseExternalName != RedirectingFileEntry::NK_NotSet) {
Ben Langmuirb59cf672014-02-27 00:25:12 +00001344 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +00001345 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001346 }
1347
Ben Langmuir93853232014-03-05 21:32:20 +00001348 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001349 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +00001350 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1351 while (Trimmed.size() > RootPathLen &&
1352 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001353 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1354 // Get the last component
1355 StringRef LastComponent = sys::path::filename(Trimmed);
1356
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001357 std::unique_ptr<Entry> Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001358 switch (Kind) {
1359 case EK_File:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001360 Result = llvm::make_unique<RedirectingFileEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001361 LastComponent, std::move(ExternalContentsPath), UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001362 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001363 case EK_Directory:
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001364 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramer268b51a2015-10-05 13:15:33 +00001365 LastComponent, std::move(EntryArrayContents),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001366 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1367 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001368 break;
1369 }
1370
1371 StringRef Parent = sys::path::parent_path(Trimmed);
1372 if (Parent.empty())
1373 return Result;
1374
1375 // if 'name' contains multiple components, create implicit directory entries
1376 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1377 E = sys::path::rend(Parent);
1378 I != E; ++I) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001379 std::vector<std::unique_ptr<Entry>> Entries;
1380 Entries.push_back(std::move(Result));
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001381 Result = llvm::make_unique<RedirectingDirectoryEntry>(
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001382 *I, std::move(Entries),
Pavel Labathac71c8e2016-11-09 10:52:22 +00001383 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1384 0, 0, 0, file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001385 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +00001386 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001387 }
1388
1389public:
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001390 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001391
1392 // false on error
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001393 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001394 auto *Top = dyn_cast<yaml::MappingNode>(Root);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001395 if (!Top) {
1396 error(Root, "expected mapping node");
1397 return false;
1398 }
1399
1400 KeyStatusPair Fields[] = {
1401 KeyStatusPair("version", true),
1402 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +00001403 KeyStatusPair("use-external-names", false),
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001404 KeyStatusPair("overlay-relative", false),
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001405 KeyStatusPair("ignore-non-existent-contents", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001406 KeyStatusPair("roots", true),
1407 };
1408
Craig Topperac67c052015-11-30 03:11:10 +00001409 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001410 std::vector<std::unique_ptr<Entry>> RootEntries;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001411
1412 // Parse configuration and 'roots'
Eugene Zelenko5a520112018-03-28 22:09:09 +00001413 for (auto &I : *Top) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001414 SmallString<10> KeyBuffer;
1415 StringRef Key;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001416 if (!parseScalarString(I.getKey(), Key, KeyBuffer))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001417 return false;
1418
Eugene Zelenko5a520112018-03-28 22:09:09 +00001419 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001420 return false;
1421
1422 if (Key == "roots") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001423 auto *Roots = dyn_cast<yaml::SequenceNode>(I.getValue());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001424 if (!Roots) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001425 error(I.getValue(), "expected array");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001426 return false;
1427 }
1428
Eugene Zelenko5a520112018-03-28 22:09:09 +00001429 for (auto &I : *Roots) {
1430 if (std::unique_ptr<Entry> E = parseEntry(&I, FS))
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001431 RootEntries.push_back(std::move(E));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001432 else
1433 return false;
1434 }
1435 } else if (Key == "version") {
1436 StringRef VersionString;
1437 SmallString<4> Storage;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001438 if (!parseScalarString(I.getValue(), VersionString, Storage))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001439 return false;
1440 int Version;
1441 if (VersionString.getAsInteger<int>(10, Version)) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001442 error(I.getValue(), "expected integer");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001443 return false;
1444 }
1445 if (Version < 0) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001446 error(I.getValue(), "invalid version number");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001447 return false;
1448 }
1449 if (Version != 0) {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001450 error(I.getValue(), "version mismatch, expected 0");
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001451 return false;
1452 }
1453 } else if (Key == "case-sensitive") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001454 if (!parseScalarBool(I.getValue(), FS->CaseSensitive))
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001455 return false;
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001456 } else if (Key == "overlay-relative") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001457 if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay))
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001458 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +00001459 } else if (Key == "use-external-names") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001460 if (!parseScalarBool(I.getValue(), FS->UseExternalNames))
Ben Langmuirb59cf672014-02-27 00:25:12 +00001461 return false;
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001462 } else if (Key == "ignore-non-existent-contents") {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001463 if (!parseScalarBool(I.getValue(), FS->IgnoreNonExistentContents))
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001464 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001465 } else {
1466 llvm_unreachable("key missing from Keys");
1467 }
1468 }
1469
1470 if (Stream.failed())
1471 return false;
1472
1473 if (!checkMissingKeys(Top, Keys))
1474 return false;
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001475
1476 // Now that we sucessefully parsed the YAML file, canonicalize the internal
1477 // representation to a proper directory tree so that we can search faster
1478 // inside the VFS.
Eugene Zelenko5a520112018-03-28 22:09:09 +00001479 for (auto &E : RootEntries)
Bruno Cardoso Lopesf6a0a722016-05-12 19:13:07 +00001480 uniqueOverlayTree(FS, E.get());
1481
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001482 return true;
1483 }
1484};
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001485
Eugene Zelenko5a520112018-03-28 22:09:09 +00001486} // namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001487
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001488RedirectingFileSystem *
1489RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1490 SourceMgr::DiagHandlerTy DiagHandler,
1491 StringRef YAMLFilePath, void *DiagContext,
1492 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001493 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00001494 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001495
Ben Langmuir97882e72014-02-24 20:56:37 +00001496 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001497 yaml::document_iterator DI = Stream.begin();
1498 yaml::Node *Root = DI->getRoot();
1499 if (DI == Stream.end() || !Root) {
1500 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +00001501 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001502 }
1503
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001504 RedirectingFileSystemParser P(Stream);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001505
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001506 std::unique_ptr<RedirectingFileSystem> FS(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001507 new RedirectingFileSystem(std::move(ExternalFS)));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001508
1509 if (!YAMLFilePath.empty()) {
1510 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1511 // to each 'external-contents' path.
1512 //
1513 // Example:
1514 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
1515 // yields:
1516 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1517 //
1518 SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1519 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1520 assert(!EC && "Overlay dir final path must be absolute");
1521 (void)EC;
1522 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1523 }
1524
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001525 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +00001526 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001527
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001528 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001529}
1530
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001531ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001532 SmallString<256> Path;
1533 Path_.toVector(Path);
1534
1535 // Handle relative paths
Benjamin Kramer7708b2a2015-10-05 13:55:20 +00001536 if (std::error_code EC = makeAbsolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001537 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001538
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001539 // Canonicalize path by removing ".", "..", "./", etc components. This is
1540 // a VFS request, do bot bother about symlinks in the path components
1541 // but canonicalize in order to perform the correct entry search.
1542 if (UseCanonicalizedPaths) {
1543 Path = sys::path::remove_leading_dotslash(Path);
1544 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1545 }
1546
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001547 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +00001548 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001549
1550 sys::path::const_iterator Start = sys::path::begin(Path);
1551 sys::path::const_iterator End = sys::path::end(Path);
Eugene Zelenko5a520112018-03-28 22:09:09 +00001552 for (const auto &Root : Roots) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001553 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001554 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001555 return Result;
1556 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001557 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001558}
1559
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001560ErrorOr<Entry *>
1561RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1562 sys::path::const_iterator End, Entry *From) {
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001563#ifndef LLVM_ON_WIN32
1564 assert(!isTraversalComponent(*Start) &&
1565 !isTraversalComponent(From->getName()) &&
1566 "Paths should not contain traversal components");
1567#else
1568 // FIXME: this is here to support windows, remove it once canonicalized
1569 // paths become globally default.
Bruno Cardoso Lopesbe056b12016-02-23 17:06:50 +00001570 if (Start->equals("."))
1571 ++Start;
Bruno Cardoso Lopesb76c0272016-03-17 02:20:43 +00001572#endif
Ben Langmuira6f8ca82014-03-04 22:34:50 +00001573
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001574 StringRef FromName = From->getName();
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001575
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001576 // Forward the search to the next component in case this is an empty one.
1577 if (!FromName.empty()) {
1578 if (CaseSensitive ? !Start->equals(FromName)
1579 : !Start->equals_lower(FromName))
1580 // failure to match
1581 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001582
Bruno Cardoso Lopesd712b342016-03-30 23:54:00 +00001583 ++Start;
1584
1585 if (Start == End) {
1586 // Match!
1587 return From;
1588 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001589 }
1590
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001591 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001592 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +00001593 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001594
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001595 for (const std::unique_ptr<Entry> &DirEntry :
1596 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1597 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
Rafael Espindola71de0b62014-06-13 17:20:50 +00001598 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001599 return Result;
1600 }
Rafael Espindola71de0b62014-06-13 17:20:50 +00001601 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001602}
1603
Ben Langmuirf13302e2015-12-10 23:41:39 +00001604static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1605 Status ExternalStatus) {
1606 Status S = ExternalStatus;
1607 if (!UseExternalNames)
1608 S = Status::copyWithNewName(S, Path.str());
1609 S.IsVFSMapped = true;
1610 return S;
1611}
1612
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001613ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001614 assert(E != nullptr);
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001615 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001616 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +00001617 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuir5de00f32014-05-23 18:15:47 +00001618 if (S)
Ben Langmuirf13302e2015-12-10 23:41:39 +00001619 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1620 *S);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001621 return S;
1622 } else { // directory
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001623 auto *DE = cast<RedirectingDirectoryEntry>(E);
Ben Langmuirf13302e2015-12-10 23:41:39 +00001624 return Status::copyWithNewName(DE->getStatus(), Path.str());
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001625 }
1626}
1627
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001628ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001629 ErrorOr<Entry *> Result = lookupPath(Path);
1630 if (!Result)
1631 return Result.getError();
1632 return status(Path, *Result);
1633}
1634
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001635namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001636
Ben Langmuirf13302e2015-12-10 23:41:39 +00001637/// Provide a file wrapper with an overriden status.
1638class FileWithFixedStatus : public File {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001639 std::unique_ptr<File> InnerFile;
Ben Langmuirf13302e2015-12-10 23:41:39 +00001640 Status S;
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001641
1642public:
Ben Langmuirf13302e2015-12-10 23:41:39 +00001643 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
Benjamin Kramercfeacf52016-05-27 14:27:13 +00001644 : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001645
Ben Langmuirf13302e2015-12-10 23:41:39 +00001646 ErrorOr<Status> status() override { return S; }
1647 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Eugene Zelenko5a520112018-03-28 22:09:09 +00001648
Benjamin Kramer737501c2015-10-05 21:20:19 +00001649 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1650 bool IsVolatile) override {
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001651 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1652 IsVolatile);
1653 }
Eugene Zelenko5a520112018-03-28 22:09:09 +00001654
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001655 std::error_code close() override { return InnerFile->close(); }
1656};
Eugene Zelenko5a520112018-03-28 22:09:09 +00001657
1658} // namespace
Benjamin Kramer5532ef12015-10-05 13:55:09 +00001659
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001660ErrorOr<std::unique_ptr<File>>
1661RedirectingFileSystem::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001662 ErrorOr<Entry *> E = lookupPath(Path);
1663 if (!E)
1664 return E.getError();
1665
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001666 auto *F = dyn_cast<RedirectingFileEntry>(*E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001667 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +00001668 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001669
Benjamin Kramera8857962014-10-26 22:44:13 +00001670 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1671 if (!Result)
1672 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +00001673
Ben Langmuirf13302e2015-12-10 23:41:39 +00001674 auto ExternalStatus = (*Result)->status();
1675 if (!ExternalStatus)
1676 return ExternalStatus.getError();
Ben Langmuird066d4c2014-02-28 21:16:07 +00001677
Ben Langmuirf13302e2015-12-10 23:41:39 +00001678 // FIXME: Update the status with the name and VFSMapped.
1679 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1680 *ExternalStatus);
1681 return std::unique_ptr<File>(
1682 llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001683}
1684
1685IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +00001686vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001687 SourceMgr::DiagHandlerTy DiagHandler,
1688 StringRef YAMLFilePath,
1689 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001690 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Benjamin Kramerdadb58b2015-10-07 10:05:44 +00001691 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001692 YAMLFilePath, DiagContext,
1693 std::move(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001694}
1695
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +00001696static void getVFSEntries(Entry *SrcE, SmallVectorImpl<StringRef> &Path,
1697 SmallVectorImpl<YAMLVFSEntry> &Entries) {
1698 auto Kind = SrcE->getKind();
1699 if (Kind == EK_Directory) {
1700 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1701 assert(DE && "Must be a directory");
1702 for (std::unique_ptr<Entry> &SubEntry :
1703 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1704 Path.push_back(SubEntry->getName());
1705 getVFSEntries(SubEntry.get(), Path, Entries);
1706 Path.pop_back();
1707 }
1708 return;
1709 }
1710
1711 assert(Kind == EK_File && "Must be a EK_File");
1712 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1713 assert(FE && "Must be a file");
1714 SmallString<128> VPath;
1715 for (auto &Comp : Path)
1716 llvm::sys::path::append(VPath, Comp);
1717 Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
1718}
1719
1720void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1721 SourceMgr::DiagHandlerTy DiagHandler,
1722 StringRef YAMLFilePath,
1723 SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
1724 void *DiagContext,
1725 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1726 RedirectingFileSystem *VFS = RedirectingFileSystem::create(
1727 std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
1728 std::move(ExternalFS));
1729 ErrorOr<Entry *> RootE = VFS->lookupPath("/");
1730 if (!RootE)
1731 return;
1732 SmallVector<StringRef, 8> Components;
1733 Components.push_back("/");
1734 getVFSEntries(*RootE, Components, CollectedEntries);
1735}
1736
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001737UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001738 static std::atomic<unsigned> UID;
1739 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001740 // The following assumes that uint64_t max will never collide with a real
1741 // dev_t value from the OS.
1742 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1743}
Justin Bogner9c785292014-05-20 21:43:27 +00001744
Justin Bogner9c785292014-05-20 21:43:27 +00001745void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1746 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1747 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1748 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1749 Mappings.emplace_back(VirtualPath, RealPath);
1750}
1751
Justin Bogner44fa450342014-05-21 22:46:51 +00001752namespace {
Eugene Zelenko5a520112018-03-28 22:09:09 +00001753
Justin Bogner44fa450342014-05-21 22:46:51 +00001754class JSONWriter {
1755 llvm::raw_ostream &OS;
1756 SmallVector<StringRef, 16> DirStack;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001757
1758 unsigned getDirIndent() { return 4 * DirStack.size(); }
1759 unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
Justin Bogner44fa450342014-05-21 22:46:51 +00001760 bool containedIn(StringRef Parent, StringRef Path);
1761 StringRef containedPart(StringRef Parent, StringRef Path);
1762 void startDirectory(StringRef Path);
1763 void endDirectory();
1764 void writeEntry(StringRef VPath, StringRef RPath);
1765
1766public:
1767 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
Eugene Zelenko5a520112018-03-28 22:09:09 +00001768
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001769 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
1770 Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001771 Optional<bool> IgnoreNonExistentContents, StringRef OverlayDir);
Justin Bogner44fa450342014-05-21 22:46:51 +00001772};
Eugene Zelenko5a520112018-03-28 22:09:09 +00001773
1774} // namespace
Justin Bogner9c785292014-05-20 21:43:27 +00001775
Justin Bogner44fa450342014-05-21 22:46:51 +00001776bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001777 using namespace llvm::sys;
Eugene Zelenko5a520112018-03-28 22:09:09 +00001778
Justin Bogner1c078f22014-05-20 22:12:58 +00001779 // Compare each path component.
1780 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1781 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1782 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1783 if (*IParent != *IChild)
1784 return false;
1785 }
1786 // Have we exhausted the parent path?
1787 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001788}
1789
Justin Bogner44fa450342014-05-21 22:46:51 +00001790StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1791 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001792 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001793 return Path.slice(Parent.size() + 1, StringRef::npos);
1794}
1795
Justin Bogner44fa450342014-05-21 22:46:51 +00001796void JSONWriter::startDirectory(StringRef Path) {
1797 StringRef Name =
1798 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1799 DirStack.push_back(Path);
1800 unsigned Indent = getDirIndent();
1801 OS.indent(Indent) << "{\n";
1802 OS.indent(Indent + 2) << "'type': 'directory',\n";
1803 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1804 OS.indent(Indent + 2) << "'contents': [\n";
1805}
1806
1807void JSONWriter::endDirectory() {
1808 unsigned Indent = getDirIndent();
1809 OS.indent(Indent + 2) << "]\n";
1810 OS.indent(Indent) << "}";
1811
1812 DirStack.pop_back();
1813}
1814
1815void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1816 unsigned Indent = getFileIndent();
1817 OS.indent(Indent) << "{\n";
1818 OS.indent(Indent + 2) << "'type': 'file',\n";
1819 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1820 OS.indent(Indent + 2) << "'external-contents': \""
1821 << llvm::yaml::escape(RPath) << "\"\n";
1822 OS.indent(Indent) << "}";
1823}
1824
1825void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001826 Optional<bool> UseExternalNames,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001827 Optional<bool> IsCaseSensitive,
1828 Optional<bool> IsOverlayRelative,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001829 Optional<bool> IgnoreNonExistentContents,
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001830 StringRef OverlayDir) {
Justin Bogner44fa450342014-05-21 22:46:51 +00001831 using namespace llvm::sys;
1832
1833 OS << "{\n"
1834 " 'version': 0,\n";
1835 if (IsCaseSensitive.hasValue())
1836 OS << " 'case-sensitive': '"
1837 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001838 if (UseExternalNames.hasValue())
1839 OS << " 'use-external-names': '"
1840 << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001841 bool UseOverlayRelative = false;
1842 if (IsOverlayRelative.hasValue()) {
1843 UseOverlayRelative = IsOverlayRelative.getValue();
1844 OS << " 'overlay-relative': '"
1845 << (UseOverlayRelative ? "true" : "false") << "',\n";
1846 }
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001847 if (IgnoreNonExistentContents.hasValue())
1848 OS << " 'ignore-non-existent-contents': '"
1849 << (IgnoreNonExistentContents.getValue() ? "true" : "false") << "',\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001850 OS << " 'roots': [\n";
1851
Justin Bogner73466402014-07-15 01:24:35 +00001852 if (!Entries.empty()) {
1853 const YAMLVFSEntry &Entry = Entries.front();
1854 startDirectory(path::parent_path(Entry.VPath));
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001855
1856 StringRef RPath = Entry.RPath;
1857 if (UseOverlayRelative) {
1858 unsigned OverlayDirLen = OverlayDir.size();
1859 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1860 "Overlay dir must be contained in RPath");
1861 RPath = RPath.slice(OverlayDirLen, RPath.size());
1862 }
1863
1864 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001865
Justin Bogner73466402014-07-15 01:24:35 +00001866 for (const auto &Entry : Entries.slice(1)) {
1867 StringRef Dir = path::parent_path(Entry.VPath);
1868 if (Dir == DirStack.back())
1869 OS << ",\n";
1870 else {
1871 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1872 OS << "\n";
1873 endDirectory();
1874 }
1875 OS << ",\n";
1876 startDirectory(Dir);
1877 }
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00001878 StringRef RPath = Entry.RPath;
1879 if (UseOverlayRelative) {
1880 unsigned OverlayDirLen = OverlayDir.size();
1881 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1882 "Overlay dir must be contained in RPath");
1883 RPath = RPath.slice(OverlayDirLen, RPath.size());
1884 }
1885 writeEntry(path::filename(Entry.VPath), RPath);
Justin Bogner73466402014-07-15 01:24:35 +00001886 }
1887
1888 while (!DirStack.empty()) {
1889 OS << "\n";
1890 endDirectory();
1891 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001892 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001893 }
1894
Justin Bogner73466402014-07-15 01:24:35 +00001895 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001896 << "}\n";
1897}
1898
Justin Bogner9c785292014-05-20 21:43:27 +00001899void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001900 llvm::sort(Mappings.begin(), Mappings.end(),
1901 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001902 return LHS.VPath < RHS.VPath;
1903 });
1904
Bruno Cardoso Lopesfc8644c2016-04-13 19:28:21 +00001905 JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
Bruno Cardoso Lopesb40d8ad2016-08-12 01:50:53 +00001906 IsOverlayRelative, IgnoreNonExistentContents,
1907 OverlayDir);
Justin Bogner9c785292014-05-20 21:43:27 +00001908}
Ben Langmuir740812b2014-06-24 19:37:16 +00001909
Benjamin Kramer49692ed2015-10-09 13:28:13 +00001910VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1911 const Twine &_Path, RedirectingFileSystem &FS,
1912 RedirectingDirectoryEntry::iterator Begin,
1913 RedirectingDirectoryEntry::iterator End, std::error_code &EC)
Ben Langmuir740812b2014-06-24 19:37:16 +00001914 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001915 while (Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001916 SmallString<128> PathStr(Dir);
1917 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001918 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001919 if (S) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001920 CurrentEntry = *S;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001921 return;
1922 }
1923 // Skip entries which do not map to a reliable external content.
1924 if (FS.ignoreNonExistentContents() &&
1925 S.getError() == llvm::errc::no_such_file_or_directory) {
1926 ++Current;
1927 continue;
1928 } else {
Ben Langmuir740812b2014-06-24 19:37:16 +00001929 EC = S.getError();
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001930 break;
1931 }
Ben Langmuir740812b2014-06-24 19:37:16 +00001932 }
1933}
1934
1935std::error_code VFSFromYamlDirIterImpl::increment() {
1936 assert(Current != End && "cannot iterate past end");
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001937 while (++Current != End) {
Ben Langmuir740812b2014-06-24 19:37:16 +00001938 SmallString<128> PathStr(Dir);
1939 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001940 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001941 if (!S) {
1942 // Skip entries which do not map to a reliable external content.
1943 if (FS.ignoreNonExistentContents() &&
1944 S.getError() == llvm::errc::no_such_file_or_directory) {
1945 continue;
1946 } else {
1947 return S.getError();
1948 }
1949 }
Ben Langmuir740812b2014-06-24 19:37:16 +00001950 CurrentEntry = *S;
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001951 break;
Bruno Cardoso Lopese43e2632016-08-12 02:17:26 +00001952 }
Bruno Cardoso Lopesb7abde02016-08-12 18:18:24 +00001953
1954 if (Current == End)
1955 CurrentEntry = Status();
Eugene Zelenko5a520112018-03-28 22:09:09 +00001956 return {};
Ben Langmuir740812b2014-06-24 19:37:16 +00001957}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001958
1959vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1960 const Twine &Path,
1961 std::error_code &EC)
1962 : FS(&FS_) {
1963 directory_iterator I = FS->dir_begin(Path, EC);
Juergen Ributzkaf9787432017-03-14 00:14:40 +00001964 if (I != directory_iterator()) {
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001965 State = std::make_shared<IterState>();
1966 State->push(I);
1967 }
1968}
1969
1970vfs::recursive_directory_iterator &
1971recursive_directory_iterator::increment(std::error_code &EC) {
1972 assert(FS && State && !State->empty() && "incrementing past end");
1973 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1974 vfs::directory_iterator End;
1975 if (State->top()->isDirectory()) {
1976 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001977 if (I != End) {
1978 State->push(I);
1979 return *this;
1980 }
1981 }
1982
1983 while (!State->empty() && State->top().increment(EC) == End)
1984 State->pop();
1985
1986 if (State->empty())
1987 State.reset(); // end iterator
1988
1989 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001990}