1 //===- VirtualFileSystem.cpp - Virtual File System Layer ------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the VirtualFileSystem interface.
11 //===----------------------------------------------------------------------===//
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"
52 #include <system_error>
57 using namespace llvm::vfs
;
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
;
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()) {}
71 Status::Status(const Twine
&Name
, UniqueID UID
, sys::TimePoint
<> MTime
,
72 uint32_t User
, uint32_t Group
, uint64_t Size
, file_type Type
,
74 : Name(Name
.str()), UID(UID
), MTime(MTime
), User(User
), Group(Group
),
75 Size(Size
), Type(Type
), Perms(Perms
) {}
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(),
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(),
89 bool Status::equivalent(const Status
&Other
) const {
90 assert(isStatusKnown() && Other
.isStatusKnown());
91 return getUniqueID() == Other
.getUniqueID();
94 bool Status::isDirectory() const { return Type
== file_type::directory_file
; }
96 bool Status::isRegularFile() const { return Type
== file_type::regular_file
; }
98 bool Status::isOther() const {
99 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
102 bool Status::isSymlink() const { return Type
== file_type::symlink_file
; }
104 bool Status::isStatusKnown() const { return Type
!= file_type::status_error
; }
106 bool Status::exists() const {
107 return isStatusKnown() && Type
!= file_type::file_not_found
;
110 File::~File() = default;
112 FileSystem::~FileSystem() = default;
114 ErrorOr
<std::unique_ptr
<MemoryBuffer
>>
115 FileSystem::getBufferForFile(const llvm::Twine
&Name
, int64_t FileSize
,
116 bool RequiresNullTerminator
, bool IsVolatile
) {
117 auto F
= openFileForRead(Name
);
121 return (*F
)->getBuffer(Name
, FileSize
, RequiresNullTerminator
, IsVolatile
);
124 std::error_code
FileSystem::makeAbsolute(SmallVectorImpl
<char> &Path
) const {
125 if (llvm::sys::path::is_absolute(Path
))
128 auto WorkingDir
= getCurrentWorkingDirectory();
130 return WorkingDir
.getError();
132 llvm::sys::fs::make_absolute(WorkingDir
.get(), Path
);
136 std::error_code
FileSystem::getRealPath(const Twine
&Path
,
137 SmallVectorImpl
<char> &Output
) const {
138 return errc::operation_not_permitted
;
141 std::error_code
FileSystem::isLocal(const Twine
&Path
, bool &Result
) {
142 return errc::operation_not_permitted
;
145 bool FileSystem::exists(const Twine
&Path
) {
146 auto Status
= status(Path
);
147 return Status
&& Status
->exists();
151 static bool isTraversalComponent(StringRef Component
) {
152 return Component
.equals("..") || Component
.equals(".");
155 static bool pathHasTraversal(StringRef Path
) {
156 using namespace llvm::sys
;
158 for (StringRef Comp
: llvm::make_range(path::begin(Path
), path::end(Path
)))
159 if (isTraversalComponent(Comp
))
165 //===-----------------------------------------------------------------------===/
166 // RealFileSystem implementation
167 //===-----------------------------------------------------------------------===/
171 /// Wrapper around a raw file descriptor.
172 class RealFile
: public File
{
173 friend class RealFileSystem
;
177 std::string RealName
;
179 RealFile(file_t FD
, StringRef NewName
, StringRef NewRealPathName
)
180 : FD(FD
), S(NewName
, {}, {}, {}, {}, {},
181 llvm::sys::fs::file_type::status_error
, {}),
182 RealName(NewRealPathName
.str()) {
183 assert(FD
!= kInvalidFile
&& "Invalid or inactive file descriptor");
187 ~RealFile() override
;
189 ErrorOr
<Status
> status() override
;
190 ErrorOr
<std::string
> getName() override
;
191 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> getBuffer(const Twine
&Name
,
193 bool RequiresNullTerminator
,
194 bool IsVolatile
) override
;
195 std::error_code
close() override
;
200 RealFile::~RealFile() { close(); }
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
))
208 S
= Status::copyWithNewName(RealStatus
, S
.getName());
213 ErrorOr
<std::string
> RealFile::getName() {
214 return RealName
.empty() ? S
.getName().str() : RealName
;
217 ErrorOr
<std::unique_ptr
<MemoryBuffer
>>
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
,
225 std::error_code
RealFile::close() {
226 std::error_code EC
= sys::fs::closeFile(FD
);
233 /// A file system according to your operating system.
234 /// This may be linked to the process's working directory, or maintain its own.
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
{
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
))
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
;
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
;
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.
268 Twine
adjustPath(const Twine
&Path
, SmallVectorImpl
<char> &Storage
) const {
271 Path
.toVector(Storage
);
272 sys::fs::make_absolute(WD
->Resolved
, Storage
);
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
;
282 Optional
<WorkingDirectory
> WD
;
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
))
293 return Status::copyWithNewName(RealStatus
, Path
);
296 ErrorOr
<std::unique_ptr
<File
>>
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
);
302 return errorToErrorCode(FDOrErr
.takeError());
303 return std::unique_ptr
<File
>(
304 new RealFile(*FDOrErr
, Name
.str(), RealName
.str()));
307 llvm::ErrorOr
<std::string
> RealFileSystem::getCurrentWorkingDirectory() const {
309 return WD
->Specified
.str();
311 SmallString
<128> Dir
;
312 if (std::error_code EC
= llvm::sys::fs::current_path(Dir
))
317 std::error_code
RealFileSystem::setCurrentWorkingDirectory(const Twine
&Path
) {
319 return llvm::sys::fs::set_current_path(Path
);
321 SmallString
<128> Absolute
, Resolved
, Storage
;
322 adjustPath(Path
, Storage
).toVector(Absolute
);
324 if (auto Err
= llvm::sys::fs::is_directory(Absolute
, IsDir
))
327 return std::make_error_code(std::errc::not_a_directory
);
328 if (auto Err
= llvm::sys::fs::real_path(Absolute
, Resolved
))
330 WD
= {Absolute
, Resolved
};
331 return std::error_code();
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
);
340 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
);
346 IntrusiveRefCntPtr
<FileSystem
> vfs::getRealFileSystem() {
347 static IntrusiveRefCntPtr
<FileSystem
> FS(new RealFileSystem(true));
351 std::unique_ptr
<FileSystem
> vfs::createPhysicalFileSystem() {
352 return std::make_unique
<RealFileSystem
>(false);
357 class RealFSDirIter
: public llvm::vfs::detail::DirIterImpl
{
358 llvm::sys::fs::directory_iterator Iter
;
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());
366 std::error_code
increment() override
{
369 CurrentEntry
= (Iter
== llvm::sys::fs::directory_iterator())
371 : directory_entry(Iter
->path(), Iter
->type());
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
));
385 //===-----------------------------------------------------------------------===/
386 // OverlayFileSystem implementation
387 //===-----------------------------------------------------------------------===/
389 OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr
<FileSystem
> BaseFS
) {
390 FSList
.push_back(std::move(BaseFS
));
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());
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
)
407 return make_error_code(llvm::errc::no_such_file_or_directory
);
410 ErrorOr
<std::unique_ptr
<File
>>
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
)
418 return make_error_code(llvm::errc::no_such_file_or_directory
);
421 llvm::ErrorOr
<std::string
>
422 OverlayFileSystem::getCurrentWorkingDirectory() const {
423 // All file systems are synchronized, just take the first working directory.
424 return FSList
.front()->getCurrentWorkingDirectory();
428 OverlayFileSystem::setCurrentWorkingDirectory(const Twine
&Path
) {
429 for (auto &FS
: FSList
)
430 if (std::error_code EC
= FS
->setCurrentWorkingDirectory(Path
))
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
;
443 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
;
451 llvm::vfs::detail::DirIterImpl::~DirIterImpl() = default;
455 class OverlayFSDirIterImpl
: public llvm::vfs::detail::DirIterImpl
{
456 OverlayFileSystem
&Overlays
;
458 OverlayFileSystem::iterator CurrentFS
;
459 directory_iterator CurrentDirIter
;
460 llvm::StringSet
<> SeenNames
;
462 std::error_code
incrementFS() {
463 assert(CurrentFS
!= Overlays
.overlays_end() && "incrementing past end");
465 for (auto E
= Overlays
.overlays_end(); CurrentFS
!= E
; ++CurrentFS
) {
467 CurrentDirIter
= (*CurrentFS
)->dir_begin(Path
, EC
);
468 if (EC
&& EC
!= errc::no_such_file_or_directory
)
470 if (CurrentDirIter
!= directory_iterator())
476 std::error_code
incrementDirIter(bool IsFirstTime
) {
477 assert((IsFirstTime
|| CurrentDirIter
!= directory_iterator()) &&
478 "incrementing past end");
481 CurrentDirIter
.increment(EC
);
482 if (!EC
&& CurrentDirIter
== directory_iterator())
487 std::error_code
incrementImpl(bool IsFirstTime
) {
489 std::error_code EC
= incrementDirIter(IsFirstTime
);
490 if (EC
|| CurrentDirIter
== directory_iterator()) {
491 CurrentEntry
= directory_entry();
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
499 llvm_unreachable("returned above");
503 OverlayFSDirIterImpl(const Twine
&Path
, OverlayFileSystem
&FS
,
505 : Overlays(FS
), Path(Path
.str()), CurrentFS(Overlays
.overlays_begin()) {
506 CurrentDirIter
= (*CurrentFS
)->dir_begin(Path
, EC
);
507 EC
= incrementImpl(true);
510 std::error_code
increment() override
{ return incrementImpl(false); }
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
));
521 void ProxyFileSystem::anchor() {}
528 enum InMemoryNodeKind
{ IME_File
, IME_Directory
, IME_HardLink
};
530 /// The in memory file system is a tree of Nodes. Every node can either be a
531 /// file , hardlink or a directory.
533 InMemoryNodeKind Kind
;
534 std::string FileName
;
537 InMemoryNode(llvm::StringRef FileName
, InMemoryNodeKind Kind
)
538 : Kind(Kind
), FileName(llvm::sys::path::filename(FileName
)) {}
539 virtual ~InMemoryNode() = default;
541 /// Get the filename of this node (the name without the directory part).
542 StringRef
getFileName() const { return FileName
; }
543 InMemoryNodeKind
getKind() const { return Kind
; }
544 virtual std::string
toString(unsigned Indent
) const = 0;
547 class InMemoryFile
: public InMemoryNode
{
549 std::unique_ptr
<llvm::MemoryBuffer
> Buffer
;
552 InMemoryFile(Status Stat
, std::unique_ptr
<llvm::MemoryBuffer
> Buffer
)
553 : InMemoryNode(Stat
.getName(), IME_File
), Stat(std::move(Stat
)),
554 Buffer(std::move(Buffer
)) {}
556 /// Return the \p Status for this node. \p RequestedName should be the name
557 /// through which the caller referred to this node. It will override
558 /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
559 Status
getStatus(const Twine
&RequestedName
) const {
560 return Status::copyWithNewName(Stat
, RequestedName
);
562 llvm::MemoryBuffer
*getBuffer() const { return Buffer
.get(); }
564 std::string
toString(unsigned Indent
) const override
{
565 return (std::string(Indent
, ' ') + Stat
.getName() + "\n").str();
568 static bool classof(const InMemoryNode
*N
) {
569 return N
->getKind() == IME_File
;
575 class InMemoryHardLink
: public InMemoryNode
{
576 const InMemoryFile
&ResolvedFile
;
579 InMemoryHardLink(StringRef Path
, const InMemoryFile
&ResolvedFile
)
580 : InMemoryNode(Path
, IME_HardLink
), ResolvedFile(ResolvedFile
) {}
581 const InMemoryFile
&getResolvedFile() const { return ResolvedFile
; }
583 std::string
toString(unsigned Indent
) const override
{
584 return std::string(Indent
, ' ') + "HardLink to -> " +
585 ResolvedFile
.toString(0);
588 static bool classof(const InMemoryNode
*N
) {
589 return N
->getKind() == IME_HardLink
;
593 /// Adapt a InMemoryFile for VFS' File interface. The goal is to make
594 /// \p InMemoryFileAdaptor mimic as much as possible the behavior of
596 class InMemoryFileAdaptor
: public File
{
597 const InMemoryFile
&Node
;
598 /// The name to use when returning a Status for this file.
599 std::string RequestedName
;
602 explicit InMemoryFileAdaptor(const InMemoryFile
&Node
,
603 std::string RequestedName
)
604 : Node(Node
), RequestedName(std::move(RequestedName
)) {}
606 llvm::ErrorOr
<Status
> status() override
{
607 return Node
.getStatus(RequestedName
);
610 llvm::ErrorOr
<std::unique_ptr
<llvm::MemoryBuffer
>>
611 getBuffer(const Twine
&Name
, int64_t FileSize
, bool RequiresNullTerminator
,
612 bool IsVolatile
) override
{
613 llvm::MemoryBuffer
*Buf
= Node
.getBuffer();
614 return llvm::MemoryBuffer::getMemBuffer(
615 Buf
->getBuffer(), Buf
->getBufferIdentifier(), RequiresNullTerminator
);
618 std::error_code
close() override
{ return {}; }
622 class InMemoryDirectory
: public InMemoryNode
{
624 llvm::StringMap
<std::unique_ptr
<InMemoryNode
>> Entries
;
627 InMemoryDirectory(Status Stat
)
628 : InMemoryNode(Stat
.getName(), IME_Directory
), Stat(std::move(Stat
)) {}
630 /// Return the \p Status for this node. \p RequestedName should be the name
631 /// through which the caller referred to this node. It will override
632 /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
633 Status
getStatus(const Twine
&RequestedName
) const {
634 return Status::copyWithNewName(Stat
, RequestedName
);
636 InMemoryNode
*getChild(StringRef Name
) {
637 auto I
= Entries
.find(Name
);
638 if (I
!= Entries
.end())
639 return I
->second
.get();
643 InMemoryNode
*addChild(StringRef Name
, std::unique_ptr
<InMemoryNode
> Child
) {
644 return Entries
.insert(make_pair(Name
, std::move(Child
)))
645 .first
->second
.get();
648 using const_iterator
= decltype(Entries
)::const_iterator
;
650 const_iterator
begin() const { return Entries
.begin(); }
651 const_iterator
end() const { return Entries
.end(); }
653 std::string
toString(unsigned Indent
) const override
{
655 (std::string(Indent
, ' ') + Stat
.getName() + "\n").str();
656 for (const auto &Entry
: Entries
)
657 Result
+= Entry
.second
->toString(Indent
+ 2);
661 static bool classof(const InMemoryNode
*N
) {
662 return N
->getKind() == IME_Directory
;
667 Status
getNodeStatus(const InMemoryNode
*Node
, const Twine
&RequestedName
) {
668 if (auto Dir
= dyn_cast
<detail::InMemoryDirectory
>(Node
))
669 return Dir
->getStatus(RequestedName
);
670 if (auto File
= dyn_cast
<detail::InMemoryFile
>(Node
))
671 return File
->getStatus(RequestedName
);
672 if (auto Link
= dyn_cast
<detail::InMemoryHardLink
>(Node
))
673 return Link
->getResolvedFile().getStatus(RequestedName
);
674 llvm_unreachable("Unknown node type");
677 } // namespace detail
679 InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths
)
680 : Root(new detail::InMemoryDirectory(
681 Status("", getNextVirtualUniqueID(), llvm::sys::TimePoint
<>(), 0, 0,
682 0, llvm::sys::fs::file_type::directory_file
,
683 llvm::sys::fs::perms::all_all
))),
684 UseNormalizedPaths(UseNormalizedPaths
) {}
686 InMemoryFileSystem::~InMemoryFileSystem() = default;
688 std::string
InMemoryFileSystem::toString() const {
689 return Root
->toString(/*Indent=*/0);
692 bool InMemoryFileSystem::addFile(const Twine
&P
, time_t ModificationTime
,
693 std::unique_ptr
<llvm::MemoryBuffer
> Buffer
,
694 Optional
<uint32_t> User
,
695 Optional
<uint32_t> Group
,
696 Optional
<llvm::sys::fs::file_type
> Type
,
697 Optional
<llvm::sys::fs::perms
> Perms
,
698 const detail::InMemoryFile
*HardLinkTarget
) {
699 SmallString
<128> Path
;
702 // Fix up relative paths. This just prepends the current working directory.
703 std::error_code EC
= makeAbsolute(Path
);
707 if (useNormalizedPaths())
708 llvm::sys::path::remove_dots(Path
, /*remove_dot_dot=*/true);
713 detail::InMemoryDirectory
*Dir
= Root
.get();
714 auto I
= llvm::sys::path::begin(Path
), E
= sys::path::end(Path
);
715 const auto ResolvedUser
= User
.getValueOr(0);
716 const auto ResolvedGroup
= Group
.getValueOr(0);
717 const auto ResolvedType
= Type
.getValueOr(sys::fs::file_type::regular_file
);
718 const auto ResolvedPerms
= Perms
.getValueOr(sys::fs::all_all
);
719 assert(!(HardLinkTarget
&& Buffer
) && "HardLink cannot have a buffer");
720 // Any intermediate directories we create should be accessible by
721 // the owner, even if Perms says otherwise for the final path.
722 const auto NewDirectoryPerms
= ResolvedPerms
| sys::fs::owner_all
;
725 detail::InMemoryNode
*Node
= Dir
->getChild(Name
);
730 std::unique_ptr
<detail::InMemoryNode
> Child
;
732 Child
.reset(new detail::InMemoryHardLink(P
.str(), *HardLinkTarget
));
734 // Create a new file or directory.
735 Status
Stat(P
.str(), getNextVirtualUniqueID(),
736 llvm::sys::toTimePoint(ModificationTime
), ResolvedUser
,
737 ResolvedGroup
, Buffer
->getBufferSize(), ResolvedType
,
739 if (ResolvedType
== sys::fs::file_type::directory_file
) {
740 Child
.reset(new detail::InMemoryDirectory(std::move(Stat
)));
743 new detail::InMemoryFile(std::move(Stat
), std::move(Buffer
)));
746 Dir
->addChild(Name
, std::move(Child
));
750 // Create a new directory. Use the path up to here.
752 StringRef(Path
.str().begin(), Name
.end() - Path
.str().begin()),
753 getNextVirtualUniqueID(), llvm::sys::toTimePoint(ModificationTime
),
754 ResolvedUser
, ResolvedGroup
, 0, sys::fs::file_type::directory_file
,
756 Dir
= cast
<detail::InMemoryDirectory
>(Dir
->addChild(
757 Name
, std::make_unique
<detail::InMemoryDirectory
>(std::move(Stat
))));
761 if (auto *NewDir
= dyn_cast
<detail::InMemoryDirectory
>(Node
)) {
764 assert((isa
<detail::InMemoryFile
>(Node
) ||
765 isa
<detail::InMemoryHardLink
>(Node
)) &&
766 "Must be either file, hardlink or directory!");
768 // Trying to insert a directory in place of a file.
772 // Return false only if the new file is different from the existing one.
773 if (auto Link
= dyn_cast
<detail::InMemoryHardLink
>(Node
)) {
774 return Link
->getResolvedFile().getBuffer()->getBuffer() ==
777 return cast
<detail::InMemoryFile
>(Node
)->getBuffer()->getBuffer() ==
783 bool InMemoryFileSystem::addFile(const Twine
&P
, time_t ModificationTime
,
784 std::unique_ptr
<llvm::MemoryBuffer
> Buffer
,
785 Optional
<uint32_t> User
,
786 Optional
<uint32_t> Group
,
787 Optional
<llvm::sys::fs::file_type
> Type
,
788 Optional
<llvm::sys::fs::perms
> Perms
) {
789 return addFile(P
, ModificationTime
, std::move(Buffer
), User
, Group
, Type
,
790 Perms
, /*HardLinkTarget=*/nullptr);
793 bool InMemoryFileSystem::addFileNoOwn(const Twine
&P
, time_t ModificationTime
,
794 llvm::MemoryBuffer
*Buffer
,
795 Optional
<uint32_t> User
,
796 Optional
<uint32_t> Group
,
797 Optional
<llvm::sys::fs::file_type
> Type
,
798 Optional
<llvm::sys::fs::perms
> Perms
) {
799 return addFile(P
, ModificationTime
,
800 llvm::MemoryBuffer::getMemBuffer(
801 Buffer
->getBuffer(), Buffer
->getBufferIdentifier()),
802 std::move(User
), std::move(Group
), std::move(Type
),
806 static ErrorOr
<const detail::InMemoryNode
*>
807 lookupInMemoryNode(const InMemoryFileSystem
&FS
, detail::InMemoryDirectory
*Dir
,
809 SmallString
<128> Path
;
812 // Fix up relative paths. This just prepends the current working directory.
813 std::error_code EC
= FS
.makeAbsolute(Path
);
817 if (FS
.useNormalizedPaths())
818 llvm::sys::path::remove_dots(Path
, /*remove_dot_dot=*/true);
823 auto I
= llvm::sys::path::begin(Path
), E
= llvm::sys::path::end(Path
);
825 detail::InMemoryNode
*Node
= Dir
->getChild(*I
);
828 return errc::no_such_file_or_directory
;
830 // Return the file if it's at the end of the path.
831 if (auto File
= dyn_cast
<detail::InMemoryFile
>(Node
)) {
834 return errc::no_such_file_or_directory
;
837 // If Node is HardLink then return the resolved file.
838 if (auto File
= dyn_cast
<detail::InMemoryHardLink
>(Node
)) {
840 return &File
->getResolvedFile();
841 return errc::no_such_file_or_directory
;
843 // Traverse directories.
844 Dir
= cast
<detail::InMemoryDirectory
>(Node
);
850 bool InMemoryFileSystem::addHardLink(const Twine
&FromPath
,
851 const Twine
&ToPath
) {
852 auto FromNode
= lookupInMemoryNode(*this, Root
.get(), FromPath
);
853 auto ToNode
= lookupInMemoryNode(*this, Root
.get(), ToPath
);
854 // FromPath must not have been added before. ToPath must have been added
855 // before. Resolved ToPath must be a File.
856 if (!ToNode
|| FromNode
|| !isa
<detail::InMemoryFile
>(*ToNode
))
858 return this->addFile(FromPath
, 0, nullptr, None
, None
, None
, None
,
859 cast
<detail::InMemoryFile
>(*ToNode
));
862 llvm::ErrorOr
<Status
> InMemoryFileSystem::status(const Twine
&Path
) {
863 auto Node
= lookupInMemoryNode(*this, Root
.get(), Path
);
865 return detail::getNodeStatus(*Node
, Path
);
866 return Node
.getError();
869 llvm::ErrorOr
<std::unique_ptr
<File
>>
870 InMemoryFileSystem::openFileForRead(const Twine
&Path
) {
871 auto Node
= lookupInMemoryNode(*this, Root
.get(), Path
);
873 return Node
.getError();
875 // When we have a file provide a heap-allocated wrapper for the memory buffer
876 // to match the ownership semantics for File.
877 if (auto *F
= dyn_cast
<detail::InMemoryFile
>(*Node
))
878 return std::unique_ptr
<File
>(
879 new detail::InMemoryFileAdaptor(*F
, Path
.str()));
881 // FIXME: errc::not_a_file?
882 return make_error_code(llvm::errc::invalid_argument
);
887 /// Adaptor from InMemoryDir::iterator to directory_iterator.
888 class InMemoryDirIterator
: public llvm::vfs::detail::DirIterImpl
{
889 detail::InMemoryDirectory::const_iterator I
;
890 detail::InMemoryDirectory::const_iterator E
;
891 std::string RequestedDirName
;
893 void setCurrentEntry() {
895 SmallString
<256> Path(RequestedDirName
);
896 llvm::sys::path::append(Path
, I
->second
->getFileName());
897 sys::fs::file_type Type
;
898 switch (I
->second
->getKind()) {
899 case detail::IME_File
:
900 case detail::IME_HardLink
:
901 Type
= sys::fs::file_type::regular_file
;
903 case detail::IME_Directory
:
904 Type
= sys::fs::file_type::directory_file
;
907 CurrentEntry
= directory_entry(Path
.str(), Type
);
909 // When we're at the end, make CurrentEntry invalid and DirIterImpl will
911 CurrentEntry
= directory_entry();
916 InMemoryDirIterator() = default;
918 explicit InMemoryDirIterator(const detail::InMemoryDirectory
&Dir
,
919 std::string RequestedDirName
)
920 : I(Dir
.begin()), E(Dir
.end()),
921 RequestedDirName(std::move(RequestedDirName
)) {
925 std::error_code
increment() override
{
934 directory_iterator
InMemoryFileSystem::dir_begin(const Twine
&Dir
,
935 std::error_code
&EC
) {
936 auto Node
= lookupInMemoryNode(*this, Root
.get(), Dir
);
938 EC
= Node
.getError();
939 return directory_iterator(std::make_shared
<InMemoryDirIterator
>());
942 if (auto *DirNode
= dyn_cast
<detail::InMemoryDirectory
>(*Node
))
943 return directory_iterator(
944 std::make_shared
<InMemoryDirIterator
>(*DirNode
, Dir
.str()));
946 EC
= make_error_code(llvm::errc::not_a_directory
);
947 return directory_iterator(std::make_shared
<InMemoryDirIterator
>());
950 std::error_code
InMemoryFileSystem::setCurrentWorkingDirectory(const Twine
&P
) {
951 SmallString
<128> Path
;
954 // Fix up relative paths. This just prepends the current working directory.
955 std::error_code EC
= makeAbsolute(Path
);
959 if (useNormalizedPaths())
960 llvm::sys::path::remove_dots(Path
, /*remove_dot_dot=*/true);
963 WorkingDirectory
= Path
.str();
968 InMemoryFileSystem::getRealPath(const Twine
&Path
,
969 SmallVectorImpl
<char> &Output
) const {
970 auto CWD
= getCurrentWorkingDirectory();
971 if (!CWD
|| CWD
->empty())
972 return errc::operation_not_permitted
;
973 Path
.toVector(Output
);
974 if (auto EC
= makeAbsolute(Output
))
976 llvm::sys::path::remove_dots(Output
, /*remove_dot_dot=*/true);
980 std::error_code
InMemoryFileSystem::isLocal(const Twine
&Path
, bool &Result
) {
988 //===-----------------------------------------------------------------------===/
989 // RedirectingFileSystem implementation
990 //===-----------------------------------------------------------------------===/
992 // FIXME: reuse implementation common with OverlayFSDirIterImpl as these
993 // iterators are conceptually similar.
994 class llvm::vfs::VFSFromYamlDirIterImpl
995 : public llvm::vfs::detail::DirIterImpl
{
997 RedirectingFileSystem::RedirectingDirectoryEntry::iterator Current
, End
;
999 // To handle 'fallthrough' mode we need to iterate at first through
1000 // RedirectingDirectoryEntry and then through ExternalFS. These operations are
1001 // done sequentially, we just need to keep a track of what kind of iteration
1002 // we are currently performing.
1004 /// Flag telling if we should iterate through ExternalFS or stop at the last
1005 /// RedirectingDirectoryEntry::iterator.
1006 bool IterateExternalFS
;
1007 /// Flag telling if we have switched to iterating through ExternalFS.
1008 bool IsExternalFSCurrent
= false;
1009 FileSystem
&ExternalFS
;
1010 directory_iterator ExternalDirIter
;
1011 llvm::StringSet
<> SeenNames
;
1013 /// To combine multiple iterations, different methods are responsible for
1014 /// different iteration steps.
1017 /// Responsible for dispatching between RedirectingDirectoryEntry iteration
1018 /// and ExternalFS iteration.
1019 std::error_code
incrementImpl(bool IsFirstTime
);
1020 /// Responsible for RedirectingDirectoryEntry iteration.
1021 std::error_code
incrementContent(bool IsFirstTime
);
1022 /// Responsible for ExternalFS iteration.
1023 std::error_code
incrementExternal();
1027 VFSFromYamlDirIterImpl(
1029 RedirectingFileSystem::RedirectingDirectoryEntry::iterator Begin
,
1030 RedirectingFileSystem::RedirectingDirectoryEntry::iterator End
,
1031 bool IterateExternalFS
, FileSystem
&ExternalFS
, std::error_code
&EC
);
1033 std::error_code
increment() override
;
1036 llvm::ErrorOr
<std::string
>
1037 RedirectingFileSystem::getCurrentWorkingDirectory() const {
1038 return ExternalFS
->getCurrentWorkingDirectory();
1042 RedirectingFileSystem::setCurrentWorkingDirectory(const Twine
&Path
) {
1043 return ExternalFS
->setCurrentWorkingDirectory(Path
);
1046 std::error_code
RedirectingFileSystem::isLocal(const Twine
&Path
,
1048 return ExternalFS
->isLocal(Path
, Result
);
1051 directory_iterator
RedirectingFileSystem::dir_begin(const Twine
&Dir
,
1052 std::error_code
&EC
) {
1053 ErrorOr
<RedirectingFileSystem::Entry
*> E
= lookupPath(Dir
);
1056 if (IsFallthrough
&& EC
== errc::no_such_file_or_directory
)
1057 return ExternalFS
->dir_begin(Dir
, EC
);
1060 ErrorOr
<Status
> S
= status(Dir
, *E
);
1065 if (!S
->isDirectory()) {
1066 EC
= std::error_code(static_cast<int>(errc::not_a_directory
),
1067 std::system_category());
1071 auto *D
= cast
<RedirectingFileSystem::RedirectingDirectoryEntry
>(*E
);
1072 return directory_iterator(std::make_shared
<VFSFromYamlDirIterImpl
>(
1073 Dir
, D
->contents_begin(), D
->contents_end(),
1074 /*IterateExternalFS=*/IsFallthrough
, *ExternalFS
, EC
));
1077 void RedirectingFileSystem::setExternalContentsPrefixDir(StringRef PrefixDir
) {
1078 ExternalContentsPrefixDir
= PrefixDir
.str();
1081 StringRef
RedirectingFileSystem::getExternalContentsPrefixDir() const {
1082 return ExternalContentsPrefixDir
;
1085 void RedirectingFileSystem::dump(raw_ostream
&OS
) const {
1086 for (const auto &Root
: Roots
)
1087 dumpEntry(OS
, Root
.get());
1090 void RedirectingFileSystem::dumpEntry(raw_ostream
&OS
,
1091 RedirectingFileSystem::Entry
*E
,
1092 int NumSpaces
) const {
1093 StringRef Name
= E
->getName();
1094 for (int i
= 0, e
= NumSpaces
; i
< e
; ++i
)
1096 OS
<< "'" << Name
.str().c_str() << "'"
1099 if (E
->getKind() == RedirectingFileSystem::EK_Directory
) {
1100 auto *DE
= dyn_cast
<RedirectingFileSystem::RedirectingDirectoryEntry
>(E
);
1101 assert(DE
&& "Should be a directory");
1103 for (std::unique_ptr
<Entry
> &SubEntry
:
1104 llvm::make_range(DE
->contents_begin(), DE
->contents_end()))
1105 dumpEntry(OS
, SubEntry
.get(), NumSpaces
+ 2);
1109 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1110 LLVM_DUMP_METHOD
void RedirectingFileSystem::dump() const { dump(dbgs()); }
1113 /// A helper class to hold the common YAML parsing state.
1114 class llvm::vfs::RedirectingFileSystemParser
{
1115 yaml::Stream
&Stream
;
1117 void error(yaml::Node
*N
, const Twine
&Msg
) { Stream
.printError(N
, Msg
); }
1120 bool parseScalarString(yaml::Node
*N
, StringRef
&Result
,
1121 SmallVectorImpl
<char> &Storage
) {
1122 const auto *S
= dyn_cast
<yaml::ScalarNode
>(N
);
1125 error(N
, "expected string");
1128 Result
= S
->getValue(Storage
);
1133 bool parseScalarBool(yaml::Node
*N
, bool &Result
) {
1134 SmallString
<5> Storage
;
1136 if (!parseScalarString(N
, Value
, Storage
))
1139 if (Value
.equals_lower("true") || Value
.equals_lower("on") ||
1140 Value
.equals_lower("yes") || Value
== "1") {
1143 } else if (Value
.equals_lower("false") || Value
.equals_lower("off") ||
1144 Value
.equals_lower("no") || Value
== "0") {
1149 error(N
, "expected boolean value");
1157 KeyStatus(bool Required
= false) : Required(Required
) {}
1160 using KeyStatusPair
= std::pair
<StringRef
, KeyStatus
>;
1163 bool checkDuplicateOrUnknownKey(yaml::Node
*KeyNode
, StringRef Key
,
1164 DenseMap
<StringRef
, KeyStatus
> &Keys
) {
1165 if (!Keys
.count(Key
)) {
1166 error(KeyNode
, "unknown key");
1169 KeyStatus
&S
= Keys
[Key
];
1171 error(KeyNode
, Twine("duplicate key '") + Key
+ "'");
1179 bool checkMissingKeys(yaml::Node
*Obj
, DenseMap
<StringRef
, KeyStatus
> &Keys
) {
1180 for (const auto &I
: Keys
) {
1181 if (I
.second
.Required
&& !I
.second
.Seen
) {
1182 error(Obj
, Twine("missing key '") + I
.first
+ "'");
1189 RedirectingFileSystem::Entry
*
1190 lookupOrCreateEntry(RedirectingFileSystem
*FS
, StringRef Name
,
1191 RedirectingFileSystem::Entry
*ParentEntry
= nullptr) {
1192 if (!ParentEntry
) { // Look for a existent root
1193 for (const auto &Root
: FS
->Roots
) {
1194 if (Name
.equals(Root
->getName())) {
1195 ParentEntry
= Root
.get();
1199 } else { // Advance to the next component
1200 auto *DE
= dyn_cast
<RedirectingFileSystem::RedirectingDirectoryEntry
>(
1202 for (std::unique_ptr
<RedirectingFileSystem::Entry
> &Content
:
1203 llvm::make_range(DE
->contents_begin(), DE
->contents_end())) {
1205 dyn_cast
<RedirectingFileSystem::RedirectingDirectoryEntry
>(
1207 if (DirContent
&& Name
.equals(Content
->getName()))
1212 // ... or create a new one
1213 std::unique_ptr
<RedirectingFileSystem::Entry
> E
=
1214 std::make_unique
<RedirectingFileSystem::RedirectingDirectoryEntry
>(
1215 Name
, Status("", getNextVirtualUniqueID(),
1216 std::chrono::system_clock::now(), 0, 0, 0,
1217 file_type::directory_file
, sys::fs::all_all
));
1219 if (!ParentEntry
) { // Add a new root to the overlay
1220 FS
->Roots
.push_back(std::move(E
));
1221 ParentEntry
= FS
->Roots
.back().get();
1226 dyn_cast
<RedirectingFileSystem::RedirectingDirectoryEntry
>(ParentEntry
);
1227 DE
->addContent(std::move(E
));
1228 return DE
->getLastContent();
1231 void uniqueOverlayTree(RedirectingFileSystem
*FS
,
1232 RedirectingFileSystem::Entry
*SrcE
,
1233 RedirectingFileSystem::Entry
*NewParentE
= nullptr) {
1234 StringRef Name
= SrcE
->getName();
1235 switch (SrcE
->getKind()) {
1236 case RedirectingFileSystem::EK_Directory
: {
1238 dyn_cast
<RedirectingFileSystem::RedirectingDirectoryEntry
>(SrcE
);
1239 assert(DE
&& "Must be a directory");
1240 // Empty directories could be present in the YAML as a way to
1241 // describe a file for a current directory after some of its subdir
1242 // is parsed. This only leads to redundant walks, ignore it.
1244 NewParentE
= lookupOrCreateEntry(FS
, Name
, NewParentE
);
1245 for (std::unique_ptr
<RedirectingFileSystem::Entry
> &SubEntry
:
1246 llvm::make_range(DE
->contents_begin(), DE
->contents_end()))
1247 uniqueOverlayTree(FS
, SubEntry
.get(), NewParentE
);
1250 case RedirectingFileSystem::EK_File
: {
1251 auto *FE
= dyn_cast
<RedirectingFileSystem::RedirectingFileEntry
>(SrcE
);
1252 assert(FE
&& "Must be a file");
1253 assert(NewParentE
&& "Parent entry must exist");
1254 auto *DE
= dyn_cast
<RedirectingFileSystem::RedirectingDirectoryEntry
>(
1257 std::make_unique
<RedirectingFileSystem::RedirectingFileEntry
>(
1258 Name
, FE
->getExternalContentsPath(), FE
->getUseName()));
1264 std::unique_ptr
<RedirectingFileSystem::Entry
>
1265 parseEntry(yaml::Node
*N
, RedirectingFileSystem
*FS
, bool IsRootEntry
) {
1266 auto *M
= dyn_cast
<yaml::MappingNode
>(N
);
1268 error(N
, "expected mapping node for file or directory entry");
1272 KeyStatusPair Fields
[] = {
1273 KeyStatusPair("name", true),
1274 KeyStatusPair("type", true),
1275 KeyStatusPair("contents", false),
1276 KeyStatusPair("external-contents", false),
1277 KeyStatusPair("use-external-name", false),
1280 DenseMap
<StringRef
, KeyStatus
> Keys(std::begin(Fields
), std::end(Fields
));
1282 bool HasContents
= false; // external or otherwise
1283 std::vector
<std::unique_ptr
<RedirectingFileSystem::Entry
>>
1285 std::string ExternalContentsPath
;
1287 yaml::Node
*NameValueNode
= nullptr;
1288 auto UseExternalName
=
1289 RedirectingFileSystem::RedirectingFileEntry::NK_NotSet
;
1290 RedirectingFileSystem::EntryKind Kind
;
1292 for (auto &I
: *M
) {
1294 // Reuse the buffer for key and value, since we don't look at key after
1296 SmallString
<256> Buffer
;
1297 if (!parseScalarString(I
.getKey(), Key
, Buffer
))
1300 if (!checkDuplicateOrUnknownKey(I
.getKey(), Key
, Keys
))
1304 if (Key
== "name") {
1305 if (!parseScalarString(I
.getValue(), Value
, Buffer
))
1308 NameValueNode
= I
.getValue();
1309 if (FS
->UseCanonicalizedPaths
) {
1310 SmallString
<256> Path(Value
);
1311 // Guarantee that old YAML files containing paths with ".." and "."
1312 // are properly canonicalized before read into the VFS.
1313 Path
= sys::path::remove_leading_dotslash(Path
);
1314 sys::path::remove_dots(Path
, /*remove_dot_dot=*/true);
1319 } else if (Key
== "type") {
1320 if (!parseScalarString(I
.getValue(), Value
, Buffer
))
1322 if (Value
== "file")
1323 Kind
= RedirectingFileSystem::EK_File
;
1324 else if (Value
== "directory")
1325 Kind
= RedirectingFileSystem::EK_Directory
;
1327 error(I
.getValue(), "unknown value for 'type'");
1330 } else if (Key
== "contents") {
1333 "entry already has 'contents' or 'external-contents'");
1337 auto *Contents
= dyn_cast
<yaml::SequenceNode
>(I
.getValue());
1339 // FIXME: this is only for directories, what about files?
1340 error(I
.getValue(), "expected array");
1344 for (auto &I
: *Contents
) {
1345 if (std::unique_ptr
<RedirectingFileSystem::Entry
> E
=
1346 parseEntry(&I
, FS
, /*IsRootEntry*/ false))
1347 EntryArrayContents
.push_back(std::move(E
));
1351 } else if (Key
== "external-contents") {
1354 "entry already has 'contents' or 'external-contents'");
1358 if (!parseScalarString(I
.getValue(), Value
, Buffer
))
1361 SmallString
<256> FullPath
;
1362 if (FS
->IsRelativeOverlay
) {
1363 FullPath
= FS
->getExternalContentsPrefixDir();
1364 assert(!FullPath
.empty() &&
1365 "External contents prefix directory must exist");
1366 llvm::sys::path::append(FullPath
, Value
);
1371 if (FS
->UseCanonicalizedPaths
) {
1372 // Guarantee that old YAML files containing paths with ".." and "."
1373 // are properly canonicalized before read into the VFS.
1374 FullPath
= sys::path::remove_leading_dotslash(FullPath
);
1375 sys::path::remove_dots(FullPath
, /*remove_dot_dot=*/true);
1377 ExternalContentsPath
= FullPath
.str();
1378 } else if (Key
== "use-external-name") {
1380 if (!parseScalarBool(I
.getValue(), Val
))
1383 Val
? RedirectingFileSystem::RedirectingFileEntry::NK_External
1384 : RedirectingFileSystem::RedirectingFileEntry::NK_Virtual
;
1386 llvm_unreachable("key missing from Keys");
1390 if (Stream
.failed())
1393 // check for missing keys
1395 error(N
, "missing key 'contents' or 'external-contents'");
1398 if (!checkMissingKeys(N
, Keys
))
1401 // check invalid configuration
1402 if (Kind
== RedirectingFileSystem::EK_Directory
&&
1404 RedirectingFileSystem::RedirectingFileEntry::NK_NotSet
) {
1405 error(N
, "'use-external-name' is not supported for directories");
1409 if (IsRootEntry
&& !sys::path::is_absolute(Name
)) {
1410 assert(NameValueNode
&& "Name presence should be checked earlier");
1411 error(NameValueNode
,
1412 "entry with relative path at the root level is not discoverable");
1416 // Remove trailing slash(es), being careful not to remove the root path
1417 StringRef
Trimmed(Name
);
1418 size_t RootPathLen
= sys::path::root_path(Trimmed
).size();
1419 while (Trimmed
.size() > RootPathLen
&&
1420 sys::path::is_separator(Trimmed
.back()))
1421 Trimmed
= Trimmed
.slice(0, Trimmed
.size() - 1);
1422 // Get the last component
1423 StringRef LastComponent
= sys::path::filename(Trimmed
);
1425 std::unique_ptr
<RedirectingFileSystem::Entry
> Result
;
1427 case RedirectingFileSystem::EK_File
:
1428 Result
= std::make_unique
<RedirectingFileSystem::RedirectingFileEntry
>(
1429 LastComponent
, std::move(ExternalContentsPath
), UseExternalName
);
1431 case RedirectingFileSystem::EK_Directory
:
1433 std::make_unique
<RedirectingFileSystem::RedirectingDirectoryEntry
>(
1434 LastComponent
, std::move(EntryArrayContents
),
1435 Status("", getNextVirtualUniqueID(),
1436 std::chrono::system_clock::now(), 0, 0, 0,
1437 file_type::directory_file
, sys::fs::all_all
));
1441 StringRef Parent
= sys::path::parent_path(Trimmed
);
1445 // if 'name' contains multiple components, create implicit directory entries
1446 for (sys::path::reverse_iterator I
= sys::path::rbegin(Parent
),
1447 E
= sys::path::rend(Parent
);
1449 std::vector
<std::unique_ptr
<RedirectingFileSystem::Entry
>> Entries
;
1450 Entries
.push_back(std::move(Result
));
1452 std::make_unique
<RedirectingFileSystem::RedirectingDirectoryEntry
>(
1453 *I
, std::move(Entries
),
1454 Status("", getNextVirtualUniqueID(),
1455 std::chrono::system_clock::now(), 0, 0, 0,
1456 file_type::directory_file
, sys::fs::all_all
));
1462 RedirectingFileSystemParser(yaml::Stream
&S
) : Stream(S
) {}
1465 bool parse(yaml::Node
*Root
, RedirectingFileSystem
*FS
) {
1466 auto *Top
= dyn_cast
<yaml::MappingNode
>(Root
);
1468 error(Root
, "expected mapping node");
1472 KeyStatusPair Fields
[] = {
1473 KeyStatusPair("version", true),
1474 KeyStatusPair("case-sensitive", false),
1475 KeyStatusPair("use-external-names", false),
1476 KeyStatusPair("overlay-relative", false),
1477 KeyStatusPair("fallthrough", false),
1478 KeyStatusPair("roots", true),
1481 DenseMap
<StringRef
, KeyStatus
> Keys(std::begin(Fields
), std::end(Fields
));
1482 std::vector
<std::unique_ptr
<RedirectingFileSystem::Entry
>> RootEntries
;
1484 // Parse configuration and 'roots'
1485 for (auto &I
: *Top
) {
1486 SmallString
<10> KeyBuffer
;
1488 if (!parseScalarString(I
.getKey(), Key
, KeyBuffer
))
1491 if (!checkDuplicateOrUnknownKey(I
.getKey(), Key
, Keys
))
1494 if (Key
== "roots") {
1495 auto *Roots
= dyn_cast
<yaml::SequenceNode
>(I
.getValue());
1497 error(I
.getValue(), "expected array");
1501 for (auto &I
: *Roots
) {
1502 if (std::unique_ptr
<RedirectingFileSystem::Entry
> E
=
1503 parseEntry(&I
, FS
, /*IsRootEntry*/ true))
1504 RootEntries
.push_back(std::move(E
));
1508 } else if (Key
== "version") {
1509 StringRef VersionString
;
1510 SmallString
<4> Storage
;
1511 if (!parseScalarString(I
.getValue(), VersionString
, Storage
))
1514 if (VersionString
.getAsInteger
<int>(10, Version
)) {
1515 error(I
.getValue(), "expected integer");
1519 error(I
.getValue(), "invalid version number");
1523 error(I
.getValue(), "version mismatch, expected 0");
1526 } else if (Key
== "case-sensitive") {
1527 if (!parseScalarBool(I
.getValue(), FS
->CaseSensitive
))
1529 } else if (Key
== "overlay-relative") {
1530 if (!parseScalarBool(I
.getValue(), FS
->IsRelativeOverlay
))
1532 } else if (Key
== "use-external-names") {
1533 if (!parseScalarBool(I
.getValue(), FS
->UseExternalNames
))
1535 } else if (Key
== "fallthrough") {
1536 if (!parseScalarBool(I
.getValue(), FS
->IsFallthrough
))
1539 llvm_unreachable("key missing from Keys");
1543 if (Stream
.failed())
1546 if (!checkMissingKeys(Top
, Keys
))
1549 // Now that we sucessefully parsed the YAML file, canonicalize the internal
1550 // representation to a proper directory tree so that we can search faster
1552 for (auto &E
: RootEntries
)
1553 uniqueOverlayTree(FS
, E
.get());
1559 RedirectingFileSystem
*
1560 RedirectingFileSystem::create(std::unique_ptr
<MemoryBuffer
> Buffer
,
1561 SourceMgr::DiagHandlerTy DiagHandler
,
1562 StringRef YAMLFilePath
, void *DiagContext
,
1563 IntrusiveRefCntPtr
<FileSystem
> ExternalFS
) {
1565 yaml::Stream
Stream(Buffer
->getMemBufferRef(), SM
);
1567 SM
.setDiagHandler(DiagHandler
, DiagContext
);
1568 yaml::document_iterator DI
= Stream
.begin();
1569 yaml::Node
*Root
= DI
->getRoot();
1570 if (DI
== Stream
.end() || !Root
) {
1571 SM
.PrintMessage(SMLoc(), SourceMgr::DK_Error
, "expected root node");
1575 RedirectingFileSystemParser
P(Stream
);
1577 std::unique_ptr
<RedirectingFileSystem
> FS(
1578 new RedirectingFileSystem(std::move(ExternalFS
)));
1580 if (!YAMLFilePath
.empty()) {
1581 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1582 // to each 'external-contents' path.
1585 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
1587 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1589 SmallString
<256> OverlayAbsDir
= sys::path::parent_path(YAMLFilePath
);
1590 std::error_code EC
= llvm::sys::fs::make_absolute(OverlayAbsDir
);
1591 assert(!EC
&& "Overlay dir final path must be absolute");
1593 FS
->setExternalContentsPrefixDir(OverlayAbsDir
);
1596 if (!P
.parse(Root
, FS
.get()))
1599 return FS
.release();
1602 ErrorOr
<RedirectingFileSystem::Entry
*>
1603 RedirectingFileSystem::lookupPath(const Twine
&Path_
) const {
1604 SmallString
<256> Path
;
1605 Path_
.toVector(Path
);
1607 // Handle relative paths
1608 if (std::error_code EC
= makeAbsolute(Path
))
1611 // Canonicalize path by removing ".", "..", "./", etc components. This is
1612 // a VFS request, do bot bother about symlinks in the path components
1613 // but canonicalize in order to perform the correct entry search.
1614 if (UseCanonicalizedPaths
) {
1615 Path
= sys::path::remove_leading_dotslash(Path
);
1616 sys::path::remove_dots(Path
, /*remove_dot_dot=*/true);
1620 return make_error_code(llvm::errc::invalid_argument
);
1622 sys::path::const_iterator Start
= sys::path::begin(Path
);
1623 sys::path::const_iterator End
= sys::path::end(Path
);
1624 for (const auto &Root
: Roots
) {
1625 ErrorOr
<RedirectingFileSystem::Entry
*> Result
=
1626 lookupPath(Start
, End
, Root
.get());
1627 if (Result
|| Result
.getError() != llvm::errc::no_such_file_or_directory
)
1630 return make_error_code(llvm::errc::no_such_file_or_directory
);
1633 ErrorOr
<RedirectingFileSystem::Entry
*>
1634 RedirectingFileSystem::lookupPath(sys::path::const_iterator Start
,
1635 sys::path::const_iterator End
,
1636 RedirectingFileSystem::Entry
*From
) const {
1638 assert(!isTraversalComponent(*Start
) &&
1639 !isTraversalComponent(From
->getName()) &&
1640 "Paths should not contain traversal components");
1642 // FIXME: this is here to support windows, remove it once canonicalized
1643 // paths become globally default.
1644 if (Start
->equals("."))
1648 StringRef FromName
= From
->getName();
1650 // Forward the search to the next component in case this is an empty one.
1651 if (!FromName
.empty()) {
1652 if (CaseSensitive
? !Start
->equals(FromName
)
1653 : !Start
->equals_lower(FromName
))
1655 return make_error_code(llvm::errc::no_such_file_or_directory
);
1665 auto *DE
= dyn_cast
<RedirectingFileSystem::RedirectingDirectoryEntry
>(From
);
1667 return make_error_code(llvm::errc::not_a_directory
);
1669 for (const std::unique_ptr
<RedirectingFileSystem::Entry
> &DirEntry
:
1670 llvm::make_range(DE
->contents_begin(), DE
->contents_end())) {
1671 ErrorOr
<RedirectingFileSystem::Entry
*> Result
=
1672 lookupPath(Start
, End
, DirEntry
.get());
1673 if (Result
|| Result
.getError() != llvm::errc::no_such_file_or_directory
)
1676 return make_error_code(llvm::errc::no_such_file_or_directory
);
1679 static Status
getRedirectedFileStatus(const Twine
&Path
, bool UseExternalNames
,
1680 Status ExternalStatus
) {
1681 Status S
= ExternalStatus
;
1682 if (!UseExternalNames
)
1683 S
= Status::copyWithNewName(S
, Path
);
1684 S
.IsVFSMapped
= true;
1688 ErrorOr
<Status
> RedirectingFileSystem::status(const Twine
&Path
,
1689 RedirectingFileSystem::Entry
*E
) {
1690 assert(E
!= nullptr);
1691 if (auto *F
= dyn_cast
<RedirectingFileSystem::RedirectingFileEntry
>(E
)) {
1692 ErrorOr
<Status
> S
= ExternalFS
->status(F
->getExternalContentsPath());
1693 assert(!S
|| S
->getName() == F
->getExternalContentsPath());
1695 return getRedirectedFileStatus(Path
, F
->useExternalName(UseExternalNames
),
1698 } else { // directory
1699 auto *DE
= cast
<RedirectingFileSystem::RedirectingDirectoryEntry
>(E
);
1700 return Status::copyWithNewName(DE
->getStatus(), Path
);
1704 ErrorOr
<Status
> RedirectingFileSystem::status(const Twine
&Path
) {
1705 ErrorOr
<RedirectingFileSystem::Entry
*> Result
= lookupPath(Path
);
1707 if (IsFallthrough
&&
1708 Result
.getError() == llvm::errc::no_such_file_or_directory
) {
1709 return ExternalFS
->status(Path
);
1711 return Result
.getError();
1713 return status(Path
, *Result
);
1718 /// Provide a file wrapper with an overriden status.
1719 class FileWithFixedStatus
: public File
{
1720 std::unique_ptr
<File
> InnerFile
;
1724 FileWithFixedStatus(std::unique_ptr
<File
> InnerFile
, Status S
)
1725 : InnerFile(std::move(InnerFile
)), S(std::move(S
)) {}
1727 ErrorOr
<Status
> status() override
{ return S
; }
1728 ErrorOr
<std::unique_ptr
<llvm::MemoryBuffer
>>
1730 getBuffer(const Twine
&Name
, int64_t FileSize
, bool RequiresNullTerminator
,
1731 bool IsVolatile
) override
{
1732 return InnerFile
->getBuffer(Name
, FileSize
, RequiresNullTerminator
,
1736 std::error_code
close() override
{ return InnerFile
->close(); }
1741 ErrorOr
<std::unique_ptr
<File
>>
1742 RedirectingFileSystem::openFileForRead(const Twine
&Path
) {
1743 ErrorOr
<RedirectingFileSystem::Entry
*> E
= lookupPath(Path
);
1745 if (IsFallthrough
&&
1746 E
.getError() == llvm::errc::no_such_file_or_directory
) {
1747 return ExternalFS
->openFileForRead(Path
);
1749 return E
.getError();
1752 auto *F
= dyn_cast
<RedirectingFileSystem::RedirectingFileEntry
>(*E
);
1753 if (!F
) // FIXME: errc::not_a_file?
1754 return make_error_code(llvm::errc::invalid_argument
);
1756 auto Result
= ExternalFS
->openFileForRead(F
->getExternalContentsPath());
1760 auto ExternalStatus
= (*Result
)->status();
1761 if (!ExternalStatus
)
1762 return ExternalStatus
.getError();
1764 // FIXME: Update the status with the name and VFSMapped.
1765 Status S
= getRedirectedFileStatus(Path
, F
->useExternalName(UseExternalNames
),
1767 return std::unique_ptr
<File
>(
1768 std::make_unique
<FileWithFixedStatus
>(std::move(*Result
), S
));
1772 RedirectingFileSystem::getRealPath(const Twine
&Path
,
1773 SmallVectorImpl
<char> &Output
) const {
1774 ErrorOr
<RedirectingFileSystem::Entry
*> Result
= lookupPath(Path
);
1776 if (IsFallthrough
&&
1777 Result
.getError() == llvm::errc::no_such_file_or_directory
) {
1778 return ExternalFS
->getRealPath(Path
, Output
);
1780 return Result
.getError();
1784 dyn_cast
<RedirectingFileSystem::RedirectingFileEntry
>(*Result
)) {
1785 return ExternalFS
->getRealPath(F
->getExternalContentsPath(), Output
);
1787 // Even if there is a directory entry, fall back to ExternalFS if allowed,
1788 // because directories don't have a single external contents path.
1789 return IsFallthrough
? ExternalFS
->getRealPath(Path
, Output
)
1790 : llvm::errc::invalid_argument
;
1793 IntrusiveRefCntPtr
<FileSystem
>
1794 vfs::getVFSFromYAML(std::unique_ptr
<MemoryBuffer
> Buffer
,
1795 SourceMgr::DiagHandlerTy DiagHandler
,
1796 StringRef YAMLFilePath
, void *DiagContext
,
1797 IntrusiveRefCntPtr
<FileSystem
> ExternalFS
) {
1798 return RedirectingFileSystem::create(std::move(Buffer
), DiagHandler
,
1799 YAMLFilePath
, DiagContext
,
1800 std::move(ExternalFS
));
1803 static void getVFSEntries(RedirectingFileSystem::Entry
*SrcE
,
1804 SmallVectorImpl
<StringRef
> &Path
,
1805 SmallVectorImpl
<YAMLVFSEntry
> &Entries
) {
1806 auto Kind
= SrcE
->getKind();
1807 if (Kind
== RedirectingFileSystem::EK_Directory
) {
1808 auto *DE
= dyn_cast
<RedirectingFileSystem::RedirectingDirectoryEntry
>(SrcE
);
1809 assert(DE
&& "Must be a directory");
1810 for (std::unique_ptr
<RedirectingFileSystem::Entry
> &SubEntry
:
1811 llvm::make_range(DE
->contents_begin(), DE
->contents_end())) {
1812 Path
.push_back(SubEntry
->getName());
1813 getVFSEntries(SubEntry
.get(), Path
, Entries
);
1819 assert(Kind
== RedirectingFileSystem::EK_File
&& "Must be a EK_File");
1820 auto *FE
= dyn_cast
<RedirectingFileSystem::RedirectingFileEntry
>(SrcE
);
1821 assert(FE
&& "Must be a file");
1822 SmallString
<128> VPath
;
1823 for (auto &Comp
: Path
)
1824 llvm::sys::path::append(VPath
, Comp
);
1825 Entries
.push_back(YAMLVFSEntry(VPath
.c_str(), FE
->getExternalContentsPath()));
1828 void vfs::collectVFSFromYAML(std::unique_ptr
<MemoryBuffer
> Buffer
,
1829 SourceMgr::DiagHandlerTy DiagHandler
,
1830 StringRef YAMLFilePath
,
1831 SmallVectorImpl
<YAMLVFSEntry
> &CollectedEntries
,
1833 IntrusiveRefCntPtr
<FileSystem
> ExternalFS
) {
1834 RedirectingFileSystem
*VFS
= RedirectingFileSystem::create(
1835 std::move(Buffer
), DiagHandler
, YAMLFilePath
, DiagContext
,
1836 std::move(ExternalFS
));
1837 ErrorOr
<RedirectingFileSystem::Entry
*> RootE
= VFS
->lookupPath("/");
1840 SmallVector
<StringRef
, 8> Components
;
1841 Components
.push_back("/");
1842 getVFSEntries(*RootE
, Components
, CollectedEntries
);
1845 UniqueID
vfs::getNextVirtualUniqueID() {
1846 static std::atomic
<unsigned> UID
;
1847 unsigned ID
= ++UID
;
1848 // The following assumes that uint64_t max will never collide with a real
1849 // dev_t value from the OS.
1850 return UniqueID(std::numeric_limits
<uint64_t>::max(), ID
);
1853 void YAMLVFSWriter::addFileMapping(StringRef VirtualPath
, StringRef RealPath
) {
1854 assert(sys::path::is_absolute(VirtualPath
) && "virtual path not absolute");
1855 assert(sys::path::is_absolute(RealPath
) && "real path not absolute");
1856 assert(!pathHasTraversal(VirtualPath
) && "path traversal is not supported");
1857 Mappings
.emplace_back(VirtualPath
, RealPath
);
1863 llvm::raw_ostream
&OS
;
1864 SmallVector
<StringRef
, 16> DirStack
;
1866 unsigned getDirIndent() { return 4 * DirStack
.size(); }
1867 unsigned getFileIndent() { return 4 * (DirStack
.size() + 1); }
1868 bool containedIn(StringRef Parent
, StringRef Path
);
1869 StringRef
containedPart(StringRef Parent
, StringRef Path
);
1870 void startDirectory(StringRef Path
);
1871 void endDirectory();
1872 void writeEntry(StringRef VPath
, StringRef RPath
);
1875 JSONWriter(llvm::raw_ostream
&OS
) : OS(OS
) {}
1877 void write(ArrayRef
<YAMLVFSEntry
> Entries
, Optional
<bool> UseExternalNames
,
1878 Optional
<bool> IsCaseSensitive
, Optional
<bool> IsOverlayRelative
,
1879 StringRef OverlayDir
);
1884 bool JSONWriter::containedIn(StringRef Parent
, StringRef Path
) {
1885 using namespace llvm::sys
;
1887 // Compare each path component.
1888 auto IParent
= path::begin(Parent
), EParent
= path::end(Parent
);
1889 for (auto IChild
= path::begin(Path
), EChild
= path::end(Path
);
1890 IParent
!= EParent
&& IChild
!= EChild
; ++IParent
, ++IChild
) {
1891 if (*IParent
!= *IChild
)
1894 // Have we exhausted the parent path?
1895 return IParent
== EParent
;
1898 StringRef
JSONWriter::containedPart(StringRef Parent
, StringRef Path
) {
1899 assert(!Parent
.empty());
1900 assert(containedIn(Parent
, Path
));
1901 return Path
.slice(Parent
.size() + 1, StringRef::npos
);
1904 void JSONWriter::startDirectory(StringRef Path
) {
1906 DirStack
.empty() ? Path
: containedPart(DirStack
.back(), Path
);
1907 DirStack
.push_back(Path
);
1908 unsigned Indent
= getDirIndent();
1909 OS
.indent(Indent
) << "{\n";
1910 OS
.indent(Indent
+ 2) << "'type': 'directory',\n";
1911 OS
.indent(Indent
+ 2) << "'name': \"" << llvm::yaml::escape(Name
) << "\",\n";
1912 OS
.indent(Indent
+ 2) << "'contents': [\n";
1915 void JSONWriter::endDirectory() {
1916 unsigned Indent
= getDirIndent();
1917 OS
.indent(Indent
+ 2) << "]\n";
1918 OS
.indent(Indent
) << "}";
1920 DirStack
.pop_back();
1923 void JSONWriter::writeEntry(StringRef VPath
, StringRef RPath
) {
1924 unsigned Indent
= getFileIndent();
1925 OS
.indent(Indent
) << "{\n";
1926 OS
.indent(Indent
+ 2) << "'type': 'file',\n";
1927 OS
.indent(Indent
+ 2) << "'name': \"" << llvm::yaml::escape(VPath
) << "\",\n";
1928 OS
.indent(Indent
+ 2) << "'external-contents': \""
1929 << llvm::yaml::escape(RPath
) << "\"\n";
1930 OS
.indent(Indent
) << "}";
1933 void JSONWriter::write(ArrayRef
<YAMLVFSEntry
> Entries
,
1934 Optional
<bool> UseExternalNames
,
1935 Optional
<bool> IsCaseSensitive
,
1936 Optional
<bool> IsOverlayRelative
,
1937 StringRef OverlayDir
) {
1938 using namespace llvm::sys
;
1942 if (IsCaseSensitive
.hasValue())
1943 OS
<< " 'case-sensitive': '"
1944 << (IsCaseSensitive
.getValue() ? "true" : "false") << "',\n";
1945 if (UseExternalNames
.hasValue())
1946 OS
<< " 'use-external-names': '"
1947 << (UseExternalNames
.getValue() ? "true" : "false") << "',\n";
1948 bool UseOverlayRelative
= false;
1949 if (IsOverlayRelative
.hasValue()) {
1950 UseOverlayRelative
= IsOverlayRelative
.getValue();
1951 OS
<< " 'overlay-relative': '" << (UseOverlayRelative
? "true" : "false")
1954 OS
<< " 'roots': [\n";
1956 if (!Entries
.empty()) {
1957 const YAMLVFSEntry
&Entry
= Entries
.front();
1958 startDirectory(path::parent_path(Entry
.VPath
));
1960 StringRef RPath
= Entry
.RPath
;
1961 if (UseOverlayRelative
) {
1962 unsigned OverlayDirLen
= OverlayDir
.size();
1963 assert(RPath
.substr(0, OverlayDirLen
) == OverlayDir
&&
1964 "Overlay dir must be contained in RPath");
1965 RPath
= RPath
.slice(OverlayDirLen
, RPath
.size());
1968 writeEntry(path::filename(Entry
.VPath
), RPath
);
1970 for (const auto &Entry
: Entries
.slice(1)) {
1971 StringRef Dir
= path::parent_path(Entry
.VPath
);
1972 if (Dir
== DirStack
.back())
1975 while (!DirStack
.empty() && !containedIn(DirStack
.back(), Dir
)) {
1980 startDirectory(Dir
);
1982 StringRef RPath
= Entry
.RPath
;
1983 if (UseOverlayRelative
) {
1984 unsigned OverlayDirLen
= OverlayDir
.size();
1985 assert(RPath
.substr(0, OverlayDirLen
) == OverlayDir
&&
1986 "Overlay dir must be contained in RPath");
1987 RPath
= RPath
.slice(OverlayDirLen
, RPath
.size());
1989 writeEntry(path::filename(Entry
.VPath
), RPath
);
1992 while (!DirStack
.empty()) {
2003 void YAMLVFSWriter::write(llvm::raw_ostream
&OS
) {
2004 llvm::sort(Mappings
, [](const YAMLVFSEntry
&LHS
, const YAMLVFSEntry
&RHS
) {
2005 return LHS
.VPath
< RHS
.VPath
;
2008 JSONWriter(OS
).write(Mappings
, UseExternalNames
, IsCaseSensitive
,
2009 IsOverlayRelative
, OverlayDir
);
2012 VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
2014 RedirectingFileSystem::RedirectingDirectoryEntry::iterator Begin
,
2015 RedirectingFileSystem::RedirectingDirectoryEntry::iterator End
,
2016 bool IterateExternalFS
, FileSystem
&ExternalFS
, std::error_code
&EC
)
2017 : Dir(_Path
.str()), Current(Begin
), End(End
),
2018 IterateExternalFS(IterateExternalFS
), ExternalFS(ExternalFS
) {
2019 EC
= incrementImpl(/*IsFirstTime=*/true);
2022 std::error_code
VFSFromYamlDirIterImpl::increment() {
2023 return incrementImpl(/*IsFirstTime=*/false);
2026 std::error_code
VFSFromYamlDirIterImpl::incrementExternal() {
2027 assert(!(IsExternalFSCurrent
&& ExternalDirIter
== directory_iterator()) &&
2028 "incrementing past end");
2030 if (IsExternalFSCurrent
) {
2031 ExternalDirIter
.increment(EC
);
2032 } else if (IterateExternalFS
) {
2033 ExternalDirIter
= ExternalFS
.dir_begin(Dir
, EC
);
2034 IsExternalFSCurrent
= true;
2035 if (EC
&& EC
!= errc::no_such_file_or_directory
)
2039 if (EC
|| ExternalDirIter
== directory_iterator()) {
2040 CurrentEntry
= directory_entry();
2042 CurrentEntry
= *ExternalDirIter
;
2047 std::error_code
VFSFromYamlDirIterImpl::incrementContent(bool IsFirstTime
) {
2048 assert((IsFirstTime
|| Current
!= End
) && "cannot iterate past end");
2051 while (Current
!= End
) {
2052 SmallString
<128> PathStr(Dir
);
2053 llvm::sys::path::append(PathStr
, (*Current
)->getName());
2054 sys::fs::file_type Type
;
2055 switch ((*Current
)->getKind()) {
2056 case RedirectingFileSystem::EK_Directory
:
2057 Type
= sys::fs::file_type::directory_file
;
2059 case RedirectingFileSystem::EK_File
:
2060 Type
= sys::fs::file_type::regular_file
;
2063 CurrentEntry
= directory_entry(PathStr
.str(), Type
);
2066 return incrementExternal();
2069 std::error_code
VFSFromYamlDirIterImpl::incrementImpl(bool IsFirstTime
) {
2071 std::error_code EC
= IsExternalFSCurrent
? incrementExternal()
2072 : incrementContent(IsFirstTime
);
2073 if (EC
|| CurrentEntry
.path().empty())
2075 StringRef Name
= llvm::sys::path::filename(CurrentEntry
.path());
2076 if (SeenNames
.insert(Name
).second
)
2077 return EC
; // name not seen before
2079 llvm_unreachable("returned above");
2082 vfs::recursive_directory_iterator::recursive_directory_iterator(
2083 FileSystem
&FS_
, const Twine
&Path
, std::error_code
&EC
)
2085 directory_iterator I
= FS
->dir_begin(Path
, EC
);
2086 if (I
!= directory_iterator()) {
2087 State
= std::make_shared
<detail::RecDirIterState
>();
2088 State
->Stack
.push(I
);
2092 vfs::recursive_directory_iterator
&
2093 recursive_directory_iterator::increment(std::error_code
&EC
) {
2094 assert(FS
&& State
&& !State
->Stack
.empty() && "incrementing past end");
2095 assert(!State
->Stack
.top()->path().empty() && "non-canonical end iterator");
2096 vfs::directory_iterator End
;
2098 if (State
->HasNoPushRequest
)
2099 State
->HasNoPushRequest
= false;
2101 if (State
->Stack
.top()->type() == sys::fs::file_type::directory_file
) {
2102 vfs::directory_iterator I
= FS
->dir_begin(State
->Stack
.top()->path(), EC
);
2104 State
->Stack
.push(I
);
2110 while (!State
->Stack
.empty() && State
->Stack
.top().increment(EC
) == End
)
2113 if (State
->Stack
.empty())
2114 State
.reset(); // end iterator