10b57cec5SDimitry Andric //===- VirtualFileSystem.h - Virtual File System Layer ----------*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric /// \file
100b57cec5SDimitry Andric /// Defines the virtual file system interface vfs::FileSystem.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #ifndef LLVM_SUPPORT_VIRTUALFILESYSTEM_H
150b57cec5SDimitry Andric #define LLVM_SUPPORT_VIRTUALFILESYSTEM_H
160b57cec5SDimitry Andric 
170b57cec5SDimitry Andric #include "llvm/ADT/IntrusiveRefCntPtr.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
190b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
2004eeddc0SDimitry Andric #include "llvm/ADT/STLFunctionalExtras.h"
210b57cec5SDimitry Andric #include "llvm/Support/Chrono.h"
220b57cec5SDimitry Andric #include "llvm/Support/ErrorOr.h"
2381ad6265SDimitry Andric #include "llvm/Support/Errc.h"
240b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
250b57cec5SDimitry Andric #include "llvm/Support/Path.h"
260b57cec5SDimitry Andric #include "llvm/Support/SourceMgr.h"
270b57cec5SDimitry Andric #include <cassert>
280b57cec5SDimitry Andric #include <cstdint>
290b57cec5SDimitry Andric #include <ctime>
300b57cec5SDimitry Andric #include <memory>
31bdd1243dSDimitry Andric #include <optional>
320b57cec5SDimitry Andric #include <stack>
330b57cec5SDimitry Andric #include <string>
340b57cec5SDimitry Andric #include <system_error>
350b57cec5SDimitry Andric #include <utility>
360b57cec5SDimitry Andric #include <vector>
370b57cec5SDimitry Andric 
380b57cec5SDimitry Andric namespace llvm {
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric class MemoryBuffer;
41e8d8bef9SDimitry Andric class MemoryBufferRef;
425ffd83dbSDimitry Andric class Twine;
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric namespace vfs {
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric /// The result of a \p status operation.
470b57cec5SDimitry Andric class Status {
480b57cec5SDimitry Andric   std::string Name;
490b57cec5SDimitry Andric   llvm::sys::fs::UniqueID UID;
500b57cec5SDimitry Andric   llvm::sys::TimePoint<> MTime;
510b57cec5SDimitry Andric   uint32_t User;
520b57cec5SDimitry Andric   uint32_t Group;
530b57cec5SDimitry Andric   uint64_t Size;
540b57cec5SDimitry Andric   llvm::sys::fs::file_type Type = llvm::sys::fs::file_type::status_error;
550b57cec5SDimitry Andric   llvm::sys::fs::perms Perms;
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric public:
580b57cec5SDimitry Andric   // FIXME: remove when files support multiple names
590b57cec5SDimitry Andric   bool IsVFSMapped = false;
600b57cec5SDimitry Andric 
6181ad6265SDimitry Andric   /// Whether this entity has an external path different from the virtual path,
6281ad6265SDimitry Andric   /// and the external path is exposed by leaking it through the abstraction.
6381ad6265SDimitry Andric   /// For example, a RedirectingFileSystem will set this for paths where
6481ad6265SDimitry Andric   /// UseExternalName is true.
6581ad6265SDimitry Andric   ///
6681ad6265SDimitry Andric   /// FIXME: Currently the external path is exposed by replacing the virtual
6781ad6265SDimitry Andric   /// path in this Status object. Instead, we should leave the path in the
6881ad6265SDimitry Andric   /// Status intact (matching the requested virtual path) - see
695f757f3fSDimitry Andric   /// FileManager::getFileRef for how we plan to fix this.
7081ad6265SDimitry Andric   bool ExposesExternalVFSPath = false;
7181ad6265SDimitry Andric 
720b57cec5SDimitry Andric   Status() = default;
730b57cec5SDimitry Andric   Status(const llvm::sys::fs::file_status &Status);
740b57cec5SDimitry Andric   Status(const Twine &Name, llvm::sys::fs::UniqueID UID,
750b57cec5SDimitry Andric          llvm::sys::TimePoint<> MTime, uint32_t User, uint32_t Group,
760b57cec5SDimitry Andric          uint64_t Size, llvm::sys::fs::file_type Type,
770b57cec5SDimitry Andric          llvm::sys::fs::perms Perms);
780b57cec5SDimitry Andric 
790eae32dcSDimitry Andric   /// Get a copy of a Status with a different size.
800eae32dcSDimitry Andric   static Status copyWithNewSize(const Status &In, uint64_t NewSize);
810b57cec5SDimitry Andric   /// Get a copy of a Status with a different name.
820b57cec5SDimitry Andric   static Status copyWithNewName(const Status &In, const Twine &NewName);
830b57cec5SDimitry Andric   static Status copyWithNewName(const llvm::sys::fs::file_status &In,
840b57cec5SDimitry Andric                                 const Twine &NewName);
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric   /// Returns the name that should be used for this file or directory.
getName()870b57cec5SDimitry Andric   StringRef getName() const { return Name; }
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric   /// @name Status interface from llvm::sys::fs
900b57cec5SDimitry Andric   /// @{
getType()910b57cec5SDimitry Andric   llvm::sys::fs::file_type getType() const { return Type; }
getPermissions()920b57cec5SDimitry Andric   llvm::sys::fs::perms getPermissions() const { return Perms; }
getLastModificationTime()930b57cec5SDimitry Andric   llvm::sys::TimePoint<> getLastModificationTime() const { return MTime; }
getUniqueID()940b57cec5SDimitry Andric   llvm::sys::fs::UniqueID getUniqueID() const { return UID; }
getUser()950b57cec5SDimitry Andric   uint32_t getUser() const { return User; }
getGroup()960b57cec5SDimitry Andric   uint32_t getGroup() const { return Group; }
getSize()970b57cec5SDimitry Andric   uint64_t getSize() const { return Size; }
980b57cec5SDimitry Andric   /// @}
990b57cec5SDimitry Andric   /// @name Status queries
1000b57cec5SDimitry Andric   /// These are static queries in llvm::sys::fs.
1010b57cec5SDimitry Andric   /// @{
1020b57cec5SDimitry Andric   bool equivalent(const Status &Other) const;
1030b57cec5SDimitry Andric   bool isDirectory() const;
1040b57cec5SDimitry Andric   bool isRegularFile() const;
1050b57cec5SDimitry Andric   bool isOther() const;
1060b57cec5SDimitry Andric   bool isSymlink() const;
1070b57cec5SDimitry Andric   bool isStatusKnown() const;
1080b57cec5SDimitry Andric   bool exists() const;
1090b57cec5SDimitry Andric   /// @}
1100b57cec5SDimitry Andric };
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric /// Represents an open file.
1130b57cec5SDimitry Andric class File {
1140b57cec5SDimitry Andric public:
1150b57cec5SDimitry Andric   /// Destroy the file after closing it (if open).
1160b57cec5SDimitry Andric   /// Sub-classes should generally call close() inside their destructors.  We
1170b57cec5SDimitry Andric   /// cannot do that from the base class, since close is virtual.
1180b57cec5SDimitry Andric   virtual ~File();
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric   /// Get the status of the file.
1210b57cec5SDimitry Andric   virtual llvm::ErrorOr<Status> status() = 0;
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric   /// Get the name of the file
getName()1240b57cec5SDimitry Andric   virtual llvm::ErrorOr<std::string> getName() {
1250b57cec5SDimitry Andric     if (auto Status = status())
1260b57cec5SDimitry Andric       return Status->getName().str();
1270b57cec5SDimitry Andric     else
1280b57cec5SDimitry Andric       return Status.getError();
1290b57cec5SDimitry Andric   }
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric   /// Get the contents of the file as a \p MemoryBuffer.
1320b57cec5SDimitry Andric   virtual llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
1330b57cec5SDimitry Andric   getBuffer(const Twine &Name, int64_t FileSize = -1,
1340b57cec5SDimitry Andric             bool RequiresNullTerminator = true, bool IsVolatile = false) = 0;
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric   /// Closes the file.
1370b57cec5SDimitry Andric   virtual std::error_code close() = 0;
138349cc55cSDimitry Andric 
139349cc55cSDimitry Andric   // Get the same file with a different path.
140349cc55cSDimitry Andric   static ErrorOr<std::unique_ptr<File>>
141349cc55cSDimitry Andric   getWithPath(ErrorOr<std::unique_ptr<File>> Result, const Twine &P);
142349cc55cSDimitry Andric 
143349cc55cSDimitry Andric protected:
144349cc55cSDimitry Andric   // Set the file's underlying path.
setPath(const Twine & Path)145349cc55cSDimitry Andric   virtual void setPath(const Twine &Path) {}
1460b57cec5SDimitry Andric };
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric /// A member of a directory, yielded by a directory_iterator.
1490b57cec5SDimitry Andric /// Only information available on most platforms is included.
1500b57cec5SDimitry Andric class directory_entry {
1510b57cec5SDimitry Andric   std::string Path;
152480093f4SDimitry Andric   llvm::sys::fs::file_type Type = llvm::sys::fs::file_type::type_unknown;
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric public:
1550b57cec5SDimitry Andric   directory_entry() = default;
directory_entry(std::string Path,llvm::sys::fs::file_type Type)1560b57cec5SDimitry Andric   directory_entry(std::string Path, llvm::sys::fs::file_type Type)
1570b57cec5SDimitry Andric       : Path(std::move(Path)), Type(Type) {}
1580b57cec5SDimitry Andric 
path()1590b57cec5SDimitry Andric   llvm::StringRef path() const { return Path; }
type()1600b57cec5SDimitry Andric   llvm::sys::fs::file_type type() const { return Type; }
1610b57cec5SDimitry Andric };
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric namespace detail {
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric /// An interface for virtual file systems to provide an iterator over the
1660b57cec5SDimitry Andric /// (non-recursive) contents of a directory.
1670b57cec5SDimitry Andric struct DirIterImpl {
1680b57cec5SDimitry Andric   virtual ~DirIterImpl();
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   /// Sets \c CurrentEntry to the next entry in the directory on success,
1710b57cec5SDimitry Andric   /// to directory_entry() at end,  or returns a system-defined \c error_code.
1720b57cec5SDimitry Andric   virtual std::error_code increment() = 0;
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric   directory_entry CurrentEntry;
1750b57cec5SDimitry Andric };
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric } // namespace detail
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric /// An input iterator over the entries in a virtual path, similar to
1800b57cec5SDimitry Andric /// llvm::sys::fs::directory_iterator.
1810b57cec5SDimitry Andric class directory_iterator {
1820b57cec5SDimitry Andric   std::shared_ptr<detail::DirIterImpl> Impl; // Input iterator semantics on copy
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric public:
directory_iterator(std::shared_ptr<detail::DirIterImpl> I)1850b57cec5SDimitry Andric   directory_iterator(std::shared_ptr<detail::DirIterImpl> I)
1860b57cec5SDimitry Andric       : Impl(std::move(I)) {
1870b57cec5SDimitry Andric     assert(Impl.get() != nullptr && "requires non-null implementation");
1880b57cec5SDimitry Andric     if (Impl->CurrentEntry.path().empty())
1890b57cec5SDimitry Andric       Impl.reset(); // Normalize the end iterator to Impl == nullptr.
1900b57cec5SDimitry Andric   }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   /// Construct an 'end' iterator.
1930b57cec5SDimitry Andric   directory_iterator() = default;
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric   /// Equivalent to operator++, with an error code.
increment(std::error_code & EC)1960b57cec5SDimitry Andric   directory_iterator &increment(std::error_code &EC) {
1970b57cec5SDimitry Andric     assert(Impl && "attempting to increment past end");
1980b57cec5SDimitry Andric     EC = Impl->increment();
1990b57cec5SDimitry Andric     if (Impl->CurrentEntry.path().empty())
2000b57cec5SDimitry Andric       Impl.reset(); // Normalize the end iterator to Impl == nullptr.
2010b57cec5SDimitry Andric     return *this;
2020b57cec5SDimitry Andric   }
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric   const directory_entry &operator*() const { return Impl->CurrentEntry; }
2050b57cec5SDimitry Andric   const directory_entry *operator->() const { return &Impl->CurrentEntry; }
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric   bool operator==(const directory_iterator &RHS) const {
2080b57cec5SDimitry Andric     if (Impl && RHS.Impl)
2090b57cec5SDimitry Andric       return Impl->CurrentEntry.path() == RHS.Impl->CurrentEntry.path();
2100b57cec5SDimitry Andric     return !Impl && !RHS.Impl;
2110b57cec5SDimitry Andric   }
2120b57cec5SDimitry Andric   bool operator!=(const directory_iterator &RHS) const {
2130b57cec5SDimitry Andric     return !(*this == RHS);
2140b57cec5SDimitry Andric   }
2150b57cec5SDimitry Andric };
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric class FileSystem;
2180b57cec5SDimitry Andric 
2190b57cec5SDimitry Andric namespace detail {
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric /// Keeps state for the recursive_directory_iterator.
2220b57cec5SDimitry Andric struct RecDirIterState {
2230b57cec5SDimitry Andric   std::stack<directory_iterator, std::vector<directory_iterator>> Stack;
2240b57cec5SDimitry Andric   bool HasNoPushRequest = false;
2250b57cec5SDimitry Andric };
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric } // end namespace detail
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric /// An input iterator over the recursive contents of a virtual path,
2300b57cec5SDimitry Andric /// similar to llvm::sys::fs::recursive_directory_iterator.
2310b57cec5SDimitry Andric class recursive_directory_iterator {
2320b57cec5SDimitry Andric   FileSystem *FS;
2330b57cec5SDimitry Andric   std::shared_ptr<detail::RecDirIterState>
2340b57cec5SDimitry Andric       State; // Input iterator semantics on copy.
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric public:
2370b57cec5SDimitry Andric   recursive_directory_iterator(FileSystem &FS, const Twine &Path,
2380b57cec5SDimitry Andric                                std::error_code &EC);
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric   /// Construct an 'end' iterator.
2410b57cec5SDimitry Andric   recursive_directory_iterator() = default;
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric   /// Equivalent to operator++, with an error code.
2440b57cec5SDimitry Andric   recursive_directory_iterator &increment(std::error_code &EC);
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric   const directory_entry &operator*() const { return *State->Stack.top(); }
2470b57cec5SDimitry Andric   const directory_entry *operator->() const { return &*State->Stack.top(); }
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric   bool operator==(const recursive_directory_iterator &Other) const {
2500b57cec5SDimitry Andric     return State == Other.State; // identity
2510b57cec5SDimitry Andric   }
2520b57cec5SDimitry Andric   bool operator!=(const recursive_directory_iterator &RHS) const {
2530b57cec5SDimitry Andric     return !(*this == RHS);
2540b57cec5SDimitry Andric   }
2550b57cec5SDimitry Andric 
2560b57cec5SDimitry Andric   /// Gets the current level. Starting path is at level 0.
level()2570b57cec5SDimitry Andric   int level() const {
2580b57cec5SDimitry Andric     assert(!State->Stack.empty() &&
2590b57cec5SDimitry Andric            "Cannot get level without any iteration state");
2600b57cec5SDimitry Andric     return State->Stack.size() - 1;
2610b57cec5SDimitry Andric   }
2620b57cec5SDimitry Andric 
no_push()2630b57cec5SDimitry Andric   void no_push() { State->HasNoPushRequest = true; }
2640b57cec5SDimitry Andric };
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric /// The virtual file system interface.
2670b57cec5SDimitry Andric class FileSystem : public llvm::ThreadSafeRefCountedBase<FileSystem> {
2680b57cec5SDimitry Andric public:
2690b57cec5SDimitry Andric   virtual ~FileSystem();
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric   /// Get the status of the entry at \p Path, if one exists.
2720b57cec5SDimitry Andric   virtual llvm::ErrorOr<Status> status(const Twine &Path) = 0;
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric   /// Get a \p File object for the file at \p Path, if one exists.
2750b57cec5SDimitry Andric   virtual llvm::ErrorOr<std::unique_ptr<File>>
2760b57cec5SDimitry Andric   openFileForRead(const Twine &Path) = 0;
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric   /// This is a convenience method that opens a file, gets its content and then
2790b57cec5SDimitry Andric   /// closes the file.
2800b57cec5SDimitry Andric   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
2810b57cec5SDimitry Andric   getBufferForFile(const Twine &Name, int64_t FileSize = -1,
2820b57cec5SDimitry Andric                    bool RequiresNullTerminator = true, bool IsVolatile = false);
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric   /// Get a directory_iterator for \p Dir.
2850b57cec5SDimitry Andric   /// \note The 'end' iterator is directory_iterator().
2860b57cec5SDimitry Andric   virtual directory_iterator dir_begin(const Twine &Dir,
2870b57cec5SDimitry Andric                                        std::error_code &EC) = 0;
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric   /// Set the working directory. This will affect all following operations on
2900b57cec5SDimitry Andric   /// this file system and may propagate down for nested file systems.
2910b57cec5SDimitry Andric   virtual std::error_code setCurrentWorkingDirectory(const Twine &Path) = 0;
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric   /// Get the working directory of this file system.
2940b57cec5SDimitry Andric   virtual llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const = 0;
2950b57cec5SDimitry Andric 
2960b57cec5SDimitry Andric   /// Gets real path of \p Path e.g. collapse all . and .. patterns, resolve
2970b57cec5SDimitry Andric   /// symlinks. For real file system, this uses `llvm::sys::fs::real_path`.
2980b57cec5SDimitry Andric   /// This returns errc::operation_not_permitted if not implemented by subclass.
2990b57cec5SDimitry Andric   virtual std::error_code getRealPath(const Twine &Path,
3000b57cec5SDimitry Andric                                       SmallVectorImpl<char> &Output) const;
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric   /// Check whether a file exists. Provided for convenience.
3030b57cec5SDimitry Andric   bool exists(const Twine &Path);
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric   /// Is the file mounted on a local filesystem?
3060b57cec5SDimitry Andric   virtual std::error_code isLocal(const Twine &Path, bool &Result);
3070b57cec5SDimitry Andric 
3080b57cec5SDimitry Andric   /// Make \a Path an absolute path.
3090b57cec5SDimitry Andric   ///
3100b57cec5SDimitry Andric   /// Makes \a Path absolute using the current directory if it is not already.
3110b57cec5SDimitry Andric   /// An empty \a Path will result in the current directory.
3120b57cec5SDimitry Andric   ///
3130b57cec5SDimitry Andric   /// /absolute/path   => /absolute/path
3140b57cec5SDimitry Andric   /// relative/../path => <current-directory>/relative/../path
3150b57cec5SDimitry Andric   ///
3160b57cec5SDimitry Andric   /// \param Path A path that is modified to be an absolute path.
3170b57cec5SDimitry Andric   /// \returns success if \a path has been made absolute, otherwise a
3180b57cec5SDimitry Andric   ///          platform-specific error_code.
319480093f4SDimitry Andric   virtual std::error_code makeAbsolute(SmallVectorImpl<char> &Path) const;
32081ad6265SDimitry Andric 
32181ad6265SDimitry Andric   enum class PrintType { Summary, Contents, RecursiveContents };
32281ad6265SDimitry Andric   void print(raw_ostream &OS, PrintType Type = PrintType::Contents,
32381ad6265SDimitry Andric              unsigned IndentLevel = 0) const {
32481ad6265SDimitry Andric     printImpl(OS, Type, IndentLevel);
32581ad6265SDimitry Andric   }
32681ad6265SDimitry Andric 
32781ad6265SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
32881ad6265SDimitry Andric   LLVM_DUMP_METHOD void dump() const;
32981ad6265SDimitry Andric #endif
33081ad6265SDimitry Andric 
33181ad6265SDimitry Andric protected:
printImpl(raw_ostream & OS,PrintType Type,unsigned IndentLevel)33281ad6265SDimitry Andric   virtual void printImpl(raw_ostream &OS, PrintType Type,
33381ad6265SDimitry Andric                          unsigned IndentLevel) const {
33481ad6265SDimitry Andric     printIndent(OS, IndentLevel);
33581ad6265SDimitry Andric     OS << "FileSystem\n";
33681ad6265SDimitry Andric   }
33781ad6265SDimitry Andric 
printIndent(raw_ostream & OS,unsigned IndentLevel)33881ad6265SDimitry Andric   void printIndent(raw_ostream &OS, unsigned IndentLevel) const {
33981ad6265SDimitry Andric     for (unsigned i = 0; i < IndentLevel; ++i)
34081ad6265SDimitry Andric       OS << "  ";
34181ad6265SDimitry Andric   }
3420b57cec5SDimitry Andric };
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric /// Gets an \p vfs::FileSystem for the 'real' file system, as seen by
3450b57cec5SDimitry Andric /// the operating system.
3460b57cec5SDimitry Andric /// The working directory is linked to the process's working directory.
3470b57cec5SDimitry Andric /// (This is usually thread-hostile).
3480b57cec5SDimitry Andric IntrusiveRefCntPtr<FileSystem> getRealFileSystem();
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric /// Create an \p vfs::FileSystem for the 'real' file system, as seen by
3510b57cec5SDimitry Andric /// the operating system.
3520b57cec5SDimitry Andric /// It has its own working directory, independent of (but initially equal to)
3530b57cec5SDimitry Andric /// that of the process.
3540b57cec5SDimitry Andric std::unique_ptr<FileSystem> createPhysicalFileSystem();
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric /// A file system that allows overlaying one \p AbstractFileSystem on top
3570b57cec5SDimitry Andric /// of another.
3580b57cec5SDimitry Andric ///
3590b57cec5SDimitry Andric /// Consists of a stack of >=1 \p FileSystem objects, which are treated as being
3600b57cec5SDimitry Andric /// one merged file system. When there is a directory that exists in more than
3610b57cec5SDimitry Andric /// one file system, the \p OverlayFileSystem contains a directory containing
3620b57cec5SDimitry Andric /// the union of their contents.  The attributes (permissions, etc.) of the
3630b57cec5SDimitry Andric /// top-most (most recently added) directory are used.  When there is a file
3640b57cec5SDimitry Andric /// that exists in more than one file system, the file in the top-most file
3650b57cec5SDimitry Andric /// system overrides the other(s).
3660b57cec5SDimitry Andric class OverlayFileSystem : public FileSystem {
3670b57cec5SDimitry Andric   using FileSystemList = SmallVector<IntrusiveRefCntPtr<FileSystem>, 1>;
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric   /// The stack of file systems, implemented as a list in order of
3700b57cec5SDimitry Andric   /// their addition.
3710b57cec5SDimitry Andric   FileSystemList FSList;
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric public:
3740b57cec5SDimitry Andric   OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> Base);
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric   /// Pushes a file system on top of the stack.
3770b57cec5SDimitry Andric   void pushOverlay(IntrusiveRefCntPtr<FileSystem> FS);
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric   llvm::ErrorOr<Status> status(const Twine &Path) override;
3800b57cec5SDimitry Andric   llvm::ErrorOr<std::unique_ptr<File>>
3810b57cec5SDimitry Andric   openFileForRead(const Twine &Path) override;
3820b57cec5SDimitry Andric   directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
3830b57cec5SDimitry Andric   llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
3840b57cec5SDimitry Andric   std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
3850b57cec5SDimitry Andric   std::error_code isLocal(const Twine &Path, bool &Result) override;
3860b57cec5SDimitry Andric   std::error_code getRealPath(const Twine &Path,
3870b57cec5SDimitry Andric                               SmallVectorImpl<char> &Output) const override;
3880b57cec5SDimitry Andric 
3890b57cec5SDimitry Andric   using iterator = FileSystemList::reverse_iterator;
3900b57cec5SDimitry Andric   using const_iterator = FileSystemList::const_reverse_iterator;
3910b57cec5SDimitry Andric   using reverse_iterator = FileSystemList::iterator;
3920b57cec5SDimitry Andric   using const_reverse_iterator = FileSystemList::const_iterator;
39381ad6265SDimitry Andric   using range = iterator_range<iterator>;
39481ad6265SDimitry Andric   using const_range = iterator_range<const_iterator>;
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric   /// Get an iterator pointing to the most recently added file system.
overlays_begin()3970b57cec5SDimitry Andric   iterator overlays_begin() { return FSList.rbegin(); }
overlays_begin()3980b57cec5SDimitry Andric   const_iterator overlays_begin() const { return FSList.rbegin(); }
3990b57cec5SDimitry Andric 
4000b57cec5SDimitry Andric   /// Get an iterator pointing one-past the least recently added file system.
overlays_end()4010b57cec5SDimitry Andric   iterator overlays_end() { return FSList.rend(); }
overlays_end()4020b57cec5SDimitry Andric   const_iterator overlays_end() const { return FSList.rend(); }
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric   /// Get an iterator pointing to the least recently added file system.
overlays_rbegin()4050b57cec5SDimitry Andric   reverse_iterator overlays_rbegin() { return FSList.begin(); }
overlays_rbegin()4060b57cec5SDimitry Andric   const_reverse_iterator overlays_rbegin() const { return FSList.begin(); }
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric   /// Get an iterator pointing one-past the most recently added file system.
overlays_rend()4090b57cec5SDimitry Andric   reverse_iterator overlays_rend() { return FSList.end(); }
overlays_rend()4100b57cec5SDimitry Andric   const_reverse_iterator overlays_rend() const { return FSList.end(); }
41181ad6265SDimitry Andric 
overlays_range()41281ad6265SDimitry Andric   range overlays_range() { return llvm::reverse(FSList); }
overlays_range()41381ad6265SDimitry Andric   const_range overlays_range() const { return llvm::reverse(FSList); }
41481ad6265SDimitry Andric 
41581ad6265SDimitry Andric protected:
41681ad6265SDimitry Andric   void printImpl(raw_ostream &OS, PrintType Type,
41781ad6265SDimitry Andric                  unsigned IndentLevel) const override;
4180b57cec5SDimitry Andric };
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric /// By default, this delegates all calls to the underlying file system. This
4210b57cec5SDimitry Andric /// is useful when derived file systems want to override some calls and still
4220b57cec5SDimitry Andric /// proxy other calls.
4230b57cec5SDimitry Andric class ProxyFileSystem : public FileSystem {
4240b57cec5SDimitry Andric public:
ProxyFileSystem(IntrusiveRefCntPtr<FileSystem> FS)4250b57cec5SDimitry Andric   explicit ProxyFileSystem(IntrusiveRefCntPtr<FileSystem> FS)
4260b57cec5SDimitry Andric       : FS(std::move(FS)) {}
4270b57cec5SDimitry Andric 
status(const Twine & Path)4280b57cec5SDimitry Andric   llvm::ErrorOr<Status> status(const Twine &Path) override {
4290b57cec5SDimitry Andric     return FS->status(Path);
4300b57cec5SDimitry Andric   }
4310b57cec5SDimitry Andric   llvm::ErrorOr<std::unique_ptr<File>>
openFileForRead(const Twine & Path)4320b57cec5SDimitry Andric   openFileForRead(const Twine &Path) override {
4330b57cec5SDimitry Andric     return FS->openFileForRead(Path);
4340b57cec5SDimitry Andric   }
dir_begin(const Twine & Dir,std::error_code & EC)4350b57cec5SDimitry Andric   directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override {
4360b57cec5SDimitry Andric     return FS->dir_begin(Dir, EC);
4370b57cec5SDimitry Andric   }
getCurrentWorkingDirectory()4380b57cec5SDimitry Andric   llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
4390b57cec5SDimitry Andric     return FS->getCurrentWorkingDirectory();
4400b57cec5SDimitry Andric   }
setCurrentWorkingDirectory(const Twine & Path)4410b57cec5SDimitry Andric   std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
4420b57cec5SDimitry Andric     return FS->setCurrentWorkingDirectory(Path);
4430b57cec5SDimitry Andric   }
getRealPath(const Twine & Path,SmallVectorImpl<char> & Output)4440b57cec5SDimitry Andric   std::error_code getRealPath(const Twine &Path,
4450b57cec5SDimitry Andric                               SmallVectorImpl<char> &Output) const override {
4460b57cec5SDimitry Andric     return FS->getRealPath(Path, Output);
4470b57cec5SDimitry Andric   }
isLocal(const Twine & Path,bool & Result)4480b57cec5SDimitry Andric   std::error_code isLocal(const Twine &Path, bool &Result) override {
4490b57cec5SDimitry Andric     return FS->isLocal(Path, Result);
4500b57cec5SDimitry Andric   }
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric protected:
getUnderlyingFS()453bdd1243dSDimitry Andric   FileSystem &getUnderlyingFS() const { return *FS; }
4540b57cec5SDimitry Andric 
4550b57cec5SDimitry Andric private:
4560b57cec5SDimitry Andric   IntrusiveRefCntPtr<FileSystem> FS;
4570b57cec5SDimitry Andric 
4580b57cec5SDimitry Andric   virtual void anchor();
4590b57cec5SDimitry Andric };
4600b57cec5SDimitry Andric 
4610b57cec5SDimitry Andric namespace detail {
4620b57cec5SDimitry Andric 
4630b57cec5SDimitry Andric class InMemoryDirectory;
46404eeddc0SDimitry Andric class InMemoryNode;
46504eeddc0SDimitry Andric 
46604eeddc0SDimitry Andric struct NewInMemoryNodeInfo {
46704eeddc0SDimitry Andric   llvm::sys::fs::UniqueID DirUID;
46804eeddc0SDimitry Andric   StringRef Path;
46904eeddc0SDimitry Andric   StringRef Name;
47004eeddc0SDimitry Andric   time_t ModificationTime;
47104eeddc0SDimitry Andric   std::unique_ptr<llvm::MemoryBuffer> Buffer;
47204eeddc0SDimitry Andric   uint32_t User;
47304eeddc0SDimitry Andric   uint32_t Group;
47404eeddc0SDimitry Andric   llvm::sys::fs::file_type Type;
47504eeddc0SDimitry Andric   llvm::sys::fs::perms Perms;
47604eeddc0SDimitry Andric 
47704eeddc0SDimitry Andric   Status makeStatus() const;
47804eeddc0SDimitry Andric };
4790b57cec5SDimitry Andric 
48081ad6265SDimitry Andric class NamedNodeOrError {
48181ad6265SDimitry Andric   ErrorOr<std::pair<llvm::SmallString<128>, const detail::InMemoryNode *>>
48281ad6265SDimitry Andric       Value;
48381ad6265SDimitry Andric 
48481ad6265SDimitry Andric public:
NamedNodeOrError(llvm::SmallString<128> Name,const detail::InMemoryNode * Node)48581ad6265SDimitry Andric   NamedNodeOrError(llvm::SmallString<128> Name,
48681ad6265SDimitry Andric                    const detail::InMemoryNode *Node)
48781ad6265SDimitry Andric       : Value(std::make_pair(Name, Node)) {}
NamedNodeOrError(std::error_code EC)48881ad6265SDimitry Andric   NamedNodeOrError(std::error_code EC) : Value(EC) {}
NamedNodeOrError(llvm::errc EC)48981ad6265SDimitry Andric   NamedNodeOrError(llvm::errc EC) : Value(EC) {}
49081ad6265SDimitry Andric 
getName()49181ad6265SDimitry Andric   StringRef getName() const { return (*Value).first; }
49281ad6265SDimitry Andric   explicit operator bool() const { return static_cast<bool>(Value); }
error_code()49381ad6265SDimitry Andric   operator std::error_code() const { return Value.getError(); }
getError()49481ad6265SDimitry Andric   std::error_code getError() const { return Value.getError(); }
49581ad6265SDimitry Andric   const detail::InMemoryNode *operator*() const { return (*Value).second; }
49681ad6265SDimitry Andric };
49781ad6265SDimitry Andric 
4980b57cec5SDimitry Andric } // namespace detail
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric /// An in-memory file system.
5010b57cec5SDimitry Andric class InMemoryFileSystem : public FileSystem {
5020b57cec5SDimitry Andric   std::unique_ptr<detail::InMemoryDirectory> Root;
5030b57cec5SDimitry Andric   std::string WorkingDirectory;
5040b57cec5SDimitry Andric   bool UseNormalizedPaths = true;
5050b57cec5SDimitry Andric 
50604eeddc0SDimitry Andric   using MakeNodeFn = llvm::function_ref<std::unique_ptr<detail::InMemoryNode>(
50704eeddc0SDimitry Andric       detail::NewInMemoryNodeInfo)>;
50804eeddc0SDimitry Andric 
50904eeddc0SDimitry Andric   /// Create node with \p MakeNode and add it into this filesystem at \p Path.
5100b57cec5SDimitry Andric   bool addFile(const Twine &Path, time_t ModificationTime,
5110b57cec5SDimitry Andric                std::unique_ptr<llvm::MemoryBuffer> Buffer,
512bdd1243dSDimitry Andric                std::optional<uint32_t> User, std::optional<uint32_t> Group,
513bdd1243dSDimitry Andric                std::optional<llvm::sys::fs::file_type> Type,
514bdd1243dSDimitry Andric                std::optional<llvm::sys::fs::perms> Perms, MakeNodeFn MakeNode);
5150b57cec5SDimitry Andric 
516bdd1243dSDimitry Andric   /// Looks up the in-memory node for the path \p P.
517bdd1243dSDimitry Andric   /// If \p FollowFinalSymlink is true, the returned node is guaranteed to
518bdd1243dSDimitry Andric   /// not be a symlink and its path may differ from \p P.
51981ad6265SDimitry Andric   detail::NamedNodeOrError lookupNode(const Twine &P, bool FollowFinalSymlink,
52081ad6265SDimitry Andric                                       size_t SymlinkDepth = 0) const;
52181ad6265SDimitry Andric 
52281ad6265SDimitry Andric   class DirIterator;
52381ad6265SDimitry Andric 
5240b57cec5SDimitry Andric public:
5250b57cec5SDimitry Andric   explicit InMemoryFileSystem(bool UseNormalizedPaths = true);
5260b57cec5SDimitry Andric   ~InMemoryFileSystem() override;
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric   /// Add a file containing a buffer or a directory to the VFS with a
5290b57cec5SDimitry Andric   /// path. The VFS owns the buffer.  If present, User, Group, Type
5300b57cec5SDimitry Andric   /// and Perms apply to the newly-created file or directory.
5310b57cec5SDimitry Andric   /// \return true if the file or directory was successfully added,
5320b57cec5SDimitry Andric   /// false if the file or directory already exists in the file system with
5330b57cec5SDimitry Andric   /// different contents.
5340b57cec5SDimitry Andric   bool addFile(const Twine &Path, time_t ModificationTime,
5350b57cec5SDimitry Andric                std::unique_ptr<llvm::MemoryBuffer> Buffer,
536bdd1243dSDimitry Andric                std::optional<uint32_t> User = std::nullopt,
537bdd1243dSDimitry Andric                std::optional<uint32_t> Group = std::nullopt,
538bdd1243dSDimitry Andric                std::optional<llvm::sys::fs::file_type> Type = std::nullopt,
539bdd1243dSDimitry Andric                std::optional<llvm::sys::fs::perms> Perms = std::nullopt);
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric   /// Add a hard link to a file.
54281ad6265SDimitry Andric   ///
5430b57cec5SDimitry Andric   /// Here hard links are not intended to be fully equivalent to the classical
5440b57cec5SDimitry Andric   /// filesystem. Both the hard link and the file share the same buffer and
5450b57cec5SDimitry Andric   /// status (and thus have the same UniqueID). Because of this there is no way
5460b57cec5SDimitry Andric   /// to distinguish between the link and the file after the link has been
5470b57cec5SDimitry Andric   /// added.
5480b57cec5SDimitry Andric   ///
549bdd1243dSDimitry Andric   /// The \p Target path must be an existing file or a hardlink. The
550bdd1243dSDimitry Andric   /// \p NewLink file must not have been added before. The \p Target
551bdd1243dSDimitry Andric   /// path must not be a directory. The \p NewLink node is added as a hard
552bdd1243dSDimitry Andric   /// link which points to the resolved file of \p Target node.
5530b57cec5SDimitry Andric   /// \return true if the above condition is satisfied and hardlink was
5540b57cec5SDimitry Andric   /// successfully created, false otherwise.
55581ad6265SDimitry Andric   bool addHardLink(const Twine &NewLink, const Twine &Target);
55681ad6265SDimitry Andric 
55781ad6265SDimitry Andric   /// Arbitrary max depth to search through symlinks. We can get into problems
55881ad6265SDimitry Andric   /// if a link links to a link that links back to the link, for example.
55981ad6265SDimitry Andric   static constexpr size_t MaxSymlinkDepth = 16;
56081ad6265SDimitry Andric 
561bdd1243dSDimitry Andric   /// Add a symbolic link. Unlike a HardLink, because \p Target doesn't need
56281ad6265SDimitry Andric   /// to refer to a file (or refer to anything, as it happens). Also, an
563bdd1243dSDimitry Andric   /// in-memory directory for \p Target isn't automatically created.
564bdd1243dSDimitry Andric   bool
565bdd1243dSDimitry Andric   addSymbolicLink(const Twine &NewLink, const Twine &Target,
566bdd1243dSDimitry Andric                   time_t ModificationTime,
567bdd1243dSDimitry Andric                   std::optional<uint32_t> User = std::nullopt,
568bdd1243dSDimitry Andric                   std::optional<uint32_t> Group = std::nullopt,
569bdd1243dSDimitry Andric                   std::optional<llvm::sys::fs::perms> Perms = std::nullopt);
5700b57cec5SDimitry Andric 
5710b57cec5SDimitry Andric   /// Add a buffer to the VFS with a path. The VFS does not own the buffer.
5720b57cec5SDimitry Andric   /// If present, User, Group, Type and Perms apply to the newly-created file
5730b57cec5SDimitry Andric   /// or directory.
5740b57cec5SDimitry Andric   /// \return true if the file or directory was successfully added,
5750b57cec5SDimitry Andric   /// false if the file or directory already exists in the file system with
5760b57cec5SDimitry Andric   /// different contents.
5770b57cec5SDimitry Andric   bool addFileNoOwn(const Twine &Path, time_t ModificationTime,
578e8d8bef9SDimitry Andric                     const llvm::MemoryBufferRef &Buffer,
579bdd1243dSDimitry Andric                     std::optional<uint32_t> User = std::nullopt,
580bdd1243dSDimitry Andric                     std::optional<uint32_t> Group = std::nullopt,
581bdd1243dSDimitry Andric                     std::optional<llvm::sys::fs::file_type> Type = std::nullopt,
582bdd1243dSDimitry Andric                     std::optional<llvm::sys::fs::perms> Perms = std::nullopt);
5830b57cec5SDimitry Andric 
5840b57cec5SDimitry Andric   std::string toString() const;
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric   /// Return true if this file system normalizes . and .. in paths.
useNormalizedPaths()5870b57cec5SDimitry Andric   bool useNormalizedPaths() const { return UseNormalizedPaths; }
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric   llvm::ErrorOr<Status> status(const Twine &Path) override;
5900b57cec5SDimitry Andric   llvm::ErrorOr<std::unique_ptr<File>>
5910b57cec5SDimitry Andric   openFileForRead(const Twine &Path) override;
5920b57cec5SDimitry Andric   directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
5930b57cec5SDimitry Andric 
getCurrentWorkingDirectory()5940b57cec5SDimitry Andric   llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
5950b57cec5SDimitry Andric     return WorkingDirectory;
5960b57cec5SDimitry Andric   }
5970b57cec5SDimitry Andric   /// Canonicalizes \p Path by combining with the current working
5980b57cec5SDimitry Andric   /// directory and normalizing the path (e.g. remove dots). If the current
5990b57cec5SDimitry Andric   /// working directory is not set, this returns errc::operation_not_permitted.
6000b57cec5SDimitry Andric   ///
6010b57cec5SDimitry Andric   /// This doesn't resolve symlinks as they are not supported in in-memory file
6020b57cec5SDimitry Andric   /// system.
6030b57cec5SDimitry Andric   std::error_code getRealPath(const Twine &Path,
6040b57cec5SDimitry Andric                               SmallVectorImpl<char> &Output) const override;
6050b57cec5SDimitry Andric   std::error_code isLocal(const Twine &Path, bool &Result) override;
6060b57cec5SDimitry Andric   std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
60781ad6265SDimitry Andric 
60881ad6265SDimitry Andric protected:
60981ad6265SDimitry Andric   void printImpl(raw_ostream &OS, PrintType Type,
61081ad6265SDimitry Andric                  unsigned IndentLevel) const override;
6110b57cec5SDimitry Andric };
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric /// Get a globally unique ID for a virtual file or directory.
6140b57cec5SDimitry Andric llvm::sys::fs::UniqueID getNextVirtualUniqueID();
6150b57cec5SDimitry Andric 
6160b57cec5SDimitry Andric /// Gets a \p FileSystem for a virtual file system described in YAML
6170b57cec5SDimitry Andric /// format.
618e8d8bef9SDimitry Andric std::unique_ptr<FileSystem>
6190b57cec5SDimitry Andric getVFSFromYAML(std::unique_ptr<llvm::MemoryBuffer> Buffer,
6200b57cec5SDimitry Andric                llvm::SourceMgr::DiagHandlerTy DiagHandler,
6210b57cec5SDimitry Andric                StringRef YAMLFilePath, void *DiagContext = nullptr,
6220b57cec5SDimitry Andric                IntrusiveRefCntPtr<FileSystem> ExternalFS = getRealFileSystem());
6230b57cec5SDimitry Andric 
6240b57cec5SDimitry Andric struct YAMLVFSEntry {
6250b57cec5SDimitry Andric   template <typename T1, typename T2>
6265ffd83dbSDimitry Andric   YAMLVFSEntry(T1 &&VPath, T2 &&RPath, bool IsDirectory = false)
VPathYAMLVFSEntry6275ffd83dbSDimitry Andric       : VPath(std::forward<T1>(VPath)), RPath(std::forward<T2>(RPath)),
6285ffd83dbSDimitry Andric         IsDirectory(IsDirectory) {}
6290b57cec5SDimitry Andric   std::string VPath;
6300b57cec5SDimitry Andric   std::string RPath;
6315ffd83dbSDimitry Andric   bool IsDirectory = false;
6320b57cec5SDimitry Andric };
6330b57cec5SDimitry Andric 
634fe6060f1SDimitry Andric class RedirectingFSDirIterImpl;
6350b57cec5SDimitry Andric class RedirectingFileSystemParser;
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric /// A virtual file system parsed from a YAML file.
6380b57cec5SDimitry Andric ///
639fe6060f1SDimitry Andric /// Currently, this class allows creating virtual files and directories. Virtual
640fe6060f1SDimitry Andric /// files map to existing external files in \c ExternalFS, and virtual
641fe6060f1SDimitry Andric /// directories may either map to existing directories in \c ExternalFS or list
642fe6060f1SDimitry Andric /// their contents in the form of other virtual directories and/or files.
6430b57cec5SDimitry Andric ///
6440b57cec5SDimitry Andric /// The basic structure of the parsed file is:
6450b57cec5SDimitry Andric /// \verbatim
6460b57cec5SDimitry Andric /// {
6470b57cec5SDimitry Andric ///   'version': <version number>,
6480b57cec5SDimitry Andric ///   <optional configuration>
6490b57cec5SDimitry Andric ///   'roots': [
6500b57cec5SDimitry Andric ///              <directory entries>
6510b57cec5SDimitry Andric ///            ]
6520b57cec5SDimitry Andric /// }
6530b57cec5SDimitry Andric /// \endverbatim
6540b57cec5SDimitry Andric ///
65504eeddc0SDimitry Andric /// The roots may be absolute or relative. If relative they will be made
656bdd1243dSDimitry Andric /// absolute against either current working directory or the directory where
657bdd1243dSDimitry Andric /// the Overlay YAML file is located, depending on the 'root-relative'
658bdd1243dSDimitry Andric /// configuration.
65904eeddc0SDimitry Andric ///
6600b57cec5SDimitry Andric /// All configuration options are optional.
661480093f4SDimitry Andric ///   'case-sensitive': <boolean, default=(true for Posix, false for Windows)>
6620b57cec5SDimitry Andric ///   'use-external-names': <boolean, default=true>
663bdd1243dSDimitry Andric ///   'root-relative': <string, one of 'cwd' or 'overlay-dir', default='cwd'>
6640b57cec5SDimitry Andric ///   'overlay-relative': <boolean, default=false>
66581ad6265SDimitry Andric ///   'fallthrough': <boolean, default=true, deprecated - use 'redirecting-with'
66681ad6265SDimitry Andric ///                   instead>
66781ad6265SDimitry Andric ///   'redirecting-with': <string, one of 'fallthrough', 'fallback', or
66881ad6265SDimitry Andric ///                        'redirect-only', default='fallthrough'>
6690b57cec5SDimitry Andric ///
670bdd1243dSDimitry Andric /// To clarify, 'root-relative' option will prepend the current working
671bdd1243dSDimitry Andric /// directory, or the overlay directory to the 'roots->name' field only if
672bdd1243dSDimitry Andric /// 'roots->name' is a relative path. On the other hand, when 'overlay-relative'
673bdd1243dSDimitry Andric /// is set to 'true', external paths will always be prepended with the overlay
674bdd1243dSDimitry Andric /// directory, even if external paths are not relative paths. The
675bdd1243dSDimitry Andric /// 'root-relative' option has no interaction with the 'overlay-relative'
676bdd1243dSDimitry Andric /// option.
677bdd1243dSDimitry Andric ///
678fe6060f1SDimitry Andric /// Virtual directories that list their contents are represented as
6790b57cec5SDimitry Andric /// \verbatim
6800b57cec5SDimitry Andric /// {
6810b57cec5SDimitry Andric ///   'type': 'directory',
6820b57cec5SDimitry Andric ///   'name': <string>,
6830b57cec5SDimitry Andric ///   'contents': [ <file or directory entries> ]
6840b57cec5SDimitry Andric /// }
6850b57cec5SDimitry Andric /// \endverbatim
6860b57cec5SDimitry Andric ///
687fe6060f1SDimitry Andric /// The default attributes for such virtual directories are:
6880b57cec5SDimitry Andric /// \verbatim
6890b57cec5SDimitry Andric /// MTime = now() when created
6900b57cec5SDimitry Andric /// Perms = 0777
6910b57cec5SDimitry Andric /// User = Group = 0
6920b57cec5SDimitry Andric /// Size = 0
6930b57cec5SDimitry Andric /// UniqueID = unspecified unique value
6940b57cec5SDimitry Andric /// \endverbatim
6950b57cec5SDimitry Andric ///
696fe6060f1SDimitry Andric /// When a path prefix matches such a directory, the next component in the path
697fe6060f1SDimitry Andric /// is matched against the entries in the 'contents' array.
698fe6060f1SDimitry Andric ///
699fe6060f1SDimitry Andric /// Re-mapped directories, on the other hand, are represented as
700fe6060f1SDimitry Andric /// /// \verbatim
701fe6060f1SDimitry Andric /// {
702fe6060f1SDimitry Andric ///   'type': 'directory-remap',
703fe6060f1SDimitry Andric ///   'name': <string>,
704fe6060f1SDimitry Andric ///   'use-external-name': <boolean>, # Optional
705fe6060f1SDimitry Andric ///   'external-contents': <path to external directory>
706fe6060f1SDimitry Andric /// }
707fe6060f1SDimitry Andric /// \endverbatim
708fe6060f1SDimitry Andric ///
709fe6060f1SDimitry Andric /// and inherit their attributes from the external directory. When a path
710fe6060f1SDimitry Andric /// prefix matches such an entry, the unmatched components are appended to the
711fe6060f1SDimitry Andric /// 'external-contents' path, and the resulting path is looked up in the
712fe6060f1SDimitry Andric /// external file system instead.
713fe6060f1SDimitry Andric ///
7140b57cec5SDimitry Andric /// Re-mapped files are represented as
7150b57cec5SDimitry Andric /// \verbatim
7160b57cec5SDimitry Andric /// {
7170b57cec5SDimitry Andric ///   'type': 'file',
7180b57cec5SDimitry Andric ///   'name': <string>,
719fe6060f1SDimitry Andric ///   'use-external-name': <boolean>, # Optional
7200b57cec5SDimitry Andric ///   'external-contents': <path to external file>
7210b57cec5SDimitry Andric /// }
7220b57cec5SDimitry Andric /// \endverbatim
7230b57cec5SDimitry Andric ///
724fe6060f1SDimitry Andric /// Their attributes and file contents are determined by looking up the file at
725fe6060f1SDimitry Andric /// their 'external-contents' path in the external file system.
7260b57cec5SDimitry Andric ///
727fe6060f1SDimitry Andric /// For 'file', 'directory' and 'directory-remap' entries the 'name' field may
728fe6060f1SDimitry Andric /// contain multiple path components (e.g. /path/to/file). However, any
729fe6060f1SDimitry Andric /// directory in such a path that contains more than one child must be uniquely
730fe6060f1SDimitry Andric /// represented by a 'directory' entry.
731349cc55cSDimitry Andric ///
732349cc55cSDimitry Andric /// When the 'use-external-name' field is set, calls to \a vfs::File::status()
733349cc55cSDimitry Andric /// give the external (remapped) filesystem name instead of the name the file
734349cc55cSDimitry Andric /// was accessed by. This is an intentional leak through the \a
735349cc55cSDimitry Andric /// RedirectingFileSystem abstraction layer. It enables clients to discover
736349cc55cSDimitry Andric /// (and use) the external file location when communicating with users or tools
737349cc55cSDimitry Andric /// that don't use the same VFS overlay.
738349cc55cSDimitry Andric ///
739349cc55cSDimitry Andric /// FIXME: 'use-external-name' causes behaviour that's inconsistent with how
740349cc55cSDimitry Andric /// "real" filesystems behave. Maybe there should be a separate channel for
741349cc55cSDimitry Andric /// this information.
7420b57cec5SDimitry Andric class RedirectingFileSystem : public vfs::FileSystem {
7430b57cec5SDimitry Andric public:
744fe6060f1SDimitry Andric   enum EntryKind { EK_Directory, EK_DirectoryRemap, EK_File };
745fe6060f1SDimitry Andric   enum NameKind { NK_NotSet, NK_External, NK_Virtual };
7460b57cec5SDimitry Andric 
74781ad6265SDimitry Andric   /// The type of redirection to perform.
74881ad6265SDimitry Andric   enum class RedirectKind {
74981ad6265SDimitry Andric     /// Lookup the redirected path first (ie. the one specified in
75081ad6265SDimitry Andric     /// 'external-contents') and if that fails "fallthrough" to a lookup of the
75181ad6265SDimitry Andric     /// originally provided path.
75281ad6265SDimitry Andric     Fallthrough,
75381ad6265SDimitry Andric     /// Lookup the provided path first and if that fails, "fallback" to a
75481ad6265SDimitry Andric     /// lookup of the redirected path.
75581ad6265SDimitry Andric     Fallback,
75681ad6265SDimitry Andric     /// Only lookup the redirected path, do not lookup the originally provided
75781ad6265SDimitry Andric     /// path.
75881ad6265SDimitry Andric     RedirectOnly
75981ad6265SDimitry Andric   };
76081ad6265SDimitry Andric 
761bdd1243dSDimitry Andric   /// The type of relative path used by Roots.
762bdd1243dSDimitry Andric   enum class RootRelativeKind {
763bdd1243dSDimitry Andric     /// The roots are relative to the current working directory.
764bdd1243dSDimitry Andric     CWD,
765bdd1243dSDimitry Andric     /// The roots are relative to the directory where the Overlay YAML file
766bdd1243dSDimitry Andric     // locates.
767bdd1243dSDimitry Andric     OverlayDir
768bdd1243dSDimitry Andric   };
769bdd1243dSDimitry Andric 
7700b57cec5SDimitry Andric   /// A single file or directory in the VFS.
7710b57cec5SDimitry Andric   class Entry {
7720b57cec5SDimitry Andric     EntryKind Kind;
7730b57cec5SDimitry Andric     std::string Name;
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric   public:
Entry(EntryKind K,StringRef Name)7760b57cec5SDimitry Andric     Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
7770b57cec5SDimitry Andric     virtual ~Entry() = default;
7780b57cec5SDimitry Andric 
getName()7790b57cec5SDimitry Andric     StringRef getName() const { return Name; }
getKind()7800b57cec5SDimitry Andric     EntryKind getKind() const { return Kind; }
7810b57cec5SDimitry Andric   };
7820b57cec5SDimitry Andric 
783fe6060f1SDimitry Andric   /// A directory in the vfs with explicitly specified contents.
784fe6060f1SDimitry Andric   class DirectoryEntry : public Entry {
7850b57cec5SDimitry Andric     std::vector<std::unique_ptr<Entry>> Contents;
7860b57cec5SDimitry Andric     Status S;
7870b57cec5SDimitry Andric 
7880b57cec5SDimitry Andric   public:
789fe6060f1SDimitry Andric     /// Constructs a directory entry with explicitly specified contents.
DirectoryEntry(StringRef Name,std::vector<std::unique_ptr<Entry>> Contents,Status S)790fe6060f1SDimitry Andric     DirectoryEntry(StringRef Name, std::vector<std::unique_ptr<Entry>> Contents,
7910b57cec5SDimitry Andric                    Status S)
7920b57cec5SDimitry Andric         : Entry(EK_Directory, Name), Contents(std::move(Contents)),
7930b57cec5SDimitry Andric           S(std::move(S)) {}
794fe6060f1SDimitry Andric 
795fe6060f1SDimitry Andric     /// Constructs an empty directory entry.
DirectoryEntry(StringRef Name,Status S)796fe6060f1SDimitry Andric     DirectoryEntry(StringRef Name, Status S)
7970b57cec5SDimitry Andric         : Entry(EK_Directory, Name), S(std::move(S)) {}
7980b57cec5SDimitry Andric 
getStatus()7990b57cec5SDimitry Andric     Status getStatus() { return S; }
8000b57cec5SDimitry Andric 
addContent(std::unique_ptr<Entry> Content)8010b57cec5SDimitry Andric     void addContent(std::unique_ptr<Entry> Content) {
8020b57cec5SDimitry Andric       Contents.push_back(std::move(Content));
8030b57cec5SDimitry Andric     }
8040b57cec5SDimitry Andric 
getLastContent()8050b57cec5SDimitry Andric     Entry *getLastContent() const { return Contents.back().get(); }
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric     using iterator = decltype(Contents)::iterator;
8080b57cec5SDimitry Andric 
contents_begin()8090b57cec5SDimitry Andric     iterator contents_begin() { return Contents.begin(); }
contents_end()8100b57cec5SDimitry Andric     iterator contents_end() { return Contents.end(); }
8110b57cec5SDimitry Andric 
classof(const Entry * E)8120b57cec5SDimitry Andric     static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
8130b57cec5SDimitry Andric   };
8140b57cec5SDimitry Andric 
815fe6060f1SDimitry Andric   /// A file or directory in the vfs that is mapped to a file or directory in
816fe6060f1SDimitry Andric   /// the external filesystem.
817fe6060f1SDimitry Andric   class RemapEntry : public Entry {
8180b57cec5SDimitry Andric     std::string ExternalContentsPath;
8190b57cec5SDimitry Andric     NameKind UseName;
8200b57cec5SDimitry Andric 
821fe6060f1SDimitry Andric   protected:
RemapEntry(EntryKind K,StringRef Name,StringRef ExternalContentsPath,NameKind UseName)822fe6060f1SDimitry Andric     RemapEntry(EntryKind K, StringRef Name, StringRef ExternalContentsPath,
8230b57cec5SDimitry Andric                NameKind UseName)
824fe6060f1SDimitry Andric         : Entry(K, Name), ExternalContentsPath(ExternalContentsPath),
8250b57cec5SDimitry Andric           UseName(UseName) {}
8260b57cec5SDimitry Andric 
827fe6060f1SDimitry Andric   public:
getExternalContentsPath()8280b57cec5SDimitry Andric     StringRef getExternalContentsPath() const { return ExternalContentsPath; }
8290b57cec5SDimitry Andric 
830fe6060f1SDimitry Andric     /// Whether to use the external path as the name for this file or directory.
useExternalName(bool GlobalUseExternalName)8310b57cec5SDimitry Andric     bool useExternalName(bool GlobalUseExternalName) const {
8320b57cec5SDimitry Andric       return UseName == NK_NotSet ? GlobalUseExternalName
8330b57cec5SDimitry Andric                                   : (UseName == NK_External);
8340b57cec5SDimitry Andric     }
8350b57cec5SDimitry Andric 
getUseName()8360b57cec5SDimitry Andric     NameKind getUseName() const { return UseName; }
8370b57cec5SDimitry Andric 
classof(const Entry * E)838fe6060f1SDimitry Andric     static bool classof(const Entry *E) {
839fe6060f1SDimitry Andric       switch (E->getKind()) {
840fe6060f1SDimitry Andric       case EK_DirectoryRemap:
841bdd1243dSDimitry Andric         [[fallthrough]];
842fe6060f1SDimitry Andric       case EK_File:
843fe6060f1SDimitry Andric         return true;
844fe6060f1SDimitry Andric       case EK_Directory:
845fe6060f1SDimitry Andric         return false;
846fe6060f1SDimitry Andric       }
847fe6060f1SDimitry Andric       llvm_unreachable("invalid entry kind");
848fe6060f1SDimitry Andric     }
849fe6060f1SDimitry Andric   };
850fe6060f1SDimitry Andric 
851fe6060f1SDimitry Andric   /// A directory in the vfs that maps to a directory in the external file
852fe6060f1SDimitry Andric   /// system.
853fe6060f1SDimitry Andric   class DirectoryRemapEntry : public RemapEntry {
854fe6060f1SDimitry Andric   public:
DirectoryRemapEntry(StringRef Name,StringRef ExternalContentsPath,NameKind UseName)855fe6060f1SDimitry Andric     DirectoryRemapEntry(StringRef Name, StringRef ExternalContentsPath,
856fe6060f1SDimitry Andric                         NameKind UseName)
857fe6060f1SDimitry Andric         : RemapEntry(EK_DirectoryRemap, Name, ExternalContentsPath, UseName) {}
858fe6060f1SDimitry Andric 
classof(const Entry * E)859fe6060f1SDimitry Andric     static bool classof(const Entry *E) {
860fe6060f1SDimitry Andric       return E->getKind() == EK_DirectoryRemap;
861fe6060f1SDimitry Andric     }
862fe6060f1SDimitry Andric   };
863fe6060f1SDimitry Andric 
864fe6060f1SDimitry Andric   /// A file in the vfs that maps to a file in the external file system.
865fe6060f1SDimitry Andric   class FileEntry : public RemapEntry {
866fe6060f1SDimitry Andric   public:
FileEntry(StringRef Name,StringRef ExternalContentsPath,NameKind UseName)867fe6060f1SDimitry Andric     FileEntry(StringRef Name, StringRef ExternalContentsPath, NameKind UseName)
868fe6060f1SDimitry Andric         : RemapEntry(EK_File, Name, ExternalContentsPath, UseName) {}
869fe6060f1SDimitry Andric 
classof(const Entry * E)8700b57cec5SDimitry Andric     static bool classof(const Entry *E) { return E->getKind() == EK_File; }
8710b57cec5SDimitry Andric   };
8720b57cec5SDimitry Andric 
873fe6060f1SDimitry Andric   /// Represents the result of a path lookup into the RedirectingFileSystem.
874fe6060f1SDimitry Andric   struct LookupResult {
87506c3fb27SDimitry Andric     /// Chain of parent directory entries for \c E.
87606c3fb27SDimitry Andric     llvm::SmallVector<Entry *, 32> Parents;
87706c3fb27SDimitry Andric 
878fe6060f1SDimitry Andric     /// The entry the looked-up path corresponds to.
879fe6060f1SDimitry Andric     Entry *E;
880fe6060f1SDimitry Andric 
8810b57cec5SDimitry Andric   private:
882fe6060f1SDimitry Andric     /// When the found Entry is a DirectoryRemapEntry, stores the path in the
883fe6060f1SDimitry Andric     /// external file system that the looked-up path in the virtual file system
884fe6060f1SDimitry Andric     //  corresponds to.
885bdd1243dSDimitry Andric     std::optional<std::string> ExternalRedirect;
886fe6060f1SDimitry Andric 
887fe6060f1SDimitry Andric   public:
888fe6060f1SDimitry Andric     LookupResult(Entry *E, sys::path::const_iterator Start,
889fe6060f1SDimitry Andric                  sys::path::const_iterator End);
890fe6060f1SDimitry Andric 
8915f757f3fSDimitry Andric     /// If the found Entry maps the input path to a path in the external
892fe6060f1SDimitry Andric     /// file system (i.e. it is a FileEntry or DirectoryRemapEntry), returns
893fe6060f1SDimitry Andric     /// that path.
getExternalRedirectLookupResult894bdd1243dSDimitry Andric     std::optional<StringRef> getExternalRedirect() const {
895fe6060f1SDimitry Andric       if (isa<DirectoryRemapEntry>(E))
896fe6060f1SDimitry Andric         return StringRef(*ExternalRedirect);
897fe6060f1SDimitry Andric       if (auto *FE = dyn_cast<FileEntry>(E))
898fe6060f1SDimitry Andric         return FE->getExternalContentsPath();
899bdd1243dSDimitry Andric       return std::nullopt;
900fe6060f1SDimitry Andric     }
90106c3fb27SDimitry Andric 
90206c3fb27SDimitry Andric     /// Get the (canonical) path of the found entry. This uses the as-written
90306c3fb27SDimitry Andric     /// path components from the VFS specification.
90406c3fb27SDimitry Andric     void getPath(llvm::SmallVectorImpl<char> &Path) const;
905fe6060f1SDimitry Andric   };
906fe6060f1SDimitry Andric 
907fe6060f1SDimitry Andric private:
908fe6060f1SDimitry Andric   friend class RedirectingFSDirIterImpl;
9090b57cec5SDimitry Andric   friend class RedirectingFileSystemParser;
9100b57cec5SDimitry Andric 
911e8d8bef9SDimitry Andric   /// Canonicalize path by removing ".", "..", "./", components. This is
912e8d8bef9SDimitry Andric   /// a VFS request, do not bother about symlinks in the path components
913e8d8bef9SDimitry Andric   /// but canonicalize in order to perform the correct entry search.
914e8d8bef9SDimitry Andric   std::error_code makeCanonical(SmallVectorImpl<char> &Path) const;
9158bcb0991SDimitry Andric 
916349cc55cSDimitry Andric   /// Get the File status, or error, from the underlying external file system.
917349cc55cSDimitry Andric   /// This returns the status with the originally requested name, while looking
918349cc55cSDimitry Andric   /// up the entry using the canonical path.
919349cc55cSDimitry Andric   ErrorOr<Status> getExternalStatus(const Twine &CanonicalPath,
920349cc55cSDimitry Andric                                     const Twine &OriginalPath) const;
921349cc55cSDimitry Andric 
922bdd1243dSDimitry Andric   /// Make \a Path an absolute path.
923bdd1243dSDimitry Andric   ///
924bdd1243dSDimitry Andric   /// Makes \a Path absolute using the \a WorkingDir if it is not already.
925bdd1243dSDimitry Andric   ///
926bdd1243dSDimitry Andric   /// /absolute/path   => /absolute/path
927bdd1243dSDimitry Andric   /// relative/../path => <WorkingDir>/relative/../path
928bdd1243dSDimitry Andric   ///
929bdd1243dSDimitry Andric   /// \param WorkingDir  A path that will be used as the base Dir if \a Path
930bdd1243dSDimitry Andric   ///                    is not already absolute.
931bdd1243dSDimitry Andric   /// \param Path A path that is modified to be an absolute path.
932bdd1243dSDimitry Andric   /// \returns success if \a path has been made absolute, otherwise a
933bdd1243dSDimitry Andric   ///          platform-specific error_code.
934bdd1243dSDimitry Andric   std::error_code makeAbsolute(StringRef WorkingDir,
935bdd1243dSDimitry Andric                                SmallVectorImpl<char> &Path) const;
936bdd1243dSDimitry Andric 
937480093f4SDimitry Andric   // In a RedirectingFileSystem, keys can be specified in Posix or Windows
938480093f4SDimitry Andric   // style (or even a mixture of both), so this comparison helper allows
939480093f4SDimitry Andric   // slashes (representing a root) to match backslashes (and vice versa).  Note
9405ffd83dbSDimitry Andric   // that, other than the root, path components should not contain slashes or
941480093f4SDimitry Andric   // backslashes.
pathComponentMatches(llvm::StringRef lhs,llvm::StringRef rhs)942480093f4SDimitry Andric   bool pathComponentMatches(llvm::StringRef lhs, llvm::StringRef rhs) const {
943fe6060f1SDimitry Andric     if ((CaseSensitive ? lhs.equals(rhs) : lhs.equals_insensitive(rhs)))
944480093f4SDimitry Andric       return true;
945480093f4SDimitry Andric     return (lhs == "/" && rhs == "\\") || (lhs == "\\" && rhs == "/");
946480093f4SDimitry Andric   }
947480093f4SDimitry Andric 
9480b57cec5SDimitry Andric   /// The root(s) of the virtual file system.
9490b57cec5SDimitry Andric   std::vector<std::unique_ptr<Entry>> Roots;
9500b57cec5SDimitry Andric 
9518bcb0991SDimitry Andric   /// The current working directory of the file system.
9528bcb0991SDimitry Andric   std::string WorkingDirectory;
9538bcb0991SDimitry Andric 
9540b57cec5SDimitry Andric   /// The file system to use for external references.
9550b57cec5SDimitry Andric   IntrusiveRefCntPtr<FileSystem> ExternalFS;
9560b57cec5SDimitry Andric 
957bdd1243dSDimitry Andric   /// This represents the directory path that the YAML file is located.
958bdd1243dSDimitry Andric   /// This will be prefixed to each 'external-contents' if IsRelativeOverlay
959bdd1243dSDimitry Andric   /// is set. This will also be prefixed to each 'roots->name' if RootRelative
960bdd1243dSDimitry Andric   /// is set to RootRelativeKind::OverlayDir and the path is relative.
961bdd1243dSDimitry Andric   std::string OverlayFileDir;
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric   /// @name Configuration
9640b57cec5SDimitry Andric   /// @{
9650b57cec5SDimitry Andric 
9660b57cec5SDimitry Andric   /// Whether to perform case-sensitive comparisons.
9670b57cec5SDimitry Andric   ///
9680b57cec5SDimitry Andric   /// Currently, case-insensitive matching only works correctly with ASCII.
969349cc55cSDimitry Andric   bool CaseSensitive = is_style_posix(sys::path::Style::native);
9700b57cec5SDimitry Andric 
971bdd1243dSDimitry Andric   /// IsRelativeOverlay marks whether a OverlayFileDir path must
9720b57cec5SDimitry Andric   /// be prefixed in every 'external-contents' when reading from YAML files.
9730b57cec5SDimitry Andric   bool IsRelativeOverlay = false;
9740b57cec5SDimitry Andric 
9750b57cec5SDimitry Andric   /// Whether to use to use the value of 'external-contents' for the
9760b57cec5SDimitry Andric   /// names of files.  This global value is overridable on a per-file basis.
9770b57cec5SDimitry Andric   bool UseExternalNames = true;
9780b57cec5SDimitry Andric 
97981ad6265SDimitry Andric   /// Determines the lookups to perform, as well as their order. See
98081ad6265SDimitry Andric   /// \c RedirectKind for details.
98181ad6265SDimitry Andric   RedirectKind Redirection = RedirectKind::Fallthrough;
982bdd1243dSDimitry Andric 
983bdd1243dSDimitry Andric   /// Determine the prefix directory if the roots are relative paths. See
984bdd1243dSDimitry Andric   /// \c RootRelativeKind for details.
985bdd1243dSDimitry Andric   RootRelativeKind RootRelative = RootRelativeKind::CWD;
9860b57cec5SDimitry Andric   /// @}
9870b57cec5SDimitry Andric 
9888bcb0991SDimitry Andric   RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS);
9890b57cec5SDimitry Andric 
990fe6060f1SDimitry Andric   /// Looks up the path <tt>[Start, End)</tt> in \p From, possibly recursing
991fe6060f1SDimitry Andric   /// into the contents of \p From if it is a directory. Returns a LookupResult
992fe6060f1SDimitry Andric   /// giving the matched entry and, if that entry is a FileEntry or
993fe6060f1SDimitry Andric   /// DirectoryRemapEntry, the path it redirects to in the external file system.
99406c3fb27SDimitry Andric   ErrorOr<LookupResult>
99506c3fb27SDimitry Andric   lookupPathImpl(llvm::sys::path::const_iterator Start,
99606c3fb27SDimitry Andric                  llvm::sys::path::const_iterator End, Entry *From,
99706c3fb27SDimitry Andric                  llvm::SmallVectorImpl<Entry *> &Entries) const;
9980b57cec5SDimitry Andric 
999fe6060f1SDimitry Andric   /// Get the status for a path with the provided \c LookupResult.
1000349cc55cSDimitry Andric   ErrorOr<Status> status(const Twine &CanonicalPath, const Twine &OriginalPath,
1001349cc55cSDimitry Andric                          const LookupResult &Result);
10020b57cec5SDimitry Andric 
10030b57cec5SDimitry Andric public:
1004fe6060f1SDimitry Andric   /// Looks up \p Path in \c Roots and returns a LookupResult giving the
1005fe6060f1SDimitry Andric   /// matched entry and, if the entry was a FileEntry or DirectoryRemapEntry,
1006fe6060f1SDimitry Andric   /// the path it redirects to in the external file system.
1007fe6060f1SDimitry Andric   ErrorOr<LookupResult> lookupPath(StringRef Path) const;
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric   /// Parses \p Buffer, which is expected to be in YAML format and
10100b57cec5SDimitry Andric   /// returns a virtual file system representing its contents.
1011e8d8bef9SDimitry Andric   static std::unique_ptr<RedirectingFileSystem>
10120b57cec5SDimitry Andric   create(std::unique_ptr<MemoryBuffer> Buffer,
10130b57cec5SDimitry Andric          SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
10140b57cec5SDimitry Andric          void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
10150b57cec5SDimitry Andric 
1016e8d8bef9SDimitry Andric   /// Redirect each of the remapped files from first to second.
1017e8d8bef9SDimitry Andric   static std::unique_ptr<RedirectingFileSystem>
1018e8d8bef9SDimitry Andric   create(ArrayRef<std::pair<std::string, std::string>> RemappedFiles,
1019e8d8bef9SDimitry Andric          bool UseExternalNames, FileSystem &ExternalFS);
1020e8d8bef9SDimitry Andric 
10210b57cec5SDimitry Andric   ErrorOr<Status> status(const Twine &Path) override;
10220b57cec5SDimitry Andric   ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric   std::error_code getRealPath(const Twine &Path,
10250b57cec5SDimitry Andric                               SmallVectorImpl<char> &Output) const override;
10260b57cec5SDimitry Andric 
10270b57cec5SDimitry Andric   llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric   std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
10300b57cec5SDimitry Andric 
10310b57cec5SDimitry Andric   std::error_code isLocal(const Twine &Path, bool &Result) override;
10320b57cec5SDimitry Andric 
1033480093f4SDimitry Andric   std::error_code makeAbsolute(SmallVectorImpl<char> &Path) const override;
1034480093f4SDimitry Andric 
10350b57cec5SDimitry Andric   directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
10360b57cec5SDimitry Andric 
1037bdd1243dSDimitry Andric   void setOverlayFileDir(StringRef PrefixDir);
10380b57cec5SDimitry Andric 
1039bdd1243dSDimitry Andric   StringRef getOverlayFileDir() const;
10400b57cec5SDimitry Andric 
104181ad6265SDimitry Andric   /// Sets the redirection kind to \c Fallthrough if true or \c RedirectOnly
104281ad6265SDimitry Andric   /// otherwise. Will removed in the future, use \c setRedirection instead.
1043e8d8bef9SDimitry Andric   void setFallthrough(bool Fallthrough);
1044e8d8bef9SDimitry Andric 
104581ad6265SDimitry Andric   void setRedirection(RedirectingFileSystem::RedirectKind Kind);
104681ad6265SDimitry Andric 
1047e8d8bef9SDimitry Andric   std::vector<llvm::StringRef> getRoots() const;
1048e8d8bef9SDimitry Andric 
104981ad6265SDimitry Andric   void printEntry(raw_ostream &OS, Entry *E, unsigned IndentLevel = 0) const;
105081ad6265SDimitry Andric 
105181ad6265SDimitry Andric protected:
105281ad6265SDimitry Andric   void printImpl(raw_ostream &OS, PrintType Type,
105381ad6265SDimitry Andric                  unsigned IndentLevel) const override;
10540b57cec5SDimitry Andric };
10550b57cec5SDimitry Andric 
10560b57cec5SDimitry Andric /// Collect all pairs of <virtual path, real path> entries from the
10570b57cec5SDimitry Andric /// \p YAMLFilePath. This is used by the module dependency collector to forward
10580b57cec5SDimitry Andric /// the entries into the reproducer output VFS YAML file.
10590b57cec5SDimitry Andric void collectVFSFromYAML(
10600b57cec5SDimitry Andric     std::unique_ptr<llvm::MemoryBuffer> Buffer,
10610b57cec5SDimitry Andric     llvm::SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
10620b57cec5SDimitry Andric     SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
10630b57cec5SDimitry Andric     void *DiagContext = nullptr,
10640b57cec5SDimitry Andric     IntrusiveRefCntPtr<FileSystem> ExternalFS = getRealFileSystem());
10650b57cec5SDimitry Andric 
10660b57cec5SDimitry Andric class YAMLVFSWriter {
10670b57cec5SDimitry Andric   std::vector<YAMLVFSEntry> Mappings;
1068bdd1243dSDimitry Andric   std::optional<bool> IsCaseSensitive;
1069bdd1243dSDimitry Andric   std::optional<bool> IsOverlayRelative;
1070bdd1243dSDimitry Andric   std::optional<bool> UseExternalNames;
10710b57cec5SDimitry Andric   std::string OverlayDir;
10720b57cec5SDimitry Andric 
10735ffd83dbSDimitry Andric   void addEntry(StringRef VirtualPath, StringRef RealPath, bool IsDirectory);
10745ffd83dbSDimitry Andric 
10750b57cec5SDimitry Andric public:
10760b57cec5SDimitry Andric   YAMLVFSWriter() = default;
10770b57cec5SDimitry Andric 
10780b57cec5SDimitry Andric   void addFileMapping(StringRef VirtualPath, StringRef RealPath);
10795ffd83dbSDimitry Andric   void addDirectoryMapping(StringRef VirtualPath, StringRef RealPath);
10800b57cec5SDimitry Andric 
setCaseSensitivity(bool CaseSensitive)10810b57cec5SDimitry Andric   void setCaseSensitivity(bool CaseSensitive) {
10820b57cec5SDimitry Andric     IsCaseSensitive = CaseSensitive;
10830b57cec5SDimitry Andric   }
10840b57cec5SDimitry Andric 
setUseExternalNames(bool UseExtNames)10850b57cec5SDimitry Andric   void setUseExternalNames(bool UseExtNames) { UseExternalNames = UseExtNames; }
10860b57cec5SDimitry Andric 
setOverlayDir(StringRef OverlayDirectory)10870b57cec5SDimitry Andric   void setOverlayDir(StringRef OverlayDirectory) {
10880b57cec5SDimitry Andric     IsOverlayRelative = true;
10890b57cec5SDimitry Andric     OverlayDir.assign(OverlayDirectory.str());
10900b57cec5SDimitry Andric   }
10910b57cec5SDimitry Andric 
getMappings()10920b57cec5SDimitry Andric   const std::vector<YAMLVFSEntry> &getMappings() const { return Mappings; }
10930b57cec5SDimitry Andric 
10940b57cec5SDimitry Andric   void write(llvm::raw_ostream &OS);
10950b57cec5SDimitry Andric };
10960b57cec5SDimitry Andric 
10970b57cec5SDimitry Andric } // namespace vfs
10980b57cec5SDimitry Andric } // namespace llvm
10990b57cec5SDimitry Andric 
11000b57cec5SDimitry Andric #endif // LLVM_SUPPORT_VIRTUALFILESYSTEM_H
1101