1 //===- VirtualFileSystem.cpp - Virtual File System Layer ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the VirtualFileSystem interface.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/Support/VirtualFileSystem.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/IntrusiveRefCntPtr.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/StringSet.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/Config/llvm-config.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/Chrono.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Errc.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/ErrorOr.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/Process.h"
38 #include "llvm/Support/SMLoc.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/YAMLParser.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <algorithm>
43 #include <atomic>
44 #include <cassert>
45 #include <cstdint>
46 #include <iterator>
47 #include <limits>
48 #include <map>
49 #include <memory>
50 #include <mutex>
51 #include <string>
52 #include <system_error>
53 #include <utility>
54 #include <vector>
55
56 using namespace llvm;
57 using namespace llvm::vfs;
58
59 using llvm::sys::fs::file_t;
60 using llvm::sys::fs::file_status;
61 using llvm::sys::fs::file_type;
62 using llvm::sys::fs::kInvalidFile;
63 using llvm::sys::fs::perms;
64 using llvm::sys::fs::UniqueID;
65
Status(const file_status & Status)66 Status::Status(const file_status &Status)
67 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
68 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
69 Type(Status.type()), Perms(Status.permissions()) {}
70
Status(const Twine & Name,UniqueID UID,sys::TimePoint<> MTime,uint32_t User,uint32_t Group,uint64_t Size,file_type Type,perms Perms)71 Status::Status(const Twine &Name, UniqueID UID, sys::TimePoint<> MTime,
72 uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
73 perms Perms)
74 : Name(Name.str()), UID(UID), MTime(MTime), User(User), Group(Group),
75 Size(Size), Type(Type), Perms(Perms) {}
76
copyWithNewName(const Status & In,const Twine & NewName)77 Status Status::copyWithNewName(const Status &In, const Twine &NewName) {
78 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
79 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
80 In.getPermissions());
81 }
82
copyWithNewName(const file_status & In,const Twine & NewName)83 Status Status::copyWithNewName(const file_status &In, const Twine &NewName) {
84 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
85 In.getUser(), In.getGroup(), In.getSize(), In.type(),
86 In.permissions());
87 }
88
equivalent(const Status & Other) const89 bool Status::equivalent(const Status &Other) const {
90 assert(isStatusKnown() && Other.isStatusKnown());
91 return getUniqueID() == Other.getUniqueID();
92 }
93
isDirectory() const94 bool Status::isDirectory() const { return Type == file_type::directory_file; }
95
isRegularFile() const96 bool Status::isRegularFile() const { return Type == file_type::regular_file; }
97
isOther() const98 bool Status::isOther() const {
99 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
100 }
101
isSymlink() const102 bool Status::isSymlink() const { return Type == file_type::symlink_file; }
103
isStatusKnown() const104 bool Status::isStatusKnown() const { return Type != file_type::status_error; }
105
exists() const106 bool Status::exists() const {
107 return isStatusKnown() && Type != file_type::file_not_found;
108 }
109
110 File::~File() = default;
111
112 FileSystem::~FileSystem() = default;
113
114 ErrorOr<std::unique_ptr<MemoryBuffer>>
getBufferForFile(const llvm::Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)115 FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
116 bool RequiresNullTerminator, bool IsVolatile) {
117 auto F = openFileForRead(Name);
118 if (!F)
119 return F.getError();
120
121 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
122 }
123
makeAbsolute(SmallVectorImpl<char> & Path) const124 std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
125 if (llvm::sys::path::is_absolute(Path))
126 return {};
127
128 auto WorkingDir = getCurrentWorkingDirectory();
129 if (!WorkingDir)
130 return WorkingDir.getError();
131
132 llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
133 return {};
134 }
135
getRealPath(const Twine & Path,SmallVectorImpl<char> & Output) const136 std::error_code FileSystem::getRealPath(const Twine &Path,
137 SmallVectorImpl<char> &Output) const {
138 return errc::operation_not_permitted;
139 }
140
isLocal(const Twine & Path,bool & Result)141 std::error_code FileSystem::isLocal(const Twine &Path, bool &Result) {
142 return errc::operation_not_permitted;
143 }
144
exists(const Twine & Path)145 bool FileSystem::exists(const Twine &Path) {
146 auto Status = status(Path);
147 return Status && Status->exists();
148 }
149
150 #ifndef NDEBUG
isTraversalComponent(StringRef Component)151 static bool isTraversalComponent(StringRef Component) {
152 return Component.equals("..") || Component.equals(".");
153 }
154
pathHasTraversal(StringRef Path)155 static bool pathHasTraversal(StringRef Path) {
156 using namespace llvm::sys;
157
158 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
159 if (isTraversalComponent(Comp))
160 return true;
161 return false;
162 }
163 #endif
164
165 //===-----------------------------------------------------------------------===/
166 // RealFileSystem implementation
167 //===-----------------------------------------------------------------------===/
168
169 namespace {
170
171 /// Wrapper around a raw file descriptor.
172 class RealFile : public File {
173 friend class RealFileSystem;
174
175 file_t FD;
176 Status S;
177 std::string RealName;
178
RealFile(file_t RawFD,StringRef NewName,StringRef NewRealPathName)179 RealFile(file_t RawFD, StringRef NewName, StringRef NewRealPathName)
180 : FD(RawFD), S(NewName, {}, {}, {}, {}, {},
181 llvm::sys::fs::file_type::status_error, {}),
182 RealName(NewRealPathName.str()) {
183 assert(FD != kInvalidFile && "Invalid or inactive file descriptor");
184 }
185
186 public:
187 ~RealFile() override;
188
189 ErrorOr<Status> status() override;
190 ErrorOr<std::string> getName() override;
191 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
192 int64_t FileSize,
193 bool RequiresNullTerminator,
194 bool IsVolatile) override;
195 std::error_code close() override;
196 };
197
198 } // namespace
199
~RealFile()200 RealFile::~RealFile() { close(); }
201
status()202 ErrorOr<Status> RealFile::status() {
203 assert(FD != kInvalidFile && "cannot stat closed file");
204 if (!S.isStatusKnown()) {
205 file_status RealStatus;
206 if (std::error_code EC = sys::fs::status(FD, RealStatus))
207 return EC;
208 S = Status::copyWithNewName(RealStatus, S.getName());
209 }
210 return S;
211 }
212
getName()213 ErrorOr<std::string> RealFile::getName() {
214 return RealName.empty() ? S.getName().str() : RealName;
215 }
216
217 ErrorOr<std::unique_ptr<MemoryBuffer>>
getBuffer(const Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)218 RealFile::getBuffer(const Twine &Name, int64_t FileSize,
219 bool RequiresNullTerminator, bool IsVolatile) {
220 assert(FD != kInvalidFile && "cannot get buffer for closed file");
221 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
222 IsVolatile);
223 }
224
close()225 std::error_code RealFile::close() {
226 std::error_code EC = sys::fs::closeFile(FD);
227 FD = kInvalidFile;
228 return EC;
229 }
230
231 namespace {
232
233 /// A file system according to your operating system.
234 /// This may be linked to the process's working directory, or maintain its own.
235 ///
236 /// Currently, its own working directory is emulated by storing the path and
237 /// sending absolute paths to llvm::sys::fs:: functions.
238 /// A more principled approach would be to push this down a level, modelling
239 /// the working dir as an llvm::sys::fs::WorkingDir or similar.
240 /// This would enable the use of openat()-style functions on some platforms.
241 class RealFileSystem : public FileSystem {
242 public:
RealFileSystem(bool LinkCWDToProcess)243 explicit RealFileSystem(bool LinkCWDToProcess) {
244 if (!LinkCWDToProcess) {
245 SmallString<128> PWD, RealPWD;
246 if (llvm::sys::fs::current_path(PWD))
247 return; // Awful, but nothing to do here.
248 if (llvm::sys::fs::real_path(PWD, RealPWD))
249 WD = {PWD, PWD};
250 else
251 WD = {PWD, RealPWD};
252 }
253 }
254
255 ErrorOr<Status> status(const Twine &Path) override;
256 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
257 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
258
259 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
260 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
261 std::error_code isLocal(const Twine &Path, bool &Result) override;
262 std::error_code getRealPath(const Twine &Path,
263 SmallVectorImpl<char> &Output) const override;
264
265 private:
266 // If this FS has its own working dir, use it to make Path absolute.
267 // The returned twine is safe to use as long as both Storage and Path live.
adjustPath(const Twine & Path,SmallVectorImpl<char> & Storage) const268 Twine adjustPath(const Twine &Path, SmallVectorImpl<char> &Storage) const {
269 if (!WD)
270 return Path;
271 Path.toVector(Storage);
272 sys::fs::make_absolute(WD->Resolved, Storage);
273 return Storage;
274 }
275
276 struct WorkingDirectory {
277 // The current working directory, without symlinks resolved. (echo $PWD).
278 SmallString<128> Specified;
279 // The current working directory, with links resolved. (readlink .).
280 SmallString<128> Resolved;
281 };
282 Optional<WorkingDirectory> WD;
283 };
284
285 } // namespace
286
status(const Twine & Path)287 ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
288 SmallString<256> Storage;
289 sys::fs::file_status RealStatus;
290 if (std::error_code EC =
291 sys::fs::status(adjustPath(Path, Storage), RealStatus))
292 return EC;
293 return Status::copyWithNewName(RealStatus, Path);
294 }
295
296 ErrorOr<std::unique_ptr<File>>
openFileForRead(const Twine & Name)297 RealFileSystem::openFileForRead(const Twine &Name) {
298 SmallString<256> RealName, Storage;
299 Expected<file_t> FDOrErr = sys::fs::openNativeFileForRead(
300 adjustPath(Name, Storage), sys::fs::OF_None, &RealName);
301 if (!FDOrErr)
302 return errorToErrorCode(FDOrErr.takeError());
303 return std::unique_ptr<File>(
304 new RealFile(*FDOrErr, Name.str(), RealName.str()));
305 }
306
getCurrentWorkingDirectory() const307 llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
308 if (WD)
309 return std::string(WD->Specified.str());
310
311 SmallString<128> Dir;
312 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
313 return EC;
314 return std::string(Dir.str());
315 }
316
setCurrentWorkingDirectory(const Twine & Path)317 std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
318 if (!WD)
319 return llvm::sys::fs::set_current_path(Path);
320
321 SmallString<128> Absolute, Resolved, Storage;
322 adjustPath(Path, Storage).toVector(Absolute);
323 bool IsDir;
324 if (auto Err = llvm::sys::fs::is_directory(Absolute, IsDir))
325 return Err;
326 if (!IsDir)
327 return std::make_error_code(std::errc::not_a_directory);
328 if (auto Err = llvm::sys::fs::real_path(Absolute, Resolved))
329 return Err;
330 WD = {Absolute, Resolved};
331 return std::error_code();
332 }
333
isLocal(const Twine & Path,bool & Result)334 std::error_code RealFileSystem::isLocal(const Twine &Path, bool &Result) {
335 SmallString<256> Storage;
336 return llvm::sys::fs::is_local(adjustPath(Path, Storage), Result);
337 }
338
339 std::error_code
getRealPath(const Twine & Path,SmallVectorImpl<char> & Output) const340 RealFileSystem::getRealPath(const Twine &Path,
341 SmallVectorImpl<char> &Output) const {
342 SmallString<256> Storage;
343 return llvm::sys::fs::real_path(adjustPath(Path, Storage), Output);
344 }
345
getRealFileSystem()346 IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
347 static IntrusiveRefCntPtr<FileSystem> FS(new RealFileSystem(true));
348 return FS;
349 }
350
createPhysicalFileSystem()351 std::unique_ptr<FileSystem> vfs::createPhysicalFileSystem() {
352 return std::make_unique<RealFileSystem>(false);
353 }
354
355 namespace {
356
357 class RealFSDirIter : public llvm::vfs::detail::DirIterImpl {
358 llvm::sys::fs::directory_iterator Iter;
359
360 public:
RealFSDirIter(const Twine & Path,std::error_code & EC)361 RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) {
362 if (Iter != llvm::sys::fs::directory_iterator())
363 CurrentEntry = directory_entry(Iter->path(), Iter->type());
364 }
365
increment()366 std::error_code increment() override {
367 std::error_code EC;
368 Iter.increment(EC);
369 CurrentEntry = (Iter == llvm::sys::fs::directory_iterator())
370 ? directory_entry()
371 : directory_entry(Iter->path(), Iter->type());
372 return EC;
373 }
374 };
375
376 } // namespace
377
dir_begin(const Twine & Dir,std::error_code & EC)378 directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
379 std::error_code &EC) {
380 SmallString<128> Storage;
381 return directory_iterator(
382 std::make_shared<RealFSDirIter>(adjustPath(Dir, Storage), EC));
383 }
384
385 //===-----------------------------------------------------------------------===/
386 // OverlayFileSystem implementation
387 //===-----------------------------------------------------------------------===/
388
OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS)389 OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
390 FSList.push_back(std::move(BaseFS));
391 }
392
pushOverlay(IntrusiveRefCntPtr<FileSystem> FS)393 void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
394 FSList.push_back(FS);
395 // Synchronize added file systems by duplicating the working directory from
396 // the first one in the list.
397 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
398 }
399
status(const Twine & Path)400 ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
401 // FIXME: handle symlinks that cross file systems
402 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
403 ErrorOr<Status> Status = (*I)->status(Path);
404 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
405 return Status;
406 }
407 return make_error_code(llvm::errc::no_such_file_or_directory);
408 }
409
410 ErrorOr<std::unique_ptr<File>>
openFileForRead(const llvm::Twine & Path)411 OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
412 // FIXME: handle symlinks that cross file systems
413 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
414 auto Result = (*I)->openFileForRead(Path);
415 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
416 return Result;
417 }
418 return make_error_code(llvm::errc::no_such_file_or_directory);
419 }
420
421 llvm::ErrorOr<std::string>
getCurrentWorkingDirectory() const422 OverlayFileSystem::getCurrentWorkingDirectory() const {
423 // All file systems are synchronized, just take the first working directory.
424 return FSList.front()->getCurrentWorkingDirectory();
425 }
426
427 std::error_code
setCurrentWorkingDirectory(const Twine & Path)428 OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
429 for (auto &FS : FSList)
430 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
431 return EC;
432 return {};
433 }
434
isLocal(const Twine & Path,bool & Result)435 std::error_code OverlayFileSystem::isLocal(const Twine &Path, bool &Result) {
436 for (auto &FS : FSList)
437 if (FS->exists(Path))
438 return FS->isLocal(Path, Result);
439 return errc::no_such_file_or_directory;
440 }
441
442 std::error_code
getRealPath(const Twine & Path,SmallVectorImpl<char> & Output) const443 OverlayFileSystem::getRealPath(const Twine &Path,
444 SmallVectorImpl<char> &Output) const {
445 for (auto &FS : FSList)
446 if (FS->exists(Path))
447 return FS->getRealPath(Path, Output);
448 return errc::no_such_file_or_directory;
449 }
450
451 llvm::vfs::detail::DirIterImpl::~DirIterImpl() = default;
452
453 namespace {
454
455 class OverlayFSDirIterImpl : public llvm::vfs::detail::DirIterImpl {
456 OverlayFileSystem &Overlays;
457 std::string Path;
458 OverlayFileSystem::iterator CurrentFS;
459 directory_iterator CurrentDirIter;
460 llvm::StringSet<> SeenNames;
461
incrementFS()462 std::error_code incrementFS() {
463 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
464 ++CurrentFS;
465 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
466 std::error_code EC;
467 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
468 if (EC && EC != errc::no_such_file_or_directory)
469 return EC;
470 if (CurrentDirIter != directory_iterator())
471 break; // found
472 }
473 return {};
474 }
475
incrementDirIter(bool IsFirstTime)476 std::error_code incrementDirIter(bool IsFirstTime) {
477 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
478 "incrementing past end");
479 std::error_code EC;
480 if (!IsFirstTime)
481 CurrentDirIter.increment(EC);
482 if (!EC && CurrentDirIter == directory_iterator())
483 EC = incrementFS();
484 return EC;
485 }
486
incrementImpl(bool IsFirstTime)487 std::error_code incrementImpl(bool IsFirstTime) {
488 while (true) {
489 std::error_code EC = incrementDirIter(IsFirstTime);
490 if (EC || CurrentDirIter == directory_iterator()) {
491 CurrentEntry = directory_entry();
492 return EC;
493 }
494 CurrentEntry = *CurrentDirIter;
495 StringRef Name = llvm::sys::path::filename(CurrentEntry.path());
496 if (SeenNames.insert(Name).second)
497 return EC; // name not seen before
498 }
499 llvm_unreachable("returned above");
500 }
501
502 public:
OverlayFSDirIterImpl(const Twine & Path,OverlayFileSystem & FS,std::error_code & EC)503 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
504 std::error_code &EC)
505 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
506 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
507 EC = incrementImpl(true);
508 }
509
increment()510 std::error_code increment() override { return incrementImpl(false); }
511 };
512
513 } // namespace
514
dir_begin(const Twine & Dir,std::error_code & EC)515 directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
516 std::error_code &EC) {
517 return directory_iterator(
518 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
519 }
520
anchor()521 void ProxyFileSystem::anchor() {}
522
523 namespace llvm {
524 namespace vfs {
525
526 namespace detail {
527
528 enum InMemoryNodeKind { IME_File, IME_Directory, IME_HardLink };
529
530 /// The in memory file system is a tree of Nodes. Every node can either be a
531 /// file , hardlink or a directory.
532 class InMemoryNode {
533 InMemoryNodeKind Kind;
534 std::string FileName;
535
536 public:
InMemoryNode(llvm::StringRef FileName,InMemoryNodeKind Kind)537 InMemoryNode(llvm::StringRef FileName, InMemoryNodeKind Kind)
538 : Kind(Kind), FileName(std::string(llvm::sys::path::filename(FileName))) {
539 }
540 virtual ~InMemoryNode() = default;
541
542 /// Get the filename of this node (the name without the directory part).
getFileName() const543 StringRef getFileName() const { return FileName; }
getKind() const544 InMemoryNodeKind getKind() const { return Kind; }
545 virtual std::string toString(unsigned Indent) const = 0;
546 };
547
548 class InMemoryFile : public InMemoryNode {
549 Status Stat;
550 std::unique_ptr<llvm::MemoryBuffer> Buffer;
551
552 public:
InMemoryFile(Status Stat,std::unique_ptr<llvm::MemoryBuffer> Buffer)553 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
554 : InMemoryNode(Stat.getName(), IME_File), Stat(std::move(Stat)),
555 Buffer(std::move(Buffer)) {}
556
557 /// Return the \p Status for this node. \p RequestedName should be the name
558 /// through which the caller referred to this node. It will override
559 /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
getStatus(const Twine & RequestedName) const560 Status getStatus(const Twine &RequestedName) const {
561 return Status::copyWithNewName(Stat, RequestedName);
562 }
getBuffer() const563 llvm::MemoryBuffer *getBuffer() const { return Buffer.get(); }
564
toString(unsigned Indent) const565 std::string toString(unsigned Indent) const override {
566 return (std::string(Indent, ' ') + Stat.getName() + "\n").str();
567 }
568
classof(const InMemoryNode * N)569 static bool classof(const InMemoryNode *N) {
570 return N->getKind() == IME_File;
571 }
572 };
573
574 namespace {
575
576 class InMemoryHardLink : public InMemoryNode {
577 const InMemoryFile &ResolvedFile;
578
579 public:
InMemoryHardLink(StringRef Path,const InMemoryFile & ResolvedFile)580 InMemoryHardLink(StringRef Path, const InMemoryFile &ResolvedFile)
581 : InMemoryNode(Path, IME_HardLink), ResolvedFile(ResolvedFile) {}
getResolvedFile() const582 const InMemoryFile &getResolvedFile() const { return ResolvedFile; }
583
toString(unsigned Indent) const584 std::string toString(unsigned Indent) const override {
585 return std::string(Indent, ' ') + "HardLink to -> " +
586 ResolvedFile.toString(0);
587 }
588
classof(const InMemoryNode * N)589 static bool classof(const InMemoryNode *N) {
590 return N->getKind() == IME_HardLink;
591 }
592 };
593
594 /// Adapt a InMemoryFile for VFS' File interface. The goal is to make
595 /// \p InMemoryFileAdaptor mimic as much as possible the behavior of
596 /// \p RealFile.
597 class InMemoryFileAdaptor : public File {
598 const InMemoryFile &Node;
599 /// The name to use when returning a Status for this file.
600 std::string RequestedName;
601
602 public:
InMemoryFileAdaptor(const InMemoryFile & Node,std::string RequestedName)603 explicit InMemoryFileAdaptor(const InMemoryFile &Node,
604 std::string RequestedName)
605 : Node(Node), RequestedName(std::move(RequestedName)) {}
606
status()607 llvm::ErrorOr<Status> status() override {
608 return Node.getStatus(RequestedName);
609 }
610
611 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
getBuffer(const Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)612 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
613 bool IsVolatile) override {
614 llvm::MemoryBuffer *Buf = Node.getBuffer();
615 return llvm::MemoryBuffer::getMemBuffer(
616 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
617 }
618
close()619 std::error_code close() override { return {}; }
620 };
621 } // namespace
622
623 class InMemoryDirectory : public InMemoryNode {
624 Status Stat;
625 llvm::StringMap<std::unique_ptr<InMemoryNode>> Entries;
626
627 public:
InMemoryDirectory(Status Stat)628 InMemoryDirectory(Status Stat)
629 : InMemoryNode(Stat.getName(), IME_Directory), Stat(std::move(Stat)) {}
630
631 /// Return the \p Status for this node. \p RequestedName should be the name
632 /// through which the caller referred to this node. It will override
633 /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
getStatus(const Twine & RequestedName) const634 Status getStatus(const Twine &RequestedName) const {
635 return Status::copyWithNewName(Stat, RequestedName);
636 }
getChild(StringRef Name)637 InMemoryNode *getChild(StringRef Name) {
638 auto I = Entries.find(Name);
639 if (I != Entries.end())
640 return I->second.get();
641 return nullptr;
642 }
643
addChild(StringRef Name,std::unique_ptr<InMemoryNode> Child)644 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
645 return Entries.insert(make_pair(Name, std::move(Child)))
646 .first->second.get();
647 }
648
649 using const_iterator = decltype(Entries)::const_iterator;
650
begin() const651 const_iterator begin() const { return Entries.begin(); }
end() const652 const_iterator end() const { return Entries.end(); }
653
toString(unsigned Indent) const654 std::string toString(unsigned Indent) const override {
655 std::string Result =
656 (std::string(Indent, ' ') + Stat.getName() + "\n").str();
657 for (const auto &Entry : Entries)
658 Result += Entry.second->toString(Indent + 2);
659 return Result;
660 }
661
classof(const InMemoryNode * N)662 static bool classof(const InMemoryNode *N) {
663 return N->getKind() == IME_Directory;
664 }
665 };
666
667 namespace {
getNodeStatus(const InMemoryNode * Node,const Twine & RequestedName)668 Status getNodeStatus(const InMemoryNode *Node, const Twine &RequestedName) {
669 if (auto Dir = dyn_cast<detail::InMemoryDirectory>(Node))
670 return Dir->getStatus(RequestedName);
671 if (auto File = dyn_cast<detail::InMemoryFile>(Node))
672 return File->getStatus(RequestedName);
673 if (auto Link = dyn_cast<detail::InMemoryHardLink>(Node))
674 return Link->getResolvedFile().getStatus(RequestedName);
675 llvm_unreachable("Unknown node type");
676 }
677 } // namespace
678 } // namespace detail
679
InMemoryFileSystem(bool UseNormalizedPaths)680 InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
681 : Root(new detail::InMemoryDirectory(
682 Status("", getNextVirtualUniqueID(), llvm::sys::TimePoint<>(), 0, 0,
683 0, llvm::sys::fs::file_type::directory_file,
684 llvm::sys::fs::perms::all_all))),
685 UseNormalizedPaths(UseNormalizedPaths) {}
686
687 InMemoryFileSystem::~InMemoryFileSystem() = default;
688
toString() const689 std::string InMemoryFileSystem::toString() const {
690 return Root->toString(/*Indent=*/0);
691 }
692
addFile(const Twine & P,time_t ModificationTime,std::unique_ptr<llvm::MemoryBuffer> Buffer,Optional<uint32_t> User,Optional<uint32_t> Group,Optional<llvm::sys::fs::file_type> Type,Optional<llvm::sys::fs::perms> Perms,const detail::InMemoryFile * HardLinkTarget)693 bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
694 std::unique_ptr<llvm::MemoryBuffer> Buffer,
695 Optional<uint32_t> User,
696 Optional<uint32_t> Group,
697 Optional<llvm::sys::fs::file_type> Type,
698 Optional<llvm::sys::fs::perms> Perms,
699 const detail::InMemoryFile *HardLinkTarget) {
700 SmallString<128> Path;
701 P.toVector(Path);
702
703 // Fix up relative paths. This just prepends the current working directory.
704 std::error_code EC = makeAbsolute(Path);
705 assert(!EC);
706 (void)EC;
707
708 if (useNormalizedPaths())
709 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
710
711 if (Path.empty())
712 return false;
713
714 detail::InMemoryDirectory *Dir = Root.get();
715 auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path);
716 const auto ResolvedUser = User.getValueOr(0);
717 const auto ResolvedGroup = Group.getValueOr(0);
718 const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file);
719 const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all);
720 assert(!(HardLinkTarget && Buffer) && "HardLink cannot have a buffer");
721 // Any intermediate directories we create should be accessible by
722 // the owner, even if Perms says otherwise for the final path.
723 const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
724 while (true) {
725 StringRef Name = *I;
726 detail::InMemoryNode *Node = Dir->getChild(Name);
727 ++I;
728 if (!Node) {
729 if (I == E) {
730 // End of the path.
731 std::unique_ptr<detail::InMemoryNode> Child;
732 if (HardLinkTarget)
733 Child.reset(new detail::InMemoryHardLink(P.str(), *HardLinkTarget));
734 else {
735 // Create a new file or directory.
736 Status Stat(P.str(), getNextVirtualUniqueID(),
737 llvm::sys::toTimePoint(ModificationTime), ResolvedUser,
738 ResolvedGroup, Buffer->getBufferSize(), ResolvedType,
739 ResolvedPerms);
740 if (ResolvedType == sys::fs::file_type::directory_file) {
741 Child.reset(new detail::InMemoryDirectory(std::move(Stat)));
742 } else {
743 Child.reset(
744 new detail::InMemoryFile(std::move(Stat), std::move(Buffer)));
745 }
746 }
747 Dir->addChild(Name, std::move(Child));
748 return true;
749 }
750
751 // Create a new directory. Use the path up to here.
752 Status Stat(
753 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
754 getNextVirtualUniqueID(), llvm::sys::toTimePoint(ModificationTime),
755 ResolvedUser, ResolvedGroup, 0, sys::fs::file_type::directory_file,
756 NewDirectoryPerms);
757 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
758 Name, std::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
759 continue;
760 }
761
762 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
763 Dir = NewDir;
764 } else {
765 assert((isa<detail::InMemoryFile>(Node) ||
766 isa<detail::InMemoryHardLink>(Node)) &&
767 "Must be either file, hardlink or directory!");
768
769 // Trying to insert a directory in place of a file.
770 if (I != E)
771 return false;
772
773 // Return false only if the new file is different from the existing one.
774 if (auto Link = dyn_cast<detail::InMemoryHardLink>(Node)) {
775 return Link->getResolvedFile().getBuffer()->getBuffer() ==
776 Buffer->getBuffer();
777 }
778 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
779 Buffer->getBuffer();
780 }
781 }
782 }
783
addFile(const Twine & P,time_t ModificationTime,std::unique_ptr<llvm::MemoryBuffer> Buffer,Optional<uint32_t> User,Optional<uint32_t> Group,Optional<llvm::sys::fs::file_type> Type,Optional<llvm::sys::fs::perms> Perms)784 bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
785 std::unique_ptr<llvm::MemoryBuffer> Buffer,
786 Optional<uint32_t> User,
787 Optional<uint32_t> Group,
788 Optional<llvm::sys::fs::file_type> Type,
789 Optional<llvm::sys::fs::perms> Perms) {
790 return addFile(P, ModificationTime, std::move(Buffer), User, Group, Type,
791 Perms, /*HardLinkTarget=*/nullptr);
792 }
793
addFileNoOwn(const Twine & P,time_t ModificationTime,const llvm::MemoryBufferRef & Buffer,Optional<uint32_t> User,Optional<uint32_t> Group,Optional<llvm::sys::fs::file_type> Type,Optional<llvm::sys::fs::perms> Perms)794 bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
795 const llvm::MemoryBufferRef &Buffer,
796 Optional<uint32_t> User,
797 Optional<uint32_t> Group,
798 Optional<llvm::sys::fs::file_type> Type,
799 Optional<llvm::sys::fs::perms> Perms) {
800 return addFile(P, ModificationTime, llvm::MemoryBuffer::getMemBuffer(Buffer),
801 std::move(User), std::move(Group), std::move(Type),
802 std::move(Perms));
803 }
804
805 static ErrorOr<const detail::InMemoryNode *>
lookupInMemoryNode(const InMemoryFileSystem & FS,detail::InMemoryDirectory * Dir,const Twine & P)806 lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
807 const Twine &P) {
808 SmallString<128> Path;
809 P.toVector(Path);
810
811 // Fix up relative paths. This just prepends the current working directory.
812 std::error_code EC = FS.makeAbsolute(Path);
813 assert(!EC);
814 (void)EC;
815
816 if (FS.useNormalizedPaths())
817 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
818
819 if (Path.empty())
820 return Dir;
821
822 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
823 while (true) {
824 detail::InMemoryNode *Node = Dir->getChild(*I);
825 ++I;
826 if (!Node)
827 return errc::no_such_file_or_directory;
828
829 // Return the file if it's at the end of the path.
830 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
831 if (I == E)
832 return File;
833 return errc::no_such_file_or_directory;
834 }
835
836 // If Node is HardLink then return the resolved file.
837 if (auto File = dyn_cast<detail::InMemoryHardLink>(Node)) {
838 if (I == E)
839 return &File->getResolvedFile();
840 return errc::no_such_file_or_directory;
841 }
842 // Traverse directories.
843 Dir = cast<detail::InMemoryDirectory>(Node);
844 if (I == E)
845 return Dir;
846 }
847 }
848
addHardLink(const Twine & FromPath,const Twine & ToPath)849 bool InMemoryFileSystem::addHardLink(const Twine &FromPath,
850 const Twine &ToPath) {
851 auto FromNode = lookupInMemoryNode(*this, Root.get(), FromPath);
852 auto ToNode = lookupInMemoryNode(*this, Root.get(), ToPath);
853 // FromPath must not have been added before. ToPath must have been added
854 // before. Resolved ToPath must be a File.
855 if (!ToNode || FromNode || !isa<detail::InMemoryFile>(*ToNode))
856 return false;
857 return this->addFile(FromPath, 0, nullptr, None, None, None, None,
858 cast<detail::InMemoryFile>(*ToNode));
859 }
860
status(const Twine & Path)861 llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
862 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
863 if (Node)
864 return detail::getNodeStatus(*Node, Path);
865 return Node.getError();
866 }
867
868 llvm::ErrorOr<std::unique_ptr<File>>
openFileForRead(const Twine & Path)869 InMemoryFileSystem::openFileForRead(const Twine &Path) {
870 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
871 if (!Node)
872 return Node.getError();
873
874 // When we have a file provide a heap-allocated wrapper for the memory buffer
875 // to match the ownership semantics for File.
876 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
877 return std::unique_ptr<File>(
878 new detail::InMemoryFileAdaptor(*F, Path.str()));
879
880 // FIXME: errc::not_a_file?
881 return make_error_code(llvm::errc::invalid_argument);
882 }
883
884 namespace {
885
886 /// Adaptor from InMemoryDir::iterator to directory_iterator.
887 class InMemoryDirIterator : public llvm::vfs::detail::DirIterImpl {
888 detail::InMemoryDirectory::const_iterator I;
889 detail::InMemoryDirectory::const_iterator E;
890 std::string RequestedDirName;
891
setCurrentEntry()892 void setCurrentEntry() {
893 if (I != E) {
894 SmallString<256> Path(RequestedDirName);
895 llvm::sys::path::append(Path, I->second->getFileName());
896 sys::fs::file_type Type = sys::fs::file_type::type_unknown;
897 switch (I->second->getKind()) {
898 case detail::IME_File:
899 case detail::IME_HardLink:
900 Type = sys::fs::file_type::regular_file;
901 break;
902 case detail::IME_Directory:
903 Type = sys::fs::file_type::directory_file;
904 break;
905 }
906 CurrentEntry = directory_entry(std::string(Path.str()), Type);
907 } else {
908 // When we're at the end, make CurrentEntry invalid and DirIterImpl will
909 // do the rest.
910 CurrentEntry = directory_entry();
911 }
912 }
913
914 public:
915 InMemoryDirIterator() = default;
916
InMemoryDirIterator(const detail::InMemoryDirectory & Dir,std::string RequestedDirName)917 explicit InMemoryDirIterator(const detail::InMemoryDirectory &Dir,
918 std::string RequestedDirName)
919 : I(Dir.begin()), E(Dir.end()),
920 RequestedDirName(std::move(RequestedDirName)) {
921 setCurrentEntry();
922 }
923
increment()924 std::error_code increment() override {
925 ++I;
926 setCurrentEntry();
927 return {};
928 }
929 };
930
931 } // namespace
932
dir_begin(const Twine & Dir,std::error_code & EC)933 directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
934 std::error_code &EC) {
935 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
936 if (!Node) {
937 EC = Node.getError();
938 return directory_iterator(std::make_shared<InMemoryDirIterator>());
939 }
940
941 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
942 return directory_iterator(
943 std::make_shared<InMemoryDirIterator>(*DirNode, Dir.str()));
944
945 EC = make_error_code(llvm::errc::not_a_directory);
946 return directory_iterator(std::make_shared<InMemoryDirIterator>());
947 }
948
setCurrentWorkingDirectory(const Twine & P)949 std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
950 SmallString<128> Path;
951 P.toVector(Path);
952
953 // Fix up relative paths. This just prepends the current working directory.
954 std::error_code EC = makeAbsolute(Path);
955 assert(!EC);
956 (void)EC;
957
958 if (useNormalizedPaths())
959 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
960
961 if (!Path.empty())
962 WorkingDirectory = std::string(Path.str());
963 return {};
964 }
965
966 std::error_code
getRealPath(const Twine & Path,SmallVectorImpl<char> & Output) const967 InMemoryFileSystem::getRealPath(const Twine &Path,
968 SmallVectorImpl<char> &Output) const {
969 auto CWD = getCurrentWorkingDirectory();
970 if (!CWD || CWD->empty())
971 return errc::operation_not_permitted;
972 Path.toVector(Output);
973 if (auto EC = makeAbsolute(Output))
974 return EC;
975 llvm::sys::path::remove_dots(Output, /*remove_dot_dot=*/true);
976 return {};
977 }
978
isLocal(const Twine & Path,bool & Result)979 std::error_code InMemoryFileSystem::isLocal(const Twine &Path, bool &Result) {
980 Result = false;
981 return {};
982 }
983
984 } // namespace vfs
985 } // namespace llvm
986
987 //===-----------------------------------------------------------------------===/
988 // RedirectingFileSystem implementation
989 //===-----------------------------------------------------------------------===/
990
991 namespace {
992
993 /// Removes leading "./" as well as path components like ".." and ".".
canonicalize(llvm::StringRef Path)994 static llvm::SmallString<256> canonicalize(llvm::StringRef Path) {
995 // First detect the path style in use by checking the first separator.
996 llvm::sys::path::Style style = llvm::sys::path::Style::native;
997 const size_t n = Path.find_first_of("/\\");
998 if (n != static_cast<size_t>(-1))
999 style = (Path[n] == '/') ? llvm::sys::path::Style::posix
1000 : llvm::sys::path::Style::windows;
1001
1002 // Now remove the dots. Explicitly specifying the path style prevents the
1003 // direction of the slashes from changing.
1004 llvm::SmallString<256> result =
1005 llvm::sys::path::remove_leading_dotslash(Path, style);
1006 llvm::sys::path::remove_dots(result, /*remove_dot_dot=*/true, style);
1007 return result;
1008 }
1009
1010 } // anonymous namespace
1011
1012
RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> FS)1013 RedirectingFileSystem::RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> FS)
1014 : ExternalFS(std::move(FS)) {
1015 if (ExternalFS)
1016 if (auto ExternalWorkingDirectory =
1017 ExternalFS->getCurrentWorkingDirectory()) {
1018 WorkingDirectory = *ExternalWorkingDirectory;
1019 ExternalFSValidWD = true;
1020 }
1021 }
1022
1023 // FIXME: reuse implementation common with OverlayFSDirIterImpl as these
1024 // iterators are conceptually similar.
1025 class llvm::vfs::VFSFromYamlDirIterImpl
1026 : public llvm::vfs::detail::DirIterImpl {
1027 std::string Dir;
1028 RedirectingFileSystem::RedirectingDirectoryEntry::iterator Current, End;
1029
1030 // To handle 'fallthrough' mode we need to iterate at first through
1031 // RedirectingDirectoryEntry and then through ExternalFS. These operations are
1032 // done sequentially, we just need to keep a track of what kind of iteration
1033 // we are currently performing.
1034
1035 /// Flag telling if we should iterate through ExternalFS or stop at the last
1036 /// RedirectingDirectoryEntry::iterator.
1037 bool IterateExternalFS;
1038 /// Flag telling if we have switched to iterating through ExternalFS.
1039 bool IsExternalFSCurrent = false;
1040 FileSystem &ExternalFS;
1041 directory_iterator ExternalDirIter;
1042 llvm::StringSet<> SeenNames;
1043
1044 /// To combine multiple iterations, different methods are responsible for
1045 /// different iteration steps.
1046 /// @{
1047
1048 /// Responsible for dispatching between RedirectingDirectoryEntry iteration
1049 /// and ExternalFS iteration.
1050 std::error_code incrementImpl(bool IsFirstTime);
1051 /// Responsible for RedirectingDirectoryEntry iteration.
1052 std::error_code incrementContent(bool IsFirstTime);
1053 /// Responsible for ExternalFS iteration.
1054 std::error_code incrementExternal();
1055 /// @}
1056
1057 public:
1058 VFSFromYamlDirIterImpl(
1059 const Twine &Path,
1060 RedirectingFileSystem::RedirectingDirectoryEntry::iterator Begin,
1061 RedirectingFileSystem::RedirectingDirectoryEntry::iterator End,
1062 bool IterateExternalFS, FileSystem &ExternalFS, std::error_code &EC);
1063
1064 std::error_code increment() override;
1065 };
1066
1067 llvm::ErrorOr<std::string>
getCurrentWorkingDirectory() const1068 RedirectingFileSystem::getCurrentWorkingDirectory() const {
1069 return WorkingDirectory;
1070 }
1071
1072 std::error_code
setCurrentWorkingDirectory(const Twine & Path)1073 RedirectingFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
1074 // Don't change the working directory if the path doesn't exist.
1075 if (!exists(Path))
1076 return errc::no_such_file_or_directory;
1077
1078 // Always change the external FS but ignore its result.
1079 if (ExternalFS) {
1080 auto EC = ExternalFS->setCurrentWorkingDirectory(Path);
1081 ExternalFSValidWD = !static_cast<bool>(EC);
1082 }
1083
1084 SmallString<128> AbsolutePath;
1085 Path.toVector(AbsolutePath);
1086 if (std::error_code EC = makeAbsolute(AbsolutePath))
1087 return EC;
1088 WorkingDirectory = std::string(AbsolutePath.str());
1089 return {};
1090 }
1091
isLocal(const Twine & Path,bool & Result)1092 std::error_code RedirectingFileSystem::isLocal(const Twine &Path,
1093 bool &Result) {
1094 return ExternalFS->isLocal(Path, Result);
1095 }
1096
makeAbsolute(SmallVectorImpl<char> & Path) const1097 std::error_code RedirectingFileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
1098 if (llvm::sys::path::is_absolute(Path, llvm::sys::path::Style::posix) ||
1099 llvm::sys::path::is_absolute(Path, llvm::sys::path::Style::windows))
1100 return {};
1101
1102 auto WorkingDir = getCurrentWorkingDirectory();
1103 if (!WorkingDir)
1104 return WorkingDir.getError();
1105
1106 // We can't use sys::fs::make_absolute because that assumes the path style
1107 // is native and there is no way to override that. Since we know WorkingDir
1108 // is absolute, we can use it to determine which style we actually have and
1109 // append Path ourselves.
1110 sys::path::Style style = sys::path::Style::windows;
1111 if (sys::path::is_absolute(WorkingDir.get(), sys::path::Style::posix)) {
1112 style = sys::path::Style::posix;
1113 }
1114
1115 std::string Result = WorkingDir.get();
1116 StringRef Dir(Result);
1117 if (!Dir.endswith(sys::path::get_separator(style))) {
1118 Result += sys::path::get_separator(style);
1119 }
1120 Result.append(Path.data(), Path.size());
1121 Path.assign(Result.begin(), Result.end());
1122
1123 return {};
1124 }
1125
dir_begin(const Twine & Dir,std::error_code & EC)1126 directory_iterator RedirectingFileSystem::dir_begin(const Twine &Dir,
1127 std::error_code &EC) {
1128 ErrorOr<RedirectingFileSystem::Entry *> E = lookupPath(Dir);
1129 if (!E) {
1130 EC = E.getError();
1131 if (shouldUseExternalFS() && EC == errc::no_such_file_or_directory)
1132 return ExternalFS->dir_begin(Dir, EC);
1133 return {};
1134 }
1135 ErrorOr<Status> S = status(Dir, *E);
1136 if (!S) {
1137 EC = S.getError();
1138 return {};
1139 }
1140 if (!S->isDirectory()) {
1141 EC = std::error_code(static_cast<int>(errc::not_a_directory),
1142 std::system_category());
1143 return {};
1144 }
1145
1146 auto *D = cast<RedirectingFileSystem::RedirectingDirectoryEntry>(*E);
1147 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(
1148 Dir, D->contents_begin(), D->contents_end(),
1149 /*IterateExternalFS=*/shouldUseExternalFS(), *ExternalFS, EC));
1150 }
1151
setExternalContentsPrefixDir(StringRef PrefixDir)1152 void RedirectingFileSystem::setExternalContentsPrefixDir(StringRef PrefixDir) {
1153 ExternalContentsPrefixDir = PrefixDir.str();
1154 }
1155
getExternalContentsPrefixDir() const1156 StringRef RedirectingFileSystem::getExternalContentsPrefixDir() const {
1157 return ExternalContentsPrefixDir;
1158 }
1159
setFallthrough(bool Fallthrough)1160 void RedirectingFileSystem::setFallthrough(bool Fallthrough) {
1161 IsFallthrough = Fallthrough;
1162 }
1163
getRoots() const1164 std::vector<StringRef> RedirectingFileSystem::getRoots() const {
1165 std::vector<StringRef> R;
1166 for (const auto &Root : Roots)
1167 R.push_back(Root->getName());
1168 return R;
1169 }
1170
dump(raw_ostream & OS) const1171 void RedirectingFileSystem::dump(raw_ostream &OS) const {
1172 for (const auto &Root : Roots)
1173 dumpEntry(OS, Root.get());
1174 }
1175
dumpEntry(raw_ostream & OS,RedirectingFileSystem::Entry * E,int NumSpaces) const1176 void RedirectingFileSystem::dumpEntry(raw_ostream &OS,
1177 RedirectingFileSystem::Entry *E,
1178 int NumSpaces) const {
1179 StringRef Name = E->getName();
1180 for (int i = 0, e = NumSpaces; i < e; ++i)
1181 OS << " ";
1182 OS << "'" << Name.str().c_str() << "'"
1183 << "\n";
1184
1185 if (E->getKind() == RedirectingFileSystem::EK_Directory) {
1186 auto *DE = dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(E);
1187 assert(DE && "Should be a directory");
1188
1189 for (std::unique_ptr<Entry> &SubEntry :
1190 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1191 dumpEntry(OS, SubEntry.get(), NumSpaces + 2);
1192 }
1193 }
1194
1195 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const1196 LLVM_DUMP_METHOD void RedirectingFileSystem::dump() const { dump(dbgs()); }
1197 #endif
1198
1199 /// A helper class to hold the common YAML parsing state.
1200 class llvm::vfs::RedirectingFileSystemParser {
1201 yaml::Stream &Stream;
1202
error(yaml::Node * N,const Twine & Msg)1203 void error(yaml::Node *N, const Twine &Msg) { Stream.printError(N, Msg); }
1204
1205 // false on error
parseScalarString(yaml::Node * N,StringRef & Result,SmallVectorImpl<char> & Storage)1206 bool parseScalarString(yaml::Node *N, StringRef &Result,
1207 SmallVectorImpl<char> &Storage) {
1208 const auto *S = dyn_cast<yaml::ScalarNode>(N);
1209
1210 if (!S) {
1211 error(N, "expected string");
1212 return false;
1213 }
1214 Result = S->getValue(Storage);
1215 return true;
1216 }
1217
1218 // false on error
parseScalarBool(yaml::Node * N,bool & Result)1219 bool parseScalarBool(yaml::Node *N, bool &Result) {
1220 SmallString<5> Storage;
1221 StringRef Value;
1222 if (!parseScalarString(N, Value, Storage))
1223 return false;
1224
1225 if (Value.equals_lower("true") || Value.equals_lower("on") ||
1226 Value.equals_lower("yes") || Value == "1") {
1227 Result = true;
1228 return true;
1229 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
1230 Value.equals_lower("no") || Value == "0") {
1231 Result = false;
1232 return true;
1233 }
1234
1235 error(N, "expected boolean value");
1236 return false;
1237 }
1238
1239 struct KeyStatus {
1240 bool Required;
1241 bool Seen = false;
1242
KeyStatusllvm::vfs::RedirectingFileSystemParser::KeyStatus1243 KeyStatus(bool Required = false) : Required(Required) {}
1244 };
1245
1246 using KeyStatusPair = std::pair<StringRef, KeyStatus>;
1247
1248 // false on error
checkDuplicateOrUnknownKey(yaml::Node * KeyNode,StringRef Key,DenseMap<StringRef,KeyStatus> & Keys)1249 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1250 DenseMap<StringRef, KeyStatus> &Keys) {
1251 if (!Keys.count(Key)) {
1252 error(KeyNode, "unknown key");
1253 return false;
1254 }
1255 KeyStatus &S = Keys[Key];
1256 if (S.Seen) {
1257 error(KeyNode, Twine("duplicate key '") + Key + "'");
1258 return false;
1259 }
1260 S.Seen = true;
1261 return true;
1262 }
1263
1264 // false on error
checkMissingKeys(yaml::Node * Obj,DenseMap<StringRef,KeyStatus> & Keys)1265 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
1266 for (const auto &I : Keys) {
1267 if (I.second.Required && !I.second.Seen) {
1268 error(Obj, Twine("missing key '") + I.first + "'");
1269 return false;
1270 }
1271 }
1272 return true;
1273 }
1274
1275 public:
1276 static RedirectingFileSystem::Entry *
lookupOrCreateEntry(RedirectingFileSystem * FS,StringRef Name,RedirectingFileSystem::Entry * ParentEntry=nullptr)1277 lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1278 RedirectingFileSystem::Entry *ParentEntry = nullptr) {
1279 if (!ParentEntry) { // Look for a existent root
1280 for (const auto &Root : FS->Roots) {
1281 if (Name.equals(Root->getName())) {
1282 ParentEntry = Root.get();
1283 return ParentEntry;
1284 }
1285 }
1286 } else { // Advance to the next component
1287 auto *DE = dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(
1288 ParentEntry);
1289 for (std::unique_ptr<RedirectingFileSystem::Entry> &Content :
1290 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1291 auto *DirContent =
1292 dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(
1293 Content.get());
1294 if (DirContent && Name.equals(Content->getName()))
1295 return DirContent;
1296 }
1297 }
1298
1299 // ... or create a new one
1300 std::unique_ptr<RedirectingFileSystem::Entry> E =
1301 std::make_unique<RedirectingFileSystem::RedirectingDirectoryEntry>(
1302 Name, Status("", getNextVirtualUniqueID(),
1303 std::chrono::system_clock::now(), 0, 0, 0,
1304 file_type::directory_file, sys::fs::all_all));
1305
1306 if (!ParentEntry) { // Add a new root to the overlay
1307 FS->Roots.push_back(std::move(E));
1308 ParentEntry = FS->Roots.back().get();
1309 return ParentEntry;
1310 }
1311
1312 auto *DE =
1313 cast<RedirectingFileSystem::RedirectingDirectoryEntry>(ParentEntry);
1314 DE->addContent(std::move(E));
1315 return DE->getLastContent();
1316 }
1317
1318 private:
uniqueOverlayTree(RedirectingFileSystem * FS,RedirectingFileSystem::Entry * SrcE,RedirectingFileSystem::Entry * NewParentE=nullptr)1319 void uniqueOverlayTree(RedirectingFileSystem *FS,
1320 RedirectingFileSystem::Entry *SrcE,
1321 RedirectingFileSystem::Entry *NewParentE = nullptr) {
1322 StringRef Name = SrcE->getName();
1323 switch (SrcE->getKind()) {
1324 case RedirectingFileSystem::EK_Directory: {
1325 auto *DE = cast<RedirectingFileSystem::RedirectingDirectoryEntry>(SrcE);
1326 // Empty directories could be present in the YAML as a way to
1327 // describe a file for a current directory after some of its subdir
1328 // is parsed. This only leads to redundant walks, ignore it.
1329 if (!Name.empty())
1330 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1331 for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
1332 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1333 uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1334 break;
1335 }
1336 case RedirectingFileSystem::EK_File: {
1337 assert(NewParentE && "Parent entry must exist");
1338 auto *FE = cast<RedirectingFileSystem::RedirectingFileEntry>(SrcE);
1339 auto *DE =
1340 cast<RedirectingFileSystem::RedirectingDirectoryEntry>(NewParentE);
1341 DE->addContent(
1342 std::make_unique<RedirectingFileSystem::RedirectingFileEntry>(
1343 Name, FE->getExternalContentsPath(), FE->getUseName()));
1344 break;
1345 }
1346 }
1347 }
1348
1349 std::unique_ptr<RedirectingFileSystem::Entry>
parseEntry(yaml::Node * N,RedirectingFileSystem * FS,bool IsRootEntry)1350 parseEntry(yaml::Node *N, RedirectingFileSystem *FS, bool IsRootEntry) {
1351 auto *M = dyn_cast<yaml::MappingNode>(N);
1352 if (!M) {
1353 error(N, "expected mapping node for file or directory entry");
1354 return nullptr;
1355 }
1356
1357 KeyStatusPair Fields[] = {
1358 KeyStatusPair("name", true),
1359 KeyStatusPair("type", true),
1360 KeyStatusPair("contents", false),
1361 KeyStatusPair("external-contents", false),
1362 KeyStatusPair("use-external-name", false),
1363 };
1364
1365 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
1366
1367 bool HasContents = false; // external or otherwise
1368 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>>
1369 EntryArrayContents;
1370 SmallString<256> ExternalContentsPath;
1371 SmallString<256> Name;
1372 yaml::Node *NameValueNode = nullptr;
1373 auto UseExternalName =
1374 RedirectingFileSystem::RedirectingFileEntry::NK_NotSet;
1375 RedirectingFileSystem::EntryKind Kind;
1376
1377 for (auto &I : *M) {
1378 StringRef Key;
1379 // Reuse the buffer for key and value, since we don't look at key after
1380 // parsing value.
1381 SmallString<256> Buffer;
1382 if (!parseScalarString(I.getKey(), Key, Buffer))
1383 return nullptr;
1384
1385 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
1386 return nullptr;
1387
1388 StringRef Value;
1389 if (Key == "name") {
1390 if (!parseScalarString(I.getValue(), Value, Buffer))
1391 return nullptr;
1392
1393 NameValueNode = I.getValue();
1394 // Guarantee that old YAML files containing paths with ".." and "."
1395 // are properly canonicalized before read into the VFS.
1396 Name = canonicalize(Value).str();
1397 } else if (Key == "type") {
1398 if (!parseScalarString(I.getValue(), Value, Buffer))
1399 return nullptr;
1400 if (Value == "file")
1401 Kind = RedirectingFileSystem::EK_File;
1402 else if (Value == "directory")
1403 Kind = RedirectingFileSystem::EK_Directory;
1404 else {
1405 error(I.getValue(), "unknown value for 'type'");
1406 return nullptr;
1407 }
1408 } else if (Key == "contents") {
1409 if (HasContents) {
1410 error(I.getKey(),
1411 "entry already has 'contents' or 'external-contents'");
1412 return nullptr;
1413 }
1414 HasContents = true;
1415 auto *Contents = dyn_cast<yaml::SequenceNode>(I.getValue());
1416 if (!Contents) {
1417 // FIXME: this is only for directories, what about files?
1418 error(I.getValue(), "expected array");
1419 return nullptr;
1420 }
1421
1422 for (auto &I : *Contents) {
1423 if (std::unique_ptr<RedirectingFileSystem::Entry> E =
1424 parseEntry(&I, FS, /*IsRootEntry*/ false))
1425 EntryArrayContents.push_back(std::move(E));
1426 else
1427 return nullptr;
1428 }
1429 } else if (Key == "external-contents") {
1430 if (HasContents) {
1431 error(I.getKey(),
1432 "entry already has 'contents' or 'external-contents'");
1433 return nullptr;
1434 }
1435 HasContents = true;
1436 if (!parseScalarString(I.getValue(), Value, Buffer))
1437 return nullptr;
1438
1439 SmallString<256> FullPath;
1440 if (FS->IsRelativeOverlay) {
1441 FullPath = FS->getExternalContentsPrefixDir();
1442 assert(!FullPath.empty() &&
1443 "External contents prefix directory must exist");
1444 llvm::sys::path::append(FullPath, Value);
1445 } else {
1446 FullPath = Value;
1447 }
1448
1449 // Guarantee that old YAML files containing paths with ".." and "."
1450 // are properly canonicalized before read into the VFS.
1451 FullPath = canonicalize(FullPath);
1452 ExternalContentsPath = FullPath.str();
1453 } else if (Key == "use-external-name") {
1454 bool Val;
1455 if (!parseScalarBool(I.getValue(), Val))
1456 return nullptr;
1457 UseExternalName =
1458 Val ? RedirectingFileSystem::RedirectingFileEntry::NK_External
1459 : RedirectingFileSystem::RedirectingFileEntry::NK_Virtual;
1460 } else {
1461 llvm_unreachable("key missing from Keys");
1462 }
1463 }
1464
1465 if (Stream.failed())
1466 return nullptr;
1467
1468 // check for missing keys
1469 if (!HasContents) {
1470 error(N, "missing key 'contents' or 'external-contents'");
1471 return nullptr;
1472 }
1473 if (!checkMissingKeys(N, Keys))
1474 return nullptr;
1475
1476 // check invalid configuration
1477 if (Kind == RedirectingFileSystem::EK_Directory &&
1478 UseExternalName !=
1479 RedirectingFileSystem::RedirectingFileEntry::NK_NotSet) {
1480 error(N, "'use-external-name' is not supported for directories");
1481 return nullptr;
1482 }
1483
1484 sys::path::Style path_style = sys::path::Style::native;
1485 if (IsRootEntry) {
1486 // VFS root entries may be in either Posix or Windows style. Figure out
1487 // which style we have, and use it consistently.
1488 if (sys::path::is_absolute(Name, sys::path::Style::posix)) {
1489 path_style = sys::path::Style::posix;
1490 } else if (sys::path::is_absolute(Name, sys::path::Style::windows)) {
1491 path_style = sys::path::Style::windows;
1492 } else {
1493 assert(NameValueNode && "Name presence should be checked earlier");
1494 error(NameValueNode,
1495 "entry with relative path at the root level is not discoverable");
1496 return nullptr;
1497 }
1498 }
1499
1500 // Remove trailing slash(es), being careful not to remove the root path
1501 StringRef Trimmed(Name);
1502 size_t RootPathLen = sys::path::root_path(Trimmed, path_style).size();
1503 while (Trimmed.size() > RootPathLen &&
1504 sys::path::is_separator(Trimmed.back(), path_style))
1505 Trimmed = Trimmed.slice(0, Trimmed.size() - 1);
1506
1507 // Get the last component
1508 StringRef LastComponent = sys::path::filename(Trimmed, path_style);
1509
1510 std::unique_ptr<RedirectingFileSystem::Entry> Result;
1511 switch (Kind) {
1512 case RedirectingFileSystem::EK_File:
1513 Result = std::make_unique<RedirectingFileSystem::RedirectingFileEntry>(
1514 LastComponent, std::move(ExternalContentsPath), UseExternalName);
1515 break;
1516 case RedirectingFileSystem::EK_Directory:
1517 Result =
1518 std::make_unique<RedirectingFileSystem::RedirectingDirectoryEntry>(
1519 LastComponent, std::move(EntryArrayContents),
1520 Status("", getNextVirtualUniqueID(),
1521 std::chrono::system_clock::now(), 0, 0, 0,
1522 file_type::directory_file, sys::fs::all_all));
1523 break;
1524 }
1525
1526 StringRef Parent = sys::path::parent_path(Trimmed, path_style);
1527 if (Parent.empty())
1528 return Result;
1529
1530 // if 'name' contains multiple components, create implicit directory entries
1531 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent, path_style),
1532 E = sys::path::rend(Parent);
1533 I != E; ++I) {
1534 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> Entries;
1535 Entries.push_back(std::move(Result));
1536 Result =
1537 std::make_unique<RedirectingFileSystem::RedirectingDirectoryEntry>(
1538 *I, std::move(Entries),
1539 Status("", getNextVirtualUniqueID(),
1540 std::chrono::system_clock::now(), 0, 0, 0,
1541 file_type::directory_file, sys::fs::all_all));
1542 }
1543 return Result;
1544 }
1545
1546 public:
RedirectingFileSystemParser(yaml::Stream & S)1547 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
1548
1549 // false on error
parse(yaml::Node * Root,RedirectingFileSystem * FS)1550 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
1551 auto *Top = dyn_cast<yaml::MappingNode>(Root);
1552 if (!Top) {
1553 error(Root, "expected mapping node");
1554 return false;
1555 }
1556
1557 KeyStatusPair Fields[] = {
1558 KeyStatusPair("version", true),
1559 KeyStatusPair("case-sensitive", false),
1560 KeyStatusPair("use-external-names", false),
1561 KeyStatusPair("overlay-relative", false),
1562 KeyStatusPair("fallthrough", false),
1563 KeyStatusPair("roots", true),
1564 };
1565
1566 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
1567 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> RootEntries;
1568
1569 // Parse configuration and 'roots'
1570 for (auto &I : *Top) {
1571 SmallString<10> KeyBuffer;
1572 StringRef Key;
1573 if (!parseScalarString(I.getKey(), Key, KeyBuffer))
1574 return false;
1575
1576 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
1577 return false;
1578
1579 if (Key == "roots") {
1580 auto *Roots = dyn_cast<yaml::SequenceNode>(I.getValue());
1581 if (!Roots) {
1582 error(I.getValue(), "expected array");
1583 return false;
1584 }
1585
1586 for (auto &I : *Roots) {
1587 if (std::unique_ptr<RedirectingFileSystem::Entry> E =
1588 parseEntry(&I, FS, /*IsRootEntry*/ true))
1589 RootEntries.push_back(std::move(E));
1590 else
1591 return false;
1592 }
1593 } else if (Key == "version") {
1594 StringRef VersionString;
1595 SmallString<4> Storage;
1596 if (!parseScalarString(I.getValue(), VersionString, Storage))
1597 return false;
1598 int Version;
1599 if (VersionString.getAsInteger<int>(10, Version)) {
1600 error(I.getValue(), "expected integer");
1601 return false;
1602 }
1603 if (Version < 0) {
1604 error(I.getValue(), "invalid version number");
1605 return false;
1606 }
1607 if (Version != 0) {
1608 error(I.getValue(), "version mismatch, expected 0");
1609 return false;
1610 }
1611 } else if (Key == "case-sensitive") {
1612 if (!parseScalarBool(I.getValue(), FS->CaseSensitive))
1613 return false;
1614 } else if (Key == "overlay-relative") {
1615 if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay))
1616 return false;
1617 } else if (Key == "use-external-names") {
1618 if (!parseScalarBool(I.getValue(), FS->UseExternalNames))
1619 return false;
1620 } else if (Key == "fallthrough") {
1621 if (!parseScalarBool(I.getValue(), FS->IsFallthrough))
1622 return false;
1623 } else {
1624 llvm_unreachable("key missing from Keys");
1625 }
1626 }
1627
1628 if (Stream.failed())
1629 return false;
1630
1631 if (!checkMissingKeys(Top, Keys))
1632 return false;
1633
1634 // Now that we sucessefully parsed the YAML file, canonicalize the internal
1635 // representation to a proper directory tree so that we can search faster
1636 // inside the VFS.
1637 for (auto &E : RootEntries)
1638 uniqueOverlayTree(FS, E.get());
1639
1640 return true;
1641 }
1642 };
1643
1644 std::unique_ptr<RedirectingFileSystem>
create(std::unique_ptr<MemoryBuffer> Buffer,SourceMgr::DiagHandlerTy DiagHandler,StringRef YAMLFilePath,void * DiagContext,IntrusiveRefCntPtr<FileSystem> ExternalFS)1645 RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1646 SourceMgr::DiagHandlerTy DiagHandler,
1647 StringRef YAMLFilePath, void *DiagContext,
1648 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1649 SourceMgr SM;
1650 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
1651
1652 SM.setDiagHandler(DiagHandler, DiagContext);
1653 yaml::document_iterator DI = Stream.begin();
1654 yaml::Node *Root = DI->getRoot();
1655 if (DI == Stream.end() || !Root) {
1656 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
1657 return nullptr;
1658 }
1659
1660 RedirectingFileSystemParser P(Stream);
1661
1662 std::unique_ptr<RedirectingFileSystem> FS(
1663 new RedirectingFileSystem(ExternalFS));
1664
1665 if (!YAMLFilePath.empty()) {
1666 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1667 // to each 'external-contents' path.
1668 //
1669 // Example:
1670 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
1671 // yields:
1672 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1673 //
1674 SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1675 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1676 assert(!EC && "Overlay dir final path must be absolute");
1677 (void)EC;
1678 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1679 }
1680
1681 if (!P.parse(Root, FS.get()))
1682 return nullptr;
1683
1684 return FS;
1685 }
1686
create(ArrayRef<std::pair<std::string,std::string>> RemappedFiles,bool UseExternalNames,FileSystem & ExternalFS)1687 std::unique_ptr<RedirectingFileSystem> RedirectingFileSystem::create(
1688 ArrayRef<std::pair<std::string, std::string>> RemappedFiles,
1689 bool UseExternalNames, FileSystem &ExternalFS) {
1690 std::unique_ptr<RedirectingFileSystem> FS(
1691 new RedirectingFileSystem(&ExternalFS));
1692 FS->UseExternalNames = UseExternalNames;
1693
1694 StringMap<RedirectingFileSystem::Entry *> Entries;
1695
1696 for (auto &Mapping : llvm::reverse(RemappedFiles)) {
1697 SmallString<128> From = StringRef(Mapping.first);
1698 SmallString<128> To = StringRef(Mapping.second);
1699 {
1700 auto EC = ExternalFS.makeAbsolute(From);
1701 (void)EC;
1702 assert(!EC && "Could not make absolute path");
1703 }
1704
1705 // Check if we've already mapped this file. The first one we see (in the
1706 // reverse iteration) wins.
1707 RedirectingFileSystem::Entry *&ToEntry = Entries[From];
1708 if (ToEntry)
1709 continue;
1710
1711 // Add parent directories.
1712 RedirectingFileSystem::Entry *Parent = nullptr;
1713 StringRef FromDirectory = llvm::sys::path::parent_path(From);
1714 for (auto I = llvm::sys::path::begin(FromDirectory),
1715 E = llvm::sys::path::end(FromDirectory);
1716 I != E; ++I) {
1717 Parent = RedirectingFileSystemParser::lookupOrCreateEntry(FS.get(), *I,
1718 Parent);
1719 }
1720 assert(Parent && "File without a directory?");
1721 {
1722 auto EC = ExternalFS.makeAbsolute(To);
1723 (void)EC;
1724 assert(!EC && "Could not make absolute path");
1725 }
1726
1727 // Add the file.
1728 auto NewFile =
1729 std::make_unique<RedirectingFileSystem::RedirectingFileEntry>(
1730 llvm::sys::path::filename(From), To,
1731 UseExternalNames
1732 ? RedirectingFileSystem::RedirectingFileEntry::NK_External
1733 : RedirectingFileSystem::RedirectingFileEntry::NK_Virtual);
1734 ToEntry = NewFile.get();
1735 cast<RedirectingFileSystem::RedirectingDirectoryEntry>(Parent)->addContent(
1736 std::move(NewFile));
1737 }
1738
1739 return FS;
1740 }
1741
1742 ErrorOr<RedirectingFileSystem::Entry *>
lookupPath(const Twine & Path_) const1743 RedirectingFileSystem::lookupPath(const Twine &Path_) const {
1744 SmallString<256> Path;
1745 Path_.toVector(Path);
1746
1747 // Handle relative paths
1748 if (std::error_code EC = makeAbsolute(Path))
1749 return EC;
1750
1751 // Canonicalize path by removing ".", "..", "./", components. This is
1752 // a VFS request, do not bother about symlinks in the path components
1753 // but canonicalize in order to perform the correct entry search.
1754 Path = canonicalize(Path);
1755 if (Path.empty())
1756 return make_error_code(llvm::errc::invalid_argument);
1757
1758 sys::path::const_iterator Start = sys::path::begin(Path);
1759 sys::path::const_iterator End = sys::path::end(Path);
1760 for (const auto &Root : Roots) {
1761 ErrorOr<RedirectingFileSystem::Entry *> Result =
1762 lookupPath(Start, End, Root.get());
1763 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
1764 return Result;
1765 }
1766 return make_error_code(llvm::errc::no_such_file_or_directory);
1767 }
1768
1769 ErrorOr<RedirectingFileSystem::Entry *>
lookupPath(sys::path::const_iterator Start,sys::path::const_iterator End,RedirectingFileSystem::Entry * From) const1770 RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1771 sys::path::const_iterator End,
1772 RedirectingFileSystem::Entry *From) const {
1773 assert(!isTraversalComponent(*Start) &&
1774 !isTraversalComponent(From->getName()) &&
1775 "Paths should not contain traversal components");
1776
1777 StringRef FromName = From->getName();
1778
1779 // Forward the search to the next component in case this is an empty one.
1780 if (!FromName.empty()) {
1781 if (!pathComponentMatches(*Start, FromName))
1782 return make_error_code(llvm::errc::no_such_file_or_directory);
1783
1784 ++Start;
1785
1786 if (Start == End) {
1787 // Match!
1788 return From;
1789 }
1790 }
1791
1792 auto *DE = dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(From);
1793 if (!DE)
1794 return make_error_code(llvm::errc::not_a_directory);
1795
1796 for (const std::unique_ptr<RedirectingFileSystem::Entry> &DirEntry :
1797 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1798 ErrorOr<RedirectingFileSystem::Entry *> Result =
1799 lookupPath(Start, End, DirEntry.get());
1800 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
1801 return Result;
1802 }
1803
1804 return make_error_code(llvm::errc::no_such_file_or_directory);
1805 }
1806
getRedirectedFileStatus(const Twine & Path,bool UseExternalNames,Status ExternalStatus)1807 static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1808 Status ExternalStatus) {
1809 Status S = ExternalStatus;
1810 if (!UseExternalNames)
1811 S = Status::copyWithNewName(S, Path);
1812 S.IsVFSMapped = true;
1813 return S;
1814 }
1815
status(const Twine & Path,RedirectingFileSystem::Entry * E)1816 ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path,
1817 RedirectingFileSystem::Entry *E) {
1818 assert(E != nullptr);
1819 if (auto *F = dyn_cast<RedirectingFileSystem::RedirectingFileEntry>(E)) {
1820 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
1821 assert(!S || S->getName() == F->getExternalContentsPath());
1822 if (S)
1823 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1824 *S);
1825 return S;
1826 } else { // directory
1827 auto *DE = cast<RedirectingFileSystem::RedirectingDirectoryEntry>(E);
1828 return Status::copyWithNewName(DE->getStatus(), Path);
1829 }
1830 }
1831
status(const Twine & Path)1832 ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
1833 ErrorOr<RedirectingFileSystem::Entry *> Result = lookupPath(Path);
1834 if (!Result) {
1835 if (shouldUseExternalFS() &&
1836 Result.getError() == llvm::errc::no_such_file_or_directory) {
1837 return ExternalFS->status(Path);
1838 }
1839 return Result.getError();
1840 }
1841 return status(Path, *Result);
1842 }
1843
1844 namespace {
1845
1846 /// Provide a file wrapper with an overriden status.
1847 class FileWithFixedStatus : public File {
1848 std::unique_ptr<File> InnerFile;
1849 Status S;
1850
1851 public:
FileWithFixedStatus(std::unique_ptr<File> InnerFile,Status S)1852 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
1853 : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
1854
status()1855 ErrorOr<Status> status() override { return S; }
1856 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
1857
getBuffer(const Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)1858 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1859 bool IsVolatile) override {
1860 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1861 IsVolatile);
1862 }
1863
close()1864 std::error_code close() override { return InnerFile->close(); }
1865 };
1866
1867 } // namespace
1868
1869 ErrorOr<std::unique_ptr<File>>
openFileForRead(const Twine & Path)1870 RedirectingFileSystem::openFileForRead(const Twine &Path) {
1871 ErrorOr<RedirectingFileSystem::Entry *> E = lookupPath(Path);
1872 if (!E) {
1873 if (shouldUseExternalFS() &&
1874 E.getError() == llvm::errc::no_such_file_or_directory) {
1875 return ExternalFS->openFileForRead(Path);
1876 }
1877 return E.getError();
1878 }
1879
1880 auto *F = dyn_cast<RedirectingFileSystem::RedirectingFileEntry>(*E);
1881 if (!F) // FIXME: errc::not_a_file?
1882 return make_error_code(llvm::errc::invalid_argument);
1883
1884 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1885 if (!Result)
1886 return Result;
1887
1888 auto ExternalStatus = (*Result)->status();
1889 if (!ExternalStatus)
1890 return ExternalStatus.getError();
1891
1892 // FIXME: Update the status with the name and VFSMapped.
1893 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1894 *ExternalStatus);
1895 return std::unique_ptr<File>(
1896 std::make_unique<FileWithFixedStatus>(std::move(*Result), S));
1897 }
1898
1899 std::error_code
getRealPath(const Twine & Path,SmallVectorImpl<char> & Output) const1900 RedirectingFileSystem::getRealPath(const Twine &Path,
1901 SmallVectorImpl<char> &Output) const {
1902 ErrorOr<RedirectingFileSystem::Entry *> Result = lookupPath(Path);
1903 if (!Result) {
1904 if (shouldUseExternalFS() &&
1905 Result.getError() == llvm::errc::no_such_file_or_directory) {
1906 return ExternalFS->getRealPath(Path, Output);
1907 }
1908 return Result.getError();
1909 }
1910
1911 if (auto *F =
1912 dyn_cast<RedirectingFileSystem::RedirectingFileEntry>(*Result)) {
1913 return ExternalFS->getRealPath(F->getExternalContentsPath(), Output);
1914 }
1915 // Even if there is a directory entry, fall back to ExternalFS if allowed,
1916 // because directories don't have a single external contents path.
1917 return shouldUseExternalFS() ? ExternalFS->getRealPath(Path, Output)
1918 : llvm::errc::invalid_argument;
1919 }
1920
1921 std::unique_ptr<FileSystem>
getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,SourceMgr::DiagHandlerTy DiagHandler,StringRef YAMLFilePath,void * DiagContext,IntrusiveRefCntPtr<FileSystem> ExternalFS)1922 vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1923 SourceMgr::DiagHandlerTy DiagHandler,
1924 StringRef YAMLFilePath, void *DiagContext,
1925 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1926 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
1927 YAMLFilePath, DiagContext,
1928 std::move(ExternalFS));
1929 }
1930
getVFSEntries(RedirectingFileSystem::Entry * SrcE,SmallVectorImpl<StringRef> & Path,SmallVectorImpl<YAMLVFSEntry> & Entries)1931 static void getVFSEntries(RedirectingFileSystem::Entry *SrcE,
1932 SmallVectorImpl<StringRef> &Path,
1933 SmallVectorImpl<YAMLVFSEntry> &Entries) {
1934 auto Kind = SrcE->getKind();
1935 if (Kind == RedirectingFileSystem::EK_Directory) {
1936 auto *DE = dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(SrcE);
1937 assert(DE && "Must be a directory");
1938 for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
1939 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1940 Path.push_back(SubEntry->getName());
1941 getVFSEntries(SubEntry.get(), Path, Entries);
1942 Path.pop_back();
1943 }
1944 return;
1945 }
1946
1947 assert(Kind == RedirectingFileSystem::EK_File && "Must be a EK_File");
1948 auto *FE = dyn_cast<RedirectingFileSystem::RedirectingFileEntry>(SrcE);
1949 assert(FE && "Must be a file");
1950 SmallString<128> VPath;
1951 for (auto &Comp : Path)
1952 llvm::sys::path::append(VPath, Comp);
1953 Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
1954 }
1955
collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,SourceMgr::DiagHandlerTy DiagHandler,StringRef YAMLFilePath,SmallVectorImpl<YAMLVFSEntry> & CollectedEntries,void * DiagContext,IntrusiveRefCntPtr<FileSystem> ExternalFS)1956 void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1957 SourceMgr::DiagHandlerTy DiagHandler,
1958 StringRef YAMLFilePath,
1959 SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
1960 void *DiagContext,
1961 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1962 std::unique_ptr<RedirectingFileSystem> VFS = RedirectingFileSystem::create(
1963 std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
1964 std::move(ExternalFS));
1965 ErrorOr<RedirectingFileSystem::Entry *> RootE = VFS->lookupPath("/");
1966 if (!RootE)
1967 return;
1968 SmallVector<StringRef, 8> Components;
1969 Components.push_back("/");
1970 getVFSEntries(*RootE, Components, CollectedEntries);
1971 }
1972
getNextVirtualUniqueID()1973 UniqueID vfs::getNextVirtualUniqueID() {
1974 static std::atomic<unsigned> UID;
1975 unsigned ID = ++UID;
1976 // The following assumes that uint64_t max will never collide with a real
1977 // dev_t value from the OS.
1978 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1979 }
1980
addEntry(StringRef VirtualPath,StringRef RealPath,bool IsDirectory)1981 void YAMLVFSWriter::addEntry(StringRef VirtualPath, StringRef RealPath,
1982 bool IsDirectory) {
1983 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1984 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1985 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1986 Mappings.emplace_back(VirtualPath, RealPath, IsDirectory);
1987 }
1988
addFileMapping(StringRef VirtualPath,StringRef RealPath)1989 void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1990 addEntry(VirtualPath, RealPath, /*IsDirectory=*/false);
1991 }
1992
addDirectoryMapping(StringRef VirtualPath,StringRef RealPath)1993 void YAMLVFSWriter::addDirectoryMapping(StringRef VirtualPath,
1994 StringRef RealPath) {
1995 addEntry(VirtualPath, RealPath, /*IsDirectory=*/true);
1996 }
1997
1998 namespace {
1999
2000 class JSONWriter {
2001 llvm::raw_ostream &OS;
2002 SmallVector<StringRef, 16> DirStack;
2003
getDirIndent()2004 unsigned getDirIndent() { return 4 * DirStack.size(); }
getFileIndent()2005 unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
2006 bool containedIn(StringRef Parent, StringRef Path);
2007 StringRef containedPart(StringRef Parent, StringRef Path);
2008 void startDirectory(StringRef Path);
2009 void endDirectory();
2010 void writeEntry(StringRef VPath, StringRef RPath);
2011
2012 public:
JSONWriter(llvm::raw_ostream & OS)2013 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
2014
2015 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
2016 Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
2017 StringRef OverlayDir);
2018 };
2019
2020 } // namespace
2021
containedIn(StringRef Parent,StringRef Path)2022 bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
2023 using namespace llvm::sys;
2024
2025 // Compare each path component.
2026 auto IParent = path::begin(Parent), EParent = path::end(Parent);
2027 for (auto IChild = path::begin(Path), EChild = path::end(Path);
2028 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
2029 if (*IParent != *IChild)
2030 return false;
2031 }
2032 // Have we exhausted the parent path?
2033 return IParent == EParent;
2034 }
2035
containedPart(StringRef Parent,StringRef Path)2036 StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
2037 assert(!Parent.empty());
2038 assert(containedIn(Parent, Path));
2039 return Path.slice(Parent.size() + 1, StringRef::npos);
2040 }
2041
startDirectory(StringRef Path)2042 void JSONWriter::startDirectory(StringRef Path) {
2043 StringRef Name =
2044 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
2045 DirStack.push_back(Path);
2046 unsigned Indent = getDirIndent();
2047 OS.indent(Indent) << "{\n";
2048 OS.indent(Indent + 2) << "'type': 'directory',\n";
2049 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
2050 OS.indent(Indent + 2) << "'contents': [\n";
2051 }
2052
endDirectory()2053 void JSONWriter::endDirectory() {
2054 unsigned Indent = getDirIndent();
2055 OS.indent(Indent + 2) << "]\n";
2056 OS.indent(Indent) << "}";
2057
2058 DirStack.pop_back();
2059 }
2060
writeEntry(StringRef VPath,StringRef RPath)2061 void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
2062 unsigned Indent = getFileIndent();
2063 OS.indent(Indent) << "{\n";
2064 OS.indent(Indent + 2) << "'type': 'file',\n";
2065 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
2066 OS.indent(Indent + 2) << "'external-contents': \""
2067 << llvm::yaml::escape(RPath) << "\"\n";
2068 OS.indent(Indent) << "}";
2069 }
2070
write(ArrayRef<YAMLVFSEntry> Entries,Optional<bool> UseExternalNames,Optional<bool> IsCaseSensitive,Optional<bool> IsOverlayRelative,StringRef OverlayDir)2071 void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
2072 Optional<bool> UseExternalNames,
2073 Optional<bool> IsCaseSensitive,
2074 Optional<bool> IsOverlayRelative,
2075 StringRef OverlayDir) {
2076 using namespace llvm::sys;
2077
2078 OS << "{\n"
2079 " 'version': 0,\n";
2080 if (IsCaseSensitive.hasValue())
2081 OS << " 'case-sensitive': '"
2082 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
2083 if (UseExternalNames.hasValue())
2084 OS << " 'use-external-names': '"
2085 << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
2086 bool UseOverlayRelative = false;
2087 if (IsOverlayRelative.hasValue()) {
2088 UseOverlayRelative = IsOverlayRelative.getValue();
2089 OS << " 'overlay-relative': '" << (UseOverlayRelative ? "true" : "false")
2090 << "',\n";
2091 }
2092 OS << " 'roots': [\n";
2093
2094 if (!Entries.empty()) {
2095 const YAMLVFSEntry &Entry = Entries.front();
2096
2097 startDirectory(
2098 Entry.IsDirectory ? Entry.VPath : path::parent_path(Entry.VPath)
2099 );
2100
2101 StringRef RPath = Entry.RPath;
2102 if (UseOverlayRelative) {
2103 unsigned OverlayDirLen = OverlayDir.size();
2104 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
2105 "Overlay dir must be contained in RPath");
2106 RPath = RPath.slice(OverlayDirLen, RPath.size());
2107 }
2108
2109 bool IsCurrentDirEmpty = true;
2110 if (!Entry.IsDirectory) {
2111 writeEntry(path::filename(Entry.VPath), RPath);
2112 IsCurrentDirEmpty = false;
2113 }
2114
2115 for (const auto &Entry : Entries.slice(1)) {
2116 StringRef Dir =
2117 Entry.IsDirectory ? Entry.VPath : path::parent_path(Entry.VPath);
2118 if (Dir == DirStack.back()) {
2119 if (!IsCurrentDirEmpty) {
2120 OS << ",\n";
2121 }
2122 } else {
2123 bool IsDirPoppedFromStack = false;
2124 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
2125 OS << "\n";
2126 endDirectory();
2127 IsDirPoppedFromStack = true;
2128 }
2129 if (IsDirPoppedFromStack || !IsCurrentDirEmpty) {
2130 OS << ",\n";
2131 }
2132 startDirectory(Dir);
2133 IsCurrentDirEmpty = true;
2134 }
2135 StringRef RPath = Entry.RPath;
2136 if (UseOverlayRelative) {
2137 unsigned OverlayDirLen = OverlayDir.size();
2138 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
2139 "Overlay dir must be contained in RPath");
2140 RPath = RPath.slice(OverlayDirLen, RPath.size());
2141 }
2142 if (!Entry.IsDirectory) {
2143 writeEntry(path::filename(Entry.VPath), RPath);
2144 IsCurrentDirEmpty = false;
2145 }
2146 }
2147
2148 while (!DirStack.empty()) {
2149 OS << "\n";
2150 endDirectory();
2151 }
2152 OS << "\n";
2153 }
2154
2155 OS << " ]\n"
2156 << "}\n";
2157 }
2158
write(llvm::raw_ostream & OS)2159 void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
2160 llvm::sort(Mappings, [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
2161 return LHS.VPath < RHS.VPath;
2162 });
2163
2164 JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
2165 IsOverlayRelative, OverlayDir);
2166 }
2167
VFSFromYamlDirIterImpl(const Twine & _Path,RedirectingFileSystem::RedirectingDirectoryEntry::iterator Begin,RedirectingFileSystem::RedirectingDirectoryEntry::iterator End,bool IterateExternalFS,FileSystem & ExternalFS,std::error_code & EC)2168 VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
2169 const Twine &_Path,
2170 RedirectingFileSystem::RedirectingDirectoryEntry::iterator Begin,
2171 RedirectingFileSystem::RedirectingDirectoryEntry::iterator End,
2172 bool IterateExternalFS, FileSystem &ExternalFS, std::error_code &EC)
2173 : Dir(_Path.str()), Current(Begin), End(End),
2174 IterateExternalFS(IterateExternalFS), ExternalFS(ExternalFS) {
2175 EC = incrementImpl(/*IsFirstTime=*/true);
2176 }
2177
increment()2178 std::error_code VFSFromYamlDirIterImpl::increment() {
2179 return incrementImpl(/*IsFirstTime=*/false);
2180 }
2181
incrementExternal()2182 std::error_code VFSFromYamlDirIterImpl::incrementExternal() {
2183 assert(!(IsExternalFSCurrent && ExternalDirIter == directory_iterator()) &&
2184 "incrementing past end");
2185 std::error_code EC;
2186 if (IsExternalFSCurrent) {
2187 ExternalDirIter.increment(EC);
2188 } else if (IterateExternalFS) {
2189 ExternalDirIter = ExternalFS.dir_begin(Dir, EC);
2190 IsExternalFSCurrent = true;
2191 if (EC && EC != errc::no_such_file_or_directory)
2192 return EC;
2193 EC = {};
2194 }
2195 if (EC || ExternalDirIter == directory_iterator()) {
2196 CurrentEntry = directory_entry();
2197 } else {
2198 CurrentEntry = *ExternalDirIter;
2199 }
2200 return EC;
2201 }
2202
incrementContent(bool IsFirstTime)2203 std::error_code VFSFromYamlDirIterImpl::incrementContent(bool IsFirstTime) {
2204 assert((IsFirstTime || Current != End) && "cannot iterate past end");
2205 if (!IsFirstTime)
2206 ++Current;
2207 while (Current != End) {
2208 SmallString<128> PathStr(Dir);
2209 llvm::sys::path::append(PathStr, (*Current)->getName());
2210 sys::fs::file_type Type = sys::fs::file_type::type_unknown;
2211 switch ((*Current)->getKind()) {
2212 case RedirectingFileSystem::EK_Directory:
2213 Type = sys::fs::file_type::directory_file;
2214 break;
2215 case RedirectingFileSystem::EK_File:
2216 Type = sys::fs::file_type::regular_file;
2217 break;
2218 }
2219 CurrentEntry = directory_entry(std::string(PathStr.str()), Type);
2220 return {};
2221 }
2222 return incrementExternal();
2223 }
2224
incrementImpl(bool IsFirstTime)2225 std::error_code VFSFromYamlDirIterImpl::incrementImpl(bool IsFirstTime) {
2226 while (true) {
2227 std::error_code EC = IsExternalFSCurrent ? incrementExternal()
2228 : incrementContent(IsFirstTime);
2229 if (EC || CurrentEntry.path().empty())
2230 return EC;
2231 StringRef Name = llvm::sys::path::filename(CurrentEntry.path());
2232 if (SeenNames.insert(Name).second)
2233 return EC; // name not seen before
2234 }
2235 llvm_unreachable("returned above");
2236 }
2237
recursive_directory_iterator(FileSystem & FS_,const Twine & Path,std::error_code & EC)2238 vfs::recursive_directory_iterator::recursive_directory_iterator(
2239 FileSystem &FS_, const Twine &Path, std::error_code &EC)
2240 : FS(&FS_) {
2241 directory_iterator I = FS->dir_begin(Path, EC);
2242 if (I != directory_iterator()) {
2243 State = std::make_shared<detail::RecDirIterState>();
2244 State->Stack.push(I);
2245 }
2246 }
2247
2248 vfs::recursive_directory_iterator &
increment(std::error_code & EC)2249 recursive_directory_iterator::increment(std::error_code &EC) {
2250 assert(FS && State && !State->Stack.empty() && "incrementing past end");
2251 assert(!State->Stack.top()->path().empty() && "non-canonical end iterator");
2252 vfs::directory_iterator End;
2253
2254 if (State->HasNoPushRequest)
2255 State->HasNoPushRequest = false;
2256 else {
2257 if (State->Stack.top()->type() == sys::fs::file_type::directory_file) {
2258 vfs::directory_iterator I = FS->dir_begin(State->Stack.top()->path(), EC);
2259 if (I != End) {
2260 State->Stack.push(I);
2261 return *this;
2262 }
2263 }
2264 }
2265
2266 while (!State->Stack.empty() && State->Stack.top().increment(EC) == End)
2267 State->Stack.pop();
2268
2269 if (State->Stack.empty())
2270 State.reset(); // end iterator
2271
2272 return *this;
2273 }
2274