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/None.h"
190b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
210b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
2204eeddc0SDimitry Andric #include "llvm/ADT/STLFunctionalExtras.h"
230b57cec5SDimitry Andric #include "llvm/Support/Chrono.h"
240b57cec5SDimitry Andric #include "llvm/Support/ErrorOr.h"
250b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
260b57cec5SDimitry Andric #include "llvm/Support/Path.h"
270b57cec5SDimitry Andric #include "llvm/Support/SourceMgr.h"
280b57cec5SDimitry Andric #include <cassert>
290b57cec5SDimitry Andric #include <cstdint>
300b57cec5SDimitry Andric #include <ctime>
310b57cec5SDimitry Andric #include <memory>
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 
610b57cec5SDimitry Andric   Status() = default;
620b57cec5SDimitry Andric   Status(const llvm::sys::fs::file_status &Status);
630b57cec5SDimitry Andric   Status(const Twine &Name, llvm::sys::fs::UniqueID UID,
640b57cec5SDimitry Andric          llvm::sys::TimePoint<> MTime, uint32_t User, uint32_t Group,
650b57cec5SDimitry Andric          uint64_t Size, llvm::sys::fs::file_type Type,
660b57cec5SDimitry Andric          llvm::sys::fs::perms Perms);
670b57cec5SDimitry Andric 
680eae32dcSDimitry Andric   /// Get a copy of a Status with a different size.
690eae32dcSDimitry Andric   static Status copyWithNewSize(const Status &In, uint64_t NewSize);
700b57cec5SDimitry Andric   /// Get a copy of a Status with a different name.
710b57cec5SDimitry Andric   static Status copyWithNewName(const Status &In, const Twine &NewName);
720b57cec5SDimitry Andric   static Status copyWithNewName(const llvm::sys::fs::file_status &In,
730b57cec5SDimitry Andric                                 const Twine &NewName);
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric   /// Returns the name that should be used for this file or directory.
760b57cec5SDimitry Andric   StringRef getName() const { return Name; }
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric   /// @name Status interface from llvm::sys::fs
790b57cec5SDimitry Andric   /// @{
800b57cec5SDimitry Andric   llvm::sys::fs::file_type getType() const { return Type; }
810b57cec5SDimitry Andric   llvm::sys::fs::perms getPermissions() const { return Perms; }
820b57cec5SDimitry Andric   llvm::sys::TimePoint<> getLastModificationTime() const { return MTime; }
830b57cec5SDimitry Andric   llvm::sys::fs::UniqueID getUniqueID() const { return UID; }
840b57cec5SDimitry Andric   uint32_t getUser() const { return User; }
850b57cec5SDimitry Andric   uint32_t getGroup() const { return Group; }
860b57cec5SDimitry Andric   uint64_t getSize() const { return Size; }
870b57cec5SDimitry Andric   /// @}
880b57cec5SDimitry Andric   /// @name Status queries
890b57cec5SDimitry Andric   /// These are static queries in llvm::sys::fs.
900b57cec5SDimitry Andric   /// @{
910b57cec5SDimitry Andric   bool equivalent(const Status &Other) const;
920b57cec5SDimitry Andric   bool isDirectory() const;
930b57cec5SDimitry Andric   bool isRegularFile() const;
940b57cec5SDimitry Andric   bool isOther() const;
950b57cec5SDimitry Andric   bool isSymlink() const;
960b57cec5SDimitry Andric   bool isStatusKnown() const;
970b57cec5SDimitry Andric   bool exists() const;
980b57cec5SDimitry Andric   /// @}
990b57cec5SDimitry Andric };
1000b57cec5SDimitry Andric 
1010b57cec5SDimitry Andric /// Represents an open file.
1020b57cec5SDimitry Andric class File {
1030b57cec5SDimitry Andric public:
1040b57cec5SDimitry Andric   /// Destroy the file after closing it (if open).
1050b57cec5SDimitry Andric   /// Sub-classes should generally call close() inside their destructors.  We
1060b57cec5SDimitry Andric   /// cannot do that from the base class, since close is virtual.
1070b57cec5SDimitry Andric   virtual ~File();
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric   /// Get the status of the file.
1100b57cec5SDimitry Andric   virtual llvm::ErrorOr<Status> status() = 0;
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric   /// Get the name of the file
1130b57cec5SDimitry Andric   virtual llvm::ErrorOr<std::string> getName() {
1140b57cec5SDimitry Andric     if (auto Status = status())
1150b57cec5SDimitry Andric       return Status->getName().str();
1160b57cec5SDimitry Andric     else
1170b57cec5SDimitry Andric       return Status.getError();
1180b57cec5SDimitry Andric   }
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric   /// Get the contents of the file as a \p MemoryBuffer.
1210b57cec5SDimitry Andric   virtual llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
1220b57cec5SDimitry Andric   getBuffer(const Twine &Name, int64_t FileSize = -1,
1230b57cec5SDimitry Andric             bool RequiresNullTerminator = true, bool IsVolatile = false) = 0;
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   /// Closes the file.
1260b57cec5SDimitry Andric   virtual std::error_code close() = 0;
127349cc55cSDimitry Andric 
128349cc55cSDimitry Andric   // Get the same file with a different path.
129349cc55cSDimitry Andric   static ErrorOr<std::unique_ptr<File>>
130349cc55cSDimitry Andric   getWithPath(ErrorOr<std::unique_ptr<File>> Result, const Twine &P);
131349cc55cSDimitry Andric 
132349cc55cSDimitry Andric protected:
133349cc55cSDimitry Andric   // Set the file's underlying path.
134349cc55cSDimitry Andric   virtual void setPath(const Twine &Path) {}
1350b57cec5SDimitry Andric };
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric /// A member of a directory, yielded by a directory_iterator.
1380b57cec5SDimitry Andric /// Only information available on most platforms is included.
1390b57cec5SDimitry Andric class directory_entry {
1400b57cec5SDimitry Andric   std::string Path;
141480093f4SDimitry Andric   llvm::sys::fs::file_type Type = llvm::sys::fs::file_type::type_unknown;
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric public:
1440b57cec5SDimitry Andric   directory_entry() = default;
1450b57cec5SDimitry Andric   directory_entry(std::string Path, llvm::sys::fs::file_type Type)
1460b57cec5SDimitry Andric       : Path(std::move(Path)), Type(Type) {}
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric   llvm::StringRef path() const { return Path; }
1490b57cec5SDimitry Andric   llvm::sys::fs::file_type type() const { return Type; }
1500b57cec5SDimitry Andric };
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric namespace detail {
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric /// An interface for virtual file systems to provide an iterator over the
1550b57cec5SDimitry Andric /// (non-recursive) contents of a directory.
1560b57cec5SDimitry Andric struct DirIterImpl {
1570b57cec5SDimitry Andric   virtual ~DirIterImpl();
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   /// Sets \c CurrentEntry to the next entry in the directory on success,
1600b57cec5SDimitry Andric   /// to directory_entry() at end,  or returns a system-defined \c error_code.
1610b57cec5SDimitry Andric   virtual std::error_code increment() = 0;
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric   directory_entry CurrentEntry;
1640b57cec5SDimitry Andric };
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric } // namespace detail
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric /// An input iterator over the entries in a virtual path, similar to
1690b57cec5SDimitry Andric /// llvm::sys::fs::directory_iterator.
1700b57cec5SDimitry Andric class directory_iterator {
1710b57cec5SDimitry Andric   std::shared_ptr<detail::DirIterImpl> Impl; // Input iterator semantics on copy
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric public:
1740b57cec5SDimitry Andric   directory_iterator(std::shared_ptr<detail::DirIterImpl> I)
1750b57cec5SDimitry Andric       : Impl(std::move(I)) {
1760b57cec5SDimitry Andric     assert(Impl.get() != nullptr && "requires non-null implementation");
1770b57cec5SDimitry Andric     if (Impl->CurrentEntry.path().empty())
1780b57cec5SDimitry Andric       Impl.reset(); // Normalize the end iterator to Impl == nullptr.
1790b57cec5SDimitry Andric   }
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric   /// Construct an 'end' iterator.
1820b57cec5SDimitry Andric   directory_iterator() = default;
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric   /// Equivalent to operator++, with an error code.
1850b57cec5SDimitry Andric   directory_iterator &increment(std::error_code &EC) {
1860b57cec5SDimitry Andric     assert(Impl && "attempting to increment past end");
1870b57cec5SDimitry Andric     EC = Impl->increment();
1880b57cec5SDimitry Andric     if (Impl->CurrentEntry.path().empty())
1890b57cec5SDimitry Andric       Impl.reset(); // Normalize the end iterator to Impl == nullptr.
1900b57cec5SDimitry Andric     return *this;
1910b57cec5SDimitry Andric   }
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   const directory_entry &operator*() const { return Impl->CurrentEntry; }
1940b57cec5SDimitry Andric   const directory_entry *operator->() const { return &Impl->CurrentEntry; }
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric   bool operator==(const directory_iterator &RHS) const {
1970b57cec5SDimitry Andric     if (Impl && RHS.Impl)
1980b57cec5SDimitry Andric       return Impl->CurrentEntry.path() == RHS.Impl->CurrentEntry.path();
1990b57cec5SDimitry Andric     return !Impl && !RHS.Impl;
2000b57cec5SDimitry Andric   }
2010b57cec5SDimitry Andric   bool operator!=(const directory_iterator &RHS) const {
2020b57cec5SDimitry Andric     return !(*this == RHS);
2030b57cec5SDimitry Andric   }
2040b57cec5SDimitry Andric };
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric class FileSystem;
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric namespace detail {
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric /// Keeps state for the recursive_directory_iterator.
2110b57cec5SDimitry Andric struct RecDirIterState {
2120b57cec5SDimitry Andric   std::stack<directory_iterator, std::vector<directory_iterator>> Stack;
2130b57cec5SDimitry Andric   bool HasNoPushRequest = false;
2140b57cec5SDimitry Andric };
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric } // end namespace detail
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric /// An input iterator over the recursive contents of a virtual path,
2190b57cec5SDimitry Andric /// similar to llvm::sys::fs::recursive_directory_iterator.
2200b57cec5SDimitry Andric class recursive_directory_iterator {
2210b57cec5SDimitry Andric   FileSystem *FS;
2220b57cec5SDimitry Andric   std::shared_ptr<detail::RecDirIterState>
2230b57cec5SDimitry Andric       State; // Input iterator semantics on copy.
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric public:
2260b57cec5SDimitry Andric   recursive_directory_iterator(FileSystem &FS, const Twine &Path,
2270b57cec5SDimitry Andric                                std::error_code &EC);
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric   /// Construct an 'end' iterator.
2300b57cec5SDimitry Andric   recursive_directory_iterator() = default;
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric   /// Equivalent to operator++, with an error code.
2330b57cec5SDimitry Andric   recursive_directory_iterator &increment(std::error_code &EC);
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric   const directory_entry &operator*() const { return *State->Stack.top(); }
2360b57cec5SDimitry Andric   const directory_entry *operator->() const { return &*State->Stack.top(); }
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric   bool operator==(const recursive_directory_iterator &Other) const {
2390b57cec5SDimitry Andric     return State == Other.State; // identity
2400b57cec5SDimitry Andric   }
2410b57cec5SDimitry Andric   bool operator!=(const recursive_directory_iterator &RHS) const {
2420b57cec5SDimitry Andric     return !(*this == RHS);
2430b57cec5SDimitry Andric   }
2440b57cec5SDimitry Andric 
2450b57cec5SDimitry Andric   /// Gets the current level. Starting path is at level 0.
2460b57cec5SDimitry Andric   int level() const {
2470b57cec5SDimitry Andric     assert(!State->Stack.empty() &&
2480b57cec5SDimitry Andric            "Cannot get level without any iteration state");
2490b57cec5SDimitry Andric     return State->Stack.size() - 1;
2500b57cec5SDimitry Andric   }
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric   void no_push() { State->HasNoPushRequest = true; }
2530b57cec5SDimitry Andric };
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric /// The virtual file system interface.
2560b57cec5SDimitry Andric class FileSystem : public llvm::ThreadSafeRefCountedBase<FileSystem> {
2570b57cec5SDimitry Andric public:
2580b57cec5SDimitry Andric   virtual ~FileSystem();
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric   /// Get the status of the entry at \p Path, if one exists.
2610b57cec5SDimitry Andric   virtual llvm::ErrorOr<Status> status(const Twine &Path) = 0;
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric   /// Get a \p File object for the file at \p Path, if one exists.
2640b57cec5SDimitry Andric   virtual llvm::ErrorOr<std::unique_ptr<File>>
2650b57cec5SDimitry Andric   openFileForRead(const Twine &Path) = 0;
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric   /// This is a convenience method that opens a file, gets its content and then
2680b57cec5SDimitry Andric   /// closes the file.
2690b57cec5SDimitry Andric   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
2700b57cec5SDimitry Andric   getBufferForFile(const Twine &Name, int64_t FileSize = -1,
2710b57cec5SDimitry Andric                    bool RequiresNullTerminator = true, bool IsVolatile = false);
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   /// Get a directory_iterator for \p Dir.
2740b57cec5SDimitry Andric   /// \note The 'end' iterator is directory_iterator().
2750b57cec5SDimitry Andric   virtual directory_iterator dir_begin(const Twine &Dir,
2760b57cec5SDimitry Andric                                        std::error_code &EC) = 0;
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric   /// Set the working directory. This will affect all following operations on
2790b57cec5SDimitry Andric   /// this file system and may propagate down for nested file systems.
2800b57cec5SDimitry Andric   virtual std::error_code setCurrentWorkingDirectory(const Twine &Path) = 0;
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric   /// Get the working directory of this file system.
2830b57cec5SDimitry Andric   virtual llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const = 0;
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric   /// Gets real path of \p Path e.g. collapse all . and .. patterns, resolve
2860b57cec5SDimitry Andric   /// symlinks. For real file system, this uses `llvm::sys::fs::real_path`.
2870b57cec5SDimitry Andric   /// This returns errc::operation_not_permitted if not implemented by subclass.
2880b57cec5SDimitry Andric   virtual std::error_code getRealPath(const Twine &Path,
2890b57cec5SDimitry Andric                                       SmallVectorImpl<char> &Output) const;
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric   /// Check whether a file exists. Provided for convenience.
2920b57cec5SDimitry Andric   bool exists(const Twine &Path);
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric   /// Is the file mounted on a local filesystem?
2950b57cec5SDimitry Andric   virtual std::error_code isLocal(const Twine &Path, bool &Result);
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric   /// Make \a Path an absolute path.
2980b57cec5SDimitry Andric   ///
2990b57cec5SDimitry Andric   /// Makes \a Path absolute using the current directory if it is not already.
3000b57cec5SDimitry Andric   /// An empty \a Path will result in the current directory.
3010b57cec5SDimitry Andric   ///
3020b57cec5SDimitry Andric   /// /absolute/path   => /absolute/path
3030b57cec5SDimitry Andric   /// relative/../path => <current-directory>/relative/../path
3040b57cec5SDimitry Andric   ///
3050b57cec5SDimitry Andric   /// \param Path A path that is modified to be an absolute path.
3060b57cec5SDimitry Andric   /// \returns success if \a path has been made absolute, otherwise a
3070b57cec5SDimitry Andric   ///          platform-specific error_code.
308480093f4SDimitry Andric   virtual std::error_code makeAbsolute(SmallVectorImpl<char> &Path) const;
3090b57cec5SDimitry Andric };
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric /// Gets an \p vfs::FileSystem for the 'real' file system, as seen by
3120b57cec5SDimitry Andric /// the operating system.
3130b57cec5SDimitry Andric /// The working directory is linked to the process's working directory.
3140b57cec5SDimitry Andric /// (This is usually thread-hostile).
3150b57cec5SDimitry Andric IntrusiveRefCntPtr<FileSystem> getRealFileSystem();
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric /// Create an \p vfs::FileSystem for the 'real' file system, as seen by
3180b57cec5SDimitry Andric /// the operating system.
3190b57cec5SDimitry Andric /// It has its own working directory, independent of (but initially equal to)
3200b57cec5SDimitry Andric /// that of the process.
3210b57cec5SDimitry Andric std::unique_ptr<FileSystem> createPhysicalFileSystem();
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric /// A file system that allows overlaying one \p AbstractFileSystem on top
3240b57cec5SDimitry Andric /// of another.
3250b57cec5SDimitry Andric ///
3260b57cec5SDimitry Andric /// Consists of a stack of >=1 \p FileSystem objects, which are treated as being
3270b57cec5SDimitry Andric /// one merged file system. When there is a directory that exists in more than
3280b57cec5SDimitry Andric /// one file system, the \p OverlayFileSystem contains a directory containing
3290b57cec5SDimitry Andric /// the union of their contents.  The attributes (permissions, etc.) of the
3300b57cec5SDimitry Andric /// top-most (most recently added) directory are used.  When there is a file
3310b57cec5SDimitry Andric /// that exists in more than one file system, the file in the top-most file
3320b57cec5SDimitry Andric /// system overrides the other(s).
3330b57cec5SDimitry Andric class OverlayFileSystem : public FileSystem {
3340b57cec5SDimitry Andric   using FileSystemList = SmallVector<IntrusiveRefCntPtr<FileSystem>, 1>;
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric   /// The stack of file systems, implemented as a list in order of
3370b57cec5SDimitry Andric   /// their addition.
3380b57cec5SDimitry Andric   FileSystemList FSList;
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric public:
3410b57cec5SDimitry Andric   OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> Base);
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric   /// Pushes a file system on top of the stack.
3440b57cec5SDimitry Andric   void pushOverlay(IntrusiveRefCntPtr<FileSystem> FS);
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric   llvm::ErrorOr<Status> status(const Twine &Path) override;
3470b57cec5SDimitry Andric   llvm::ErrorOr<std::unique_ptr<File>>
3480b57cec5SDimitry Andric   openFileForRead(const Twine &Path) override;
3490b57cec5SDimitry Andric   directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
3500b57cec5SDimitry Andric   llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
3510b57cec5SDimitry Andric   std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
3520b57cec5SDimitry Andric   std::error_code isLocal(const Twine &Path, bool &Result) override;
3530b57cec5SDimitry Andric   std::error_code getRealPath(const Twine &Path,
3540b57cec5SDimitry Andric                               SmallVectorImpl<char> &Output) const override;
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric   using iterator = FileSystemList::reverse_iterator;
3570b57cec5SDimitry Andric   using const_iterator = FileSystemList::const_reverse_iterator;
3580b57cec5SDimitry Andric   using reverse_iterator = FileSystemList::iterator;
3590b57cec5SDimitry Andric   using const_reverse_iterator = FileSystemList::const_iterator;
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric   /// Get an iterator pointing to the most recently added file system.
3620b57cec5SDimitry Andric   iterator overlays_begin() { return FSList.rbegin(); }
3630b57cec5SDimitry Andric   const_iterator overlays_begin() const { return FSList.rbegin(); }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric   /// Get an iterator pointing one-past the least recently added file system.
3660b57cec5SDimitry Andric   iterator overlays_end() { return FSList.rend(); }
3670b57cec5SDimitry Andric   const_iterator overlays_end() const { return FSList.rend(); }
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric   /// Get an iterator pointing to the least recently added file system.
3700b57cec5SDimitry Andric   reverse_iterator overlays_rbegin() { return FSList.begin(); }
3710b57cec5SDimitry Andric   const_reverse_iterator overlays_rbegin() const { return FSList.begin(); }
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric   /// Get an iterator pointing one-past the most recently added file system.
3740b57cec5SDimitry Andric   reverse_iterator overlays_rend() { return FSList.end(); }
3750b57cec5SDimitry Andric   const_reverse_iterator overlays_rend() const { return FSList.end(); }
3760b57cec5SDimitry Andric };
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric /// By default, this delegates all calls to the underlying file system. This
3790b57cec5SDimitry Andric /// is useful when derived file systems want to override some calls and still
3800b57cec5SDimitry Andric /// proxy other calls.
3810b57cec5SDimitry Andric class ProxyFileSystem : public FileSystem {
3820b57cec5SDimitry Andric public:
3830b57cec5SDimitry Andric   explicit ProxyFileSystem(IntrusiveRefCntPtr<FileSystem> FS)
3840b57cec5SDimitry Andric       : FS(std::move(FS)) {}
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric   llvm::ErrorOr<Status> status(const Twine &Path) override {
3870b57cec5SDimitry Andric     return FS->status(Path);
3880b57cec5SDimitry Andric   }
3890b57cec5SDimitry Andric   llvm::ErrorOr<std::unique_ptr<File>>
3900b57cec5SDimitry Andric   openFileForRead(const Twine &Path) override {
3910b57cec5SDimitry Andric     return FS->openFileForRead(Path);
3920b57cec5SDimitry Andric   }
3930b57cec5SDimitry Andric   directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override {
3940b57cec5SDimitry Andric     return FS->dir_begin(Dir, EC);
3950b57cec5SDimitry Andric   }
3960b57cec5SDimitry Andric   llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
3970b57cec5SDimitry Andric     return FS->getCurrentWorkingDirectory();
3980b57cec5SDimitry Andric   }
3990b57cec5SDimitry Andric   std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
4000b57cec5SDimitry Andric     return FS->setCurrentWorkingDirectory(Path);
4010b57cec5SDimitry Andric   }
4020b57cec5SDimitry Andric   std::error_code getRealPath(const Twine &Path,
4030b57cec5SDimitry Andric                               SmallVectorImpl<char> &Output) const override {
4040b57cec5SDimitry Andric     return FS->getRealPath(Path, Output);
4050b57cec5SDimitry Andric   }
4060b57cec5SDimitry Andric   std::error_code isLocal(const Twine &Path, bool &Result) override {
4070b57cec5SDimitry Andric     return FS->isLocal(Path, Result);
4080b57cec5SDimitry Andric   }
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric protected:
4110b57cec5SDimitry Andric   FileSystem &getUnderlyingFS() { return *FS; }
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric private:
4140b57cec5SDimitry Andric   IntrusiveRefCntPtr<FileSystem> FS;
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric   virtual void anchor();
4170b57cec5SDimitry Andric };
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric namespace detail {
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric class InMemoryDirectory;
4220b57cec5SDimitry Andric class InMemoryFile;
42304eeddc0SDimitry Andric class InMemoryNode;
42404eeddc0SDimitry Andric 
42504eeddc0SDimitry Andric struct NewInMemoryNodeInfo {
42604eeddc0SDimitry Andric   llvm::sys::fs::UniqueID DirUID;
42704eeddc0SDimitry Andric   StringRef Path;
42804eeddc0SDimitry Andric   StringRef Name;
42904eeddc0SDimitry Andric   time_t ModificationTime;
43004eeddc0SDimitry Andric   std::unique_ptr<llvm::MemoryBuffer> Buffer;
43104eeddc0SDimitry Andric   uint32_t User;
43204eeddc0SDimitry Andric   uint32_t Group;
43304eeddc0SDimitry Andric   llvm::sys::fs::file_type Type;
43404eeddc0SDimitry Andric   llvm::sys::fs::perms Perms;
43504eeddc0SDimitry Andric 
43604eeddc0SDimitry Andric   Status makeStatus() const;
43704eeddc0SDimitry Andric };
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric } // namespace detail
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric /// An in-memory file system.
4420b57cec5SDimitry Andric class InMemoryFileSystem : public FileSystem {
4430b57cec5SDimitry Andric   std::unique_ptr<detail::InMemoryDirectory> Root;
4440b57cec5SDimitry Andric   std::string WorkingDirectory;
4450b57cec5SDimitry Andric   bool UseNormalizedPaths = true;
4460b57cec5SDimitry Andric 
44704eeddc0SDimitry Andric   using MakeNodeFn = llvm::function_ref<std::unique_ptr<detail::InMemoryNode>(
44804eeddc0SDimitry Andric       detail::NewInMemoryNodeInfo)>;
44904eeddc0SDimitry Andric 
45004eeddc0SDimitry Andric   /// Create node with \p MakeNode and add it into this filesystem at \p Path.
4510b57cec5SDimitry Andric   bool addFile(const Twine &Path, time_t ModificationTime,
4520b57cec5SDimitry Andric                std::unique_ptr<llvm::MemoryBuffer> Buffer,
4530b57cec5SDimitry Andric                Optional<uint32_t> User, Optional<uint32_t> Group,
4540b57cec5SDimitry Andric                Optional<llvm::sys::fs::file_type> Type,
45504eeddc0SDimitry Andric                Optional<llvm::sys::fs::perms> Perms, MakeNodeFn MakeNode);
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric public:
4580b57cec5SDimitry Andric   explicit InMemoryFileSystem(bool UseNormalizedPaths = true);
4590b57cec5SDimitry Andric   ~InMemoryFileSystem() override;
4600b57cec5SDimitry Andric 
4610b57cec5SDimitry Andric   /// Add a file containing a buffer or a directory to the VFS with a
4620b57cec5SDimitry Andric   /// path. The VFS owns the buffer.  If present, User, Group, Type
4630b57cec5SDimitry Andric   /// and Perms apply to the newly-created file or directory.
4640b57cec5SDimitry Andric   /// \return true if the file or directory was successfully added,
4650b57cec5SDimitry Andric   /// false if the file or directory already exists in the file system with
4660b57cec5SDimitry Andric   /// different contents.
4670b57cec5SDimitry Andric   bool addFile(const Twine &Path, time_t ModificationTime,
4680b57cec5SDimitry Andric                std::unique_ptr<llvm::MemoryBuffer> Buffer,
4690b57cec5SDimitry Andric                Optional<uint32_t> User = None, Optional<uint32_t> Group = None,
4700b57cec5SDimitry Andric                Optional<llvm::sys::fs::file_type> Type = None,
4710b57cec5SDimitry Andric                Optional<llvm::sys::fs::perms> Perms = None);
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric   /// Add a hard link to a file.
4740b57cec5SDimitry Andric   /// Here hard links are not intended to be fully equivalent to the classical
4750b57cec5SDimitry Andric   /// filesystem. Both the hard link and the file share the same buffer and
4760b57cec5SDimitry Andric   /// status (and thus have the same UniqueID). Because of this there is no way
4770b57cec5SDimitry Andric   /// to distinguish between the link and the file after the link has been
4780b57cec5SDimitry Andric   /// added.
4790b57cec5SDimitry Andric   ///
4800b57cec5SDimitry Andric   /// The To path must be an existing file or a hardlink. The From file must not
4810b57cec5SDimitry Andric   /// have been added before. The To Path must not be a directory. The From Node
4820b57cec5SDimitry Andric   /// is added as a hard link which points to the resolved file of To Node.
4830b57cec5SDimitry Andric   /// \return true if the above condition is satisfied and hardlink was
4840b57cec5SDimitry Andric   /// successfully created, false otherwise.
4850b57cec5SDimitry Andric   bool addHardLink(const Twine &From, const Twine &To);
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric   /// Add a buffer to the VFS with a path. The VFS does not own the buffer.
4880b57cec5SDimitry Andric   /// If present, User, Group, Type and Perms apply to the newly-created file
4890b57cec5SDimitry Andric   /// or directory.
4900b57cec5SDimitry Andric   /// \return true if the file or directory was successfully added,
4910b57cec5SDimitry Andric   /// false if the file or directory already exists in the file system with
4920b57cec5SDimitry Andric   /// different contents.
4930b57cec5SDimitry Andric   bool addFileNoOwn(const Twine &Path, time_t ModificationTime,
494e8d8bef9SDimitry Andric                     const llvm::MemoryBufferRef &Buffer,
495e8d8bef9SDimitry Andric                     Optional<uint32_t> User = None,
4960b57cec5SDimitry Andric                     Optional<uint32_t> Group = None,
4970b57cec5SDimitry Andric                     Optional<llvm::sys::fs::file_type> Type = None,
4980b57cec5SDimitry Andric                     Optional<llvm::sys::fs::perms> Perms = None);
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric   std::string toString() const;
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric   /// Return true if this file system normalizes . and .. in paths.
5030b57cec5SDimitry Andric   bool useNormalizedPaths() const { return UseNormalizedPaths; }
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric   llvm::ErrorOr<Status> status(const Twine &Path) override;
5060b57cec5SDimitry Andric   llvm::ErrorOr<std::unique_ptr<File>>
5070b57cec5SDimitry Andric   openFileForRead(const Twine &Path) override;
5080b57cec5SDimitry Andric   directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric   llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
5110b57cec5SDimitry Andric     return WorkingDirectory;
5120b57cec5SDimitry Andric   }
5130b57cec5SDimitry Andric   /// Canonicalizes \p Path by combining with the current working
5140b57cec5SDimitry Andric   /// directory and normalizing the path (e.g. remove dots). If the current
5150b57cec5SDimitry Andric   /// working directory is not set, this returns errc::operation_not_permitted.
5160b57cec5SDimitry Andric   ///
5170b57cec5SDimitry Andric   /// This doesn't resolve symlinks as they are not supported in in-memory file
5180b57cec5SDimitry Andric   /// system.
5190b57cec5SDimitry Andric   std::error_code getRealPath(const Twine &Path,
5200b57cec5SDimitry Andric                               SmallVectorImpl<char> &Output) const override;
5210b57cec5SDimitry Andric   std::error_code isLocal(const Twine &Path, bool &Result) override;
5220b57cec5SDimitry Andric   std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
5230b57cec5SDimitry Andric };
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric /// Get a globally unique ID for a virtual file or directory.
5260b57cec5SDimitry Andric llvm::sys::fs::UniqueID getNextVirtualUniqueID();
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric /// Gets a \p FileSystem for a virtual file system described in YAML
5290b57cec5SDimitry Andric /// format.
530e8d8bef9SDimitry Andric std::unique_ptr<FileSystem>
5310b57cec5SDimitry Andric getVFSFromYAML(std::unique_ptr<llvm::MemoryBuffer> Buffer,
5320b57cec5SDimitry Andric                llvm::SourceMgr::DiagHandlerTy DiagHandler,
5330b57cec5SDimitry Andric                StringRef YAMLFilePath, void *DiagContext = nullptr,
5340b57cec5SDimitry Andric                IntrusiveRefCntPtr<FileSystem> ExternalFS = getRealFileSystem());
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric struct YAMLVFSEntry {
5370b57cec5SDimitry Andric   template <typename T1, typename T2>
5385ffd83dbSDimitry Andric   YAMLVFSEntry(T1 &&VPath, T2 &&RPath, bool IsDirectory = false)
5395ffd83dbSDimitry Andric       : VPath(std::forward<T1>(VPath)), RPath(std::forward<T2>(RPath)),
5405ffd83dbSDimitry Andric         IsDirectory(IsDirectory) {}
5410b57cec5SDimitry Andric   std::string VPath;
5420b57cec5SDimitry Andric   std::string RPath;
5435ffd83dbSDimitry Andric   bool IsDirectory = false;
5440b57cec5SDimitry Andric };
5450b57cec5SDimitry Andric 
546fe6060f1SDimitry Andric class RedirectingFSDirIterImpl;
5470b57cec5SDimitry Andric class RedirectingFileSystemParser;
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric /// A virtual file system parsed from a YAML file.
5500b57cec5SDimitry Andric ///
551fe6060f1SDimitry Andric /// Currently, this class allows creating virtual files and directories. Virtual
552fe6060f1SDimitry Andric /// files map to existing external files in \c ExternalFS, and virtual
553fe6060f1SDimitry Andric /// directories may either map to existing directories in \c ExternalFS or list
554fe6060f1SDimitry Andric /// their contents in the form of other virtual directories and/or files.
5550b57cec5SDimitry Andric ///
5560b57cec5SDimitry Andric /// The basic structure of the parsed file is:
5570b57cec5SDimitry Andric /// \verbatim
5580b57cec5SDimitry Andric /// {
5590b57cec5SDimitry Andric ///   'version': <version number>,
5600b57cec5SDimitry Andric ///   <optional configuration>
5610b57cec5SDimitry Andric ///   'roots': [
5620b57cec5SDimitry Andric ///              <directory entries>
5630b57cec5SDimitry Andric ///            ]
5640b57cec5SDimitry Andric /// }
5650b57cec5SDimitry Andric /// \endverbatim
5660b57cec5SDimitry Andric ///
56704eeddc0SDimitry Andric /// The roots may be absolute or relative. If relative they will be made
56804eeddc0SDimitry Andric /// absolute against the current working directory.
56904eeddc0SDimitry Andric ///
5700b57cec5SDimitry Andric /// All configuration options are optional.
571480093f4SDimitry Andric ///   'case-sensitive': <boolean, default=(true for Posix, false for Windows)>
5720b57cec5SDimitry Andric ///   'use-external-names': <boolean, default=true>
5730b57cec5SDimitry Andric ///   'overlay-relative': <boolean, default=false>
5740b57cec5SDimitry Andric ///   'fallthrough': <boolean, default=true>
5750b57cec5SDimitry Andric ///
576fe6060f1SDimitry Andric /// Virtual directories that list their contents are represented as
5770b57cec5SDimitry Andric /// \verbatim
5780b57cec5SDimitry Andric /// {
5790b57cec5SDimitry Andric ///   'type': 'directory',
5800b57cec5SDimitry Andric ///   'name': <string>,
5810b57cec5SDimitry Andric ///   'contents': [ <file or directory entries> ]
5820b57cec5SDimitry Andric /// }
5830b57cec5SDimitry Andric /// \endverbatim
5840b57cec5SDimitry Andric ///
585fe6060f1SDimitry Andric /// The default attributes for such virtual directories are:
5860b57cec5SDimitry Andric /// \verbatim
5870b57cec5SDimitry Andric /// MTime = now() when created
5880b57cec5SDimitry Andric /// Perms = 0777
5890b57cec5SDimitry Andric /// User = Group = 0
5900b57cec5SDimitry Andric /// Size = 0
5910b57cec5SDimitry Andric /// UniqueID = unspecified unique value
5920b57cec5SDimitry Andric /// \endverbatim
5930b57cec5SDimitry Andric ///
594fe6060f1SDimitry Andric /// When a path prefix matches such a directory, the next component in the path
595fe6060f1SDimitry Andric /// is matched against the entries in the 'contents' array.
596fe6060f1SDimitry Andric ///
597fe6060f1SDimitry Andric /// Re-mapped directories, on the other hand, are represented as
598fe6060f1SDimitry Andric /// /// \verbatim
599fe6060f1SDimitry Andric /// {
600fe6060f1SDimitry Andric ///   'type': 'directory-remap',
601fe6060f1SDimitry Andric ///   'name': <string>,
602fe6060f1SDimitry Andric ///   'use-external-name': <boolean>, # Optional
603fe6060f1SDimitry Andric ///   'external-contents': <path to external directory>
604fe6060f1SDimitry Andric /// }
605fe6060f1SDimitry Andric /// \endverbatim
606fe6060f1SDimitry Andric ///
607fe6060f1SDimitry Andric /// and inherit their attributes from the external directory. When a path
608fe6060f1SDimitry Andric /// prefix matches such an entry, the unmatched components are appended to the
609fe6060f1SDimitry Andric /// 'external-contents' path, and the resulting path is looked up in the
610fe6060f1SDimitry Andric /// external file system instead.
611fe6060f1SDimitry Andric ///
6120b57cec5SDimitry Andric /// Re-mapped files are represented as
6130b57cec5SDimitry Andric /// \verbatim
6140b57cec5SDimitry Andric /// {
6150b57cec5SDimitry Andric ///   'type': 'file',
6160b57cec5SDimitry Andric ///   'name': <string>,
617fe6060f1SDimitry Andric ///   'use-external-name': <boolean>, # Optional
6180b57cec5SDimitry Andric ///   'external-contents': <path to external file>
6190b57cec5SDimitry Andric /// }
6200b57cec5SDimitry Andric /// \endverbatim
6210b57cec5SDimitry Andric ///
622fe6060f1SDimitry Andric /// Their attributes and file contents are determined by looking up the file at
623fe6060f1SDimitry Andric /// their 'external-contents' path in the external file system.
6240b57cec5SDimitry Andric ///
625fe6060f1SDimitry Andric /// For 'file', 'directory' and 'directory-remap' entries the 'name' field may
626fe6060f1SDimitry Andric /// contain multiple path components (e.g. /path/to/file). However, any
627fe6060f1SDimitry Andric /// directory in such a path that contains more than one child must be uniquely
628fe6060f1SDimitry Andric /// represented by a 'directory' entry.
629349cc55cSDimitry Andric ///
630349cc55cSDimitry Andric /// When the 'use-external-name' field is set, calls to \a vfs::File::status()
631349cc55cSDimitry Andric /// give the external (remapped) filesystem name instead of the name the file
632349cc55cSDimitry Andric /// was accessed by. This is an intentional leak through the \a
633349cc55cSDimitry Andric /// RedirectingFileSystem abstraction layer. It enables clients to discover
634349cc55cSDimitry Andric /// (and use) the external file location when communicating with users or tools
635349cc55cSDimitry Andric /// that don't use the same VFS overlay.
636349cc55cSDimitry Andric ///
637349cc55cSDimitry Andric /// FIXME: 'use-external-name' causes behaviour that's inconsistent with how
638349cc55cSDimitry Andric /// "real" filesystems behave. Maybe there should be a separate channel for
639349cc55cSDimitry Andric /// this information.
6400b57cec5SDimitry Andric class RedirectingFileSystem : public vfs::FileSystem {
6410b57cec5SDimitry Andric public:
642fe6060f1SDimitry Andric   enum EntryKind { EK_Directory, EK_DirectoryRemap, EK_File };
643fe6060f1SDimitry Andric   enum NameKind { NK_NotSet, NK_External, NK_Virtual };
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric   /// A single file or directory in the VFS.
6460b57cec5SDimitry Andric   class Entry {
6470b57cec5SDimitry Andric     EntryKind Kind;
6480b57cec5SDimitry Andric     std::string Name;
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric   public:
6510b57cec5SDimitry Andric     Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
6520b57cec5SDimitry Andric     virtual ~Entry() = default;
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric     StringRef getName() const { return Name; }
6550b57cec5SDimitry Andric     EntryKind getKind() const { return Kind; }
6560b57cec5SDimitry Andric   };
6570b57cec5SDimitry Andric 
658fe6060f1SDimitry Andric   /// A directory in the vfs with explicitly specified contents.
659fe6060f1SDimitry Andric   class DirectoryEntry : public Entry {
6600b57cec5SDimitry Andric     std::vector<std::unique_ptr<Entry>> Contents;
6610b57cec5SDimitry Andric     Status S;
6620b57cec5SDimitry Andric 
6630b57cec5SDimitry Andric   public:
664fe6060f1SDimitry Andric     /// Constructs a directory entry with explicitly specified contents.
665fe6060f1SDimitry Andric     DirectoryEntry(StringRef Name, std::vector<std::unique_ptr<Entry>> Contents,
6660b57cec5SDimitry Andric                    Status S)
6670b57cec5SDimitry Andric         : Entry(EK_Directory, Name), Contents(std::move(Contents)),
6680b57cec5SDimitry Andric           S(std::move(S)) {}
669fe6060f1SDimitry Andric 
670fe6060f1SDimitry Andric     /// Constructs an empty directory entry.
671fe6060f1SDimitry Andric     DirectoryEntry(StringRef Name, Status S)
6720b57cec5SDimitry Andric         : Entry(EK_Directory, Name), S(std::move(S)) {}
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric     Status getStatus() { return S; }
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric     void addContent(std::unique_ptr<Entry> Content) {
6770b57cec5SDimitry Andric       Contents.push_back(std::move(Content));
6780b57cec5SDimitry Andric     }
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric     Entry *getLastContent() const { return Contents.back().get(); }
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric     using iterator = decltype(Contents)::iterator;
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric     iterator contents_begin() { return Contents.begin(); }
6850b57cec5SDimitry Andric     iterator contents_end() { return Contents.end(); }
6860b57cec5SDimitry Andric 
6870b57cec5SDimitry Andric     static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
6880b57cec5SDimitry Andric   };
6890b57cec5SDimitry Andric 
690fe6060f1SDimitry Andric   /// A file or directory in the vfs that is mapped to a file or directory in
691fe6060f1SDimitry Andric   /// the external filesystem.
692fe6060f1SDimitry Andric   class RemapEntry : public Entry {
6930b57cec5SDimitry Andric     std::string ExternalContentsPath;
6940b57cec5SDimitry Andric     NameKind UseName;
6950b57cec5SDimitry Andric 
696fe6060f1SDimitry Andric   protected:
697fe6060f1SDimitry Andric     RemapEntry(EntryKind K, StringRef Name, StringRef ExternalContentsPath,
6980b57cec5SDimitry Andric                NameKind UseName)
699fe6060f1SDimitry Andric         : Entry(K, Name), ExternalContentsPath(ExternalContentsPath),
7000b57cec5SDimitry Andric           UseName(UseName) {}
7010b57cec5SDimitry Andric 
702fe6060f1SDimitry Andric   public:
7030b57cec5SDimitry Andric     StringRef getExternalContentsPath() const { return ExternalContentsPath; }
7040b57cec5SDimitry Andric 
705fe6060f1SDimitry Andric     /// Whether to use the external path as the name for this file or directory.
7060b57cec5SDimitry Andric     bool useExternalName(bool GlobalUseExternalName) const {
7070b57cec5SDimitry Andric       return UseName == NK_NotSet ? GlobalUseExternalName
7080b57cec5SDimitry Andric                                   : (UseName == NK_External);
7090b57cec5SDimitry Andric     }
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric     NameKind getUseName() const { return UseName; }
7120b57cec5SDimitry Andric 
713fe6060f1SDimitry Andric     static bool classof(const Entry *E) {
714fe6060f1SDimitry Andric       switch (E->getKind()) {
715fe6060f1SDimitry Andric       case EK_DirectoryRemap:
716fe6060f1SDimitry Andric         LLVM_FALLTHROUGH;
717fe6060f1SDimitry Andric       case EK_File:
718fe6060f1SDimitry Andric         return true;
719fe6060f1SDimitry Andric       case EK_Directory:
720fe6060f1SDimitry Andric         return false;
721fe6060f1SDimitry Andric       }
722fe6060f1SDimitry Andric       llvm_unreachable("invalid entry kind");
723fe6060f1SDimitry Andric     }
724fe6060f1SDimitry Andric   };
725fe6060f1SDimitry Andric 
726fe6060f1SDimitry Andric   /// A directory in the vfs that maps to a directory in the external file
727fe6060f1SDimitry Andric   /// system.
728fe6060f1SDimitry Andric   class DirectoryRemapEntry : public RemapEntry {
729fe6060f1SDimitry Andric   public:
730fe6060f1SDimitry Andric     DirectoryRemapEntry(StringRef Name, StringRef ExternalContentsPath,
731fe6060f1SDimitry Andric                         NameKind UseName)
732fe6060f1SDimitry Andric         : RemapEntry(EK_DirectoryRemap, Name, ExternalContentsPath, UseName) {}
733fe6060f1SDimitry Andric 
734fe6060f1SDimitry Andric     static bool classof(const Entry *E) {
735fe6060f1SDimitry Andric       return E->getKind() == EK_DirectoryRemap;
736fe6060f1SDimitry Andric     }
737fe6060f1SDimitry Andric   };
738fe6060f1SDimitry Andric 
739fe6060f1SDimitry Andric   /// A file in the vfs that maps to a file in the external file system.
740fe6060f1SDimitry Andric   class FileEntry : public RemapEntry {
741fe6060f1SDimitry Andric   public:
742fe6060f1SDimitry Andric     FileEntry(StringRef Name, StringRef ExternalContentsPath, NameKind UseName)
743fe6060f1SDimitry Andric         : RemapEntry(EK_File, Name, ExternalContentsPath, UseName) {}
744fe6060f1SDimitry Andric 
7450b57cec5SDimitry Andric     static bool classof(const Entry *E) { return E->getKind() == EK_File; }
7460b57cec5SDimitry Andric   };
7470b57cec5SDimitry Andric 
748fe6060f1SDimitry Andric   /// Represents the result of a path lookup into the RedirectingFileSystem.
749fe6060f1SDimitry Andric   struct LookupResult {
750fe6060f1SDimitry Andric     /// The entry the looked-up path corresponds to.
751fe6060f1SDimitry Andric     Entry *E;
752fe6060f1SDimitry Andric 
7530b57cec5SDimitry Andric   private:
754fe6060f1SDimitry Andric     /// When the found Entry is a DirectoryRemapEntry, stores the path in the
755fe6060f1SDimitry Andric     /// external file system that the looked-up path in the virtual file system
756fe6060f1SDimitry Andric     //  corresponds to.
757fe6060f1SDimitry Andric     Optional<std::string> ExternalRedirect;
758fe6060f1SDimitry Andric 
759fe6060f1SDimitry Andric   public:
760fe6060f1SDimitry Andric     LookupResult(Entry *E, sys::path::const_iterator Start,
761fe6060f1SDimitry Andric                  sys::path::const_iterator End);
762fe6060f1SDimitry Andric 
763fe6060f1SDimitry Andric     /// If the found Entry maps the the input path to a path in the external
764fe6060f1SDimitry Andric     /// file system (i.e. it is a FileEntry or DirectoryRemapEntry), returns
765fe6060f1SDimitry Andric     /// that path.
766fe6060f1SDimitry Andric     Optional<StringRef> getExternalRedirect() const {
767fe6060f1SDimitry Andric       if (isa<DirectoryRemapEntry>(E))
768fe6060f1SDimitry Andric         return StringRef(*ExternalRedirect);
769fe6060f1SDimitry Andric       if (auto *FE = dyn_cast<FileEntry>(E))
770fe6060f1SDimitry Andric         return FE->getExternalContentsPath();
771fe6060f1SDimitry Andric       return None;
772fe6060f1SDimitry Andric     }
773fe6060f1SDimitry Andric   };
774fe6060f1SDimitry Andric 
775fe6060f1SDimitry Andric private:
776fe6060f1SDimitry Andric   friend class RedirectingFSDirIterImpl;
7770b57cec5SDimitry Andric   friend class RedirectingFileSystemParser;
7780b57cec5SDimitry Andric 
779e8d8bef9SDimitry Andric   bool shouldUseExternalFS() const { return IsFallthrough; }
780e8d8bef9SDimitry Andric 
781e8d8bef9SDimitry Andric   /// Canonicalize path by removing ".", "..", "./", components. This is
782e8d8bef9SDimitry Andric   /// a VFS request, do not bother about symlinks in the path components
783e8d8bef9SDimitry Andric   /// but canonicalize in order to perform the correct entry search.
784e8d8bef9SDimitry Andric   std::error_code makeCanonical(SmallVectorImpl<char> &Path) const;
7858bcb0991SDimitry Andric 
786fe6060f1SDimitry Andric   /// Whether to fall back to the external file system when an operation fails
787fe6060f1SDimitry Andric   /// with the given error code on a path associated with the provided Entry.
788fe6060f1SDimitry Andric   bool shouldFallBackToExternalFS(std::error_code EC, Entry *E = nullptr) const;
789fe6060f1SDimitry Andric 
790349cc55cSDimitry Andric   /// Get the File status, or error, from the underlying external file system.
791349cc55cSDimitry Andric   /// This returns the status with the originally requested name, while looking
792349cc55cSDimitry Andric   /// up the entry using the canonical path.
793349cc55cSDimitry Andric   ErrorOr<Status> getExternalStatus(const Twine &CanonicalPath,
794349cc55cSDimitry Andric                                     const Twine &OriginalPath) const;
795349cc55cSDimitry Andric 
796480093f4SDimitry Andric   // In a RedirectingFileSystem, keys can be specified in Posix or Windows
797480093f4SDimitry Andric   // style (or even a mixture of both), so this comparison helper allows
798480093f4SDimitry Andric   // slashes (representing a root) to match backslashes (and vice versa).  Note
7995ffd83dbSDimitry Andric   // that, other than the root, path components should not contain slashes or
800480093f4SDimitry Andric   // backslashes.
801480093f4SDimitry Andric   bool pathComponentMatches(llvm::StringRef lhs, llvm::StringRef rhs) const {
802fe6060f1SDimitry Andric     if ((CaseSensitive ? lhs.equals(rhs) : lhs.equals_insensitive(rhs)))
803480093f4SDimitry Andric       return true;
804480093f4SDimitry Andric     return (lhs == "/" && rhs == "\\") || (lhs == "\\" && rhs == "/");
805480093f4SDimitry Andric   }
806480093f4SDimitry Andric 
8070b57cec5SDimitry Andric   /// The root(s) of the virtual file system.
8080b57cec5SDimitry Andric   std::vector<std::unique_ptr<Entry>> Roots;
8090b57cec5SDimitry Andric 
8108bcb0991SDimitry Andric   /// The current working directory of the file system.
8118bcb0991SDimitry Andric   std::string WorkingDirectory;
8128bcb0991SDimitry Andric 
8130b57cec5SDimitry Andric   /// The file system to use for external references.
8140b57cec5SDimitry Andric   IntrusiveRefCntPtr<FileSystem> ExternalFS;
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric   /// If IsRelativeOverlay is set, this represents the directory
8170b57cec5SDimitry Andric   /// path that should be prefixed to each 'external-contents' entry
8180b57cec5SDimitry Andric   /// when reading from YAML files.
8190b57cec5SDimitry Andric   std::string ExternalContentsPrefixDir;
8200b57cec5SDimitry Andric 
8210b57cec5SDimitry Andric   /// @name Configuration
8220b57cec5SDimitry Andric   /// @{
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric   /// Whether to perform case-sensitive comparisons.
8250b57cec5SDimitry Andric   ///
8260b57cec5SDimitry Andric   /// Currently, case-insensitive matching only works correctly with ASCII.
827349cc55cSDimitry Andric   bool CaseSensitive = is_style_posix(sys::path::Style::native);
8280b57cec5SDimitry Andric 
8290b57cec5SDimitry Andric   /// IsRelativeOverlay marks whether a ExternalContentsPrefixDir path must
8300b57cec5SDimitry Andric   /// be prefixed in every 'external-contents' when reading from YAML files.
8310b57cec5SDimitry Andric   bool IsRelativeOverlay = false;
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric   /// Whether to use to use the value of 'external-contents' for the
8340b57cec5SDimitry Andric   /// names of files.  This global value is overridable on a per-file basis.
8350b57cec5SDimitry Andric   bool UseExternalNames = true;
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric   /// Whether to attempt a file lookup in external file system after it wasn't
8380b57cec5SDimitry Andric   /// found in VFS.
8390b57cec5SDimitry Andric   bool IsFallthrough = true;
8400b57cec5SDimitry Andric   /// @}
8410b57cec5SDimitry Andric 
8428bcb0991SDimitry Andric   RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS);
8430b57cec5SDimitry Andric 
844fe6060f1SDimitry Andric   /// Looks up the path <tt>[Start, End)</tt> in \p From, possibly recursing
845fe6060f1SDimitry Andric   /// into the contents of \p From if it is a directory. Returns a LookupResult
846fe6060f1SDimitry Andric   /// giving the matched entry and, if that entry is a FileEntry or
847fe6060f1SDimitry Andric   /// DirectoryRemapEntry, the path it redirects to in the external file system.
848fe6060f1SDimitry Andric   ErrorOr<LookupResult> lookupPathImpl(llvm::sys::path::const_iterator Start,
8490b57cec5SDimitry Andric                                        llvm::sys::path::const_iterator End,
8500b57cec5SDimitry Andric                                        Entry *From) const;
8510b57cec5SDimitry Andric 
852fe6060f1SDimitry Andric   /// Get the status for a path with the provided \c LookupResult.
853349cc55cSDimitry Andric   ErrorOr<Status> status(const Twine &CanonicalPath, const Twine &OriginalPath,
854349cc55cSDimitry Andric                          const LookupResult &Result);
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric public:
857fe6060f1SDimitry Andric   /// Looks up \p Path in \c Roots and returns a LookupResult giving the
858fe6060f1SDimitry Andric   /// matched entry and, if the entry was a FileEntry or DirectoryRemapEntry,
859fe6060f1SDimitry Andric   /// the path it redirects to in the external file system.
860fe6060f1SDimitry Andric   ErrorOr<LookupResult> lookupPath(StringRef Path) const;
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric   /// Parses \p Buffer, which is expected to be in YAML format and
8630b57cec5SDimitry Andric   /// returns a virtual file system representing its contents.
864e8d8bef9SDimitry Andric   static std::unique_ptr<RedirectingFileSystem>
8650b57cec5SDimitry Andric   create(std::unique_ptr<MemoryBuffer> Buffer,
8660b57cec5SDimitry Andric          SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
8670b57cec5SDimitry Andric          void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
8680b57cec5SDimitry Andric 
869e8d8bef9SDimitry Andric   /// Redirect each of the remapped files from first to second.
870e8d8bef9SDimitry Andric   static std::unique_ptr<RedirectingFileSystem>
871e8d8bef9SDimitry Andric   create(ArrayRef<std::pair<std::string, std::string>> RemappedFiles,
872e8d8bef9SDimitry Andric          bool UseExternalNames, FileSystem &ExternalFS);
873e8d8bef9SDimitry Andric 
8740b57cec5SDimitry Andric   ErrorOr<Status> status(const Twine &Path) override;
8750b57cec5SDimitry Andric   ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric   std::error_code getRealPath(const Twine &Path,
8780b57cec5SDimitry Andric                               SmallVectorImpl<char> &Output) const override;
8790b57cec5SDimitry Andric 
8800b57cec5SDimitry Andric   llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
8810b57cec5SDimitry Andric 
8820b57cec5SDimitry Andric   std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric   std::error_code isLocal(const Twine &Path, bool &Result) override;
8850b57cec5SDimitry Andric 
886480093f4SDimitry Andric   std::error_code makeAbsolute(SmallVectorImpl<char> &Path) const override;
887480093f4SDimitry Andric 
8880b57cec5SDimitry Andric   directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
8890b57cec5SDimitry Andric 
8900b57cec5SDimitry Andric   void setExternalContentsPrefixDir(StringRef PrefixDir);
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric   StringRef getExternalContentsPrefixDir() const;
8930b57cec5SDimitry Andric 
894e8d8bef9SDimitry Andric   void setFallthrough(bool Fallthrough);
895e8d8bef9SDimitry Andric 
896e8d8bef9SDimitry Andric   std::vector<llvm::StringRef> getRoots() const;
897e8d8bef9SDimitry Andric 
8988bcb0991SDimitry Andric   void dump(raw_ostream &OS) const;
8998bcb0991SDimitry Andric   void dumpEntry(raw_ostream &OS, Entry *E, int NumSpaces = 0) const;
9000b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9010b57cec5SDimitry Andric   LLVM_DUMP_METHOD void dump() const;
9020b57cec5SDimitry Andric #endif
9030b57cec5SDimitry Andric };
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric /// Collect all pairs of <virtual path, real path> entries from the
9060b57cec5SDimitry Andric /// \p YAMLFilePath. This is used by the module dependency collector to forward
9070b57cec5SDimitry Andric /// the entries into the reproducer output VFS YAML file.
9080b57cec5SDimitry Andric void collectVFSFromYAML(
9090b57cec5SDimitry Andric     std::unique_ptr<llvm::MemoryBuffer> Buffer,
9100b57cec5SDimitry Andric     llvm::SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
9110b57cec5SDimitry Andric     SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
9120b57cec5SDimitry Andric     void *DiagContext = nullptr,
9130b57cec5SDimitry Andric     IntrusiveRefCntPtr<FileSystem> ExternalFS = getRealFileSystem());
9140b57cec5SDimitry Andric 
9150b57cec5SDimitry Andric class YAMLVFSWriter {
9160b57cec5SDimitry Andric   std::vector<YAMLVFSEntry> Mappings;
9170b57cec5SDimitry Andric   Optional<bool> IsCaseSensitive;
9180b57cec5SDimitry Andric   Optional<bool> IsOverlayRelative;
9190b57cec5SDimitry Andric   Optional<bool> UseExternalNames;
9200b57cec5SDimitry Andric   std::string OverlayDir;
9210b57cec5SDimitry Andric 
9225ffd83dbSDimitry Andric   void addEntry(StringRef VirtualPath, StringRef RealPath, bool IsDirectory);
9235ffd83dbSDimitry Andric 
9240b57cec5SDimitry Andric public:
9250b57cec5SDimitry Andric   YAMLVFSWriter() = default;
9260b57cec5SDimitry Andric 
9270b57cec5SDimitry Andric   void addFileMapping(StringRef VirtualPath, StringRef RealPath);
9285ffd83dbSDimitry Andric   void addDirectoryMapping(StringRef VirtualPath, StringRef RealPath);
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric   void setCaseSensitivity(bool CaseSensitive) {
9310b57cec5SDimitry Andric     IsCaseSensitive = CaseSensitive;
9320b57cec5SDimitry Andric   }
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric   void setUseExternalNames(bool UseExtNames) { UseExternalNames = UseExtNames; }
9350b57cec5SDimitry Andric 
9360b57cec5SDimitry Andric   void setOverlayDir(StringRef OverlayDirectory) {
9370b57cec5SDimitry Andric     IsOverlayRelative = true;
9380b57cec5SDimitry Andric     OverlayDir.assign(OverlayDirectory.str());
9390b57cec5SDimitry Andric   }
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric   const std::vector<YAMLVFSEntry> &getMappings() const { return Mappings; }
9420b57cec5SDimitry Andric 
9430b57cec5SDimitry Andric   void write(llvm::raw_ostream &OS);
9440b57cec5SDimitry Andric };
9450b57cec5SDimitry Andric 
9460b57cec5SDimitry Andric } // namespace vfs
9470b57cec5SDimitry Andric } // namespace llvm
9480b57cec5SDimitry Andric 
9490b57cec5SDimitry Andric #endif // LLVM_SUPPORT_VIRTUALFILESYSTEM_H
950