Index: cfe/trunk/include/clang/Basic/FileManager.h =================================================================== --- cfe/trunk/include/clang/Basic/FileManager.h +++ cfe/trunk/include/clang/Basic/FileManager.h @@ -16,7 +16,7 @@ #define LLVM_CLANG_BASIC_FILEMANAGER_H #include "clang/Basic/FileSystemOptions.h" -#include "clang/Basic/VirtualFileSystem.h" +#include "clang/Basic/LLVM.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/SmallVector.h" @@ -25,9 +25,10 @@ #include "llvm/Support/Allocator.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/FileSystem.h" +#include "llvm/Support/VirtualFileSystem.h" #include -#include #include +#include #include namespace llvm { @@ -71,7 +72,7 @@ bool IsValid; // Is this \c FileEntry initialized and valid? /// The open file, if it is owned by the \p FileEntry. - mutable std::unique_ptr File; + mutable std::unique_ptr File; public: FileEntry() @@ -114,7 +115,7 @@ /// as a single file. /// class FileManager : public RefCountedBase { - IntrusiveRefCntPtr FS; + IntrusiveRefCntPtr FS; FileSystemOptions FileSystemOpts; /// Cache for existing real directories. @@ -165,7 +166,7 @@ std::unique_ptr StatCache; bool getStatValue(StringRef Path, FileData &Data, bool isFile, - std::unique_ptr *F); + std::unique_ptr *F); /// Add all ancestors of the given path (pointing to either a file /// or a directory) as virtual directories. @@ -173,7 +174,7 @@ public: FileManager(const FileSystemOptions &FileSystemOpts, - IntrusiveRefCntPtr FS = nullptr); + IntrusiveRefCntPtr FS = nullptr); ~FileManager(); /// Installs the provided FileSystemStatCache object within @@ -222,7 +223,7 @@ FileSystemOptions &getFileSystemOpts() { return FileSystemOpts; } const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; } - IntrusiveRefCntPtr getVirtualFileSystem() const { + IntrusiveRefCntPtr getVirtualFileSystem() const { return FS; } @@ -247,8 +248,7 @@ /// FileManager's FileSystemOptions. /// /// \returns false on success, true on error. - bool getNoncachedStatValue(StringRef Path, - vfs::Status &Result); + bool getNoncachedStatValue(StringRef Path, llvm::vfs::Status &Result); /// Remove the real file \p Entry from the cache. void invalidateCache(const FileEntry *Entry); Index: cfe/trunk/include/clang/Basic/FileSystemStatCache.h =================================================================== --- cfe/trunk/include/clang/Basic/FileSystemStatCache.h +++ cfe/trunk/include/clang/Basic/FileSystemStatCache.h @@ -26,7 +26,7 @@ #include #include -namespace clang { +namespace llvm { namespace vfs { @@ -34,6 +34,9 @@ class FileSystem; } // namespace vfs +} // namespace llvm + +namespace clang { // FIXME: should probably replace this with vfs::Status struct FileData { @@ -82,8 +85,8 @@ /// implementation can optionally fill in \p F with a valid \p File object and /// the client guarantees that it will close it. static bool get(StringRef Path, FileData &Data, bool isFile, - std::unique_ptr *F, FileSystemStatCache *Cache, - vfs::FileSystem &FS); + std::unique_ptr *F, + FileSystemStatCache *Cache, llvm::vfs::FileSystem &FS); /// Sets the next stat call cache in the chain of stat caches. /// Takes ownership of the given stat cache. @@ -106,11 +109,12 @@ // unique_ptr. Optional&> might be nicer, but // Optional needs some work to support references so this isn't possible yet. virtual LookupResult getStat(StringRef Path, FileData &Data, bool isFile, - std::unique_ptr *F, - vfs::FileSystem &FS) = 0; + std::unique_ptr *F, + llvm::vfs::FileSystem &FS) = 0; LookupResult statChained(StringRef Path, FileData &Data, bool isFile, - std::unique_ptr *F, vfs::FileSystem &FS) { + std::unique_ptr *F, + llvm::vfs::FileSystem &FS) { if (FileSystemStatCache *Next = getNextStatCache()) return Next->getStat(Path, Data, isFile, F, FS); @@ -135,8 +139,8 @@ iterator end() const { return StatCalls.end(); } LookupResult getStat(StringRef Path, FileData &Data, bool isFile, - std::unique_ptr *F, - vfs::FileSystem &FS) override; + std::unique_ptr *F, + llvm::vfs::FileSystem &FS) override; }; } // namespace clang Index: cfe/trunk/include/clang/Basic/VirtualFileSystem.h =================================================================== --- cfe/trunk/include/clang/Basic/VirtualFileSystem.h +++ cfe/trunk/include/clang/Basic/VirtualFileSystem.h @@ -1,529 +0,0 @@ -//===- VirtualFileSystem.h - Virtual File System Layer ----------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -/// \file -/// Defines the virtual file system interface vfs::FileSystem. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_BASIC_VIRTUALFILESYSTEM_H -#define LLVM_CLANG_BASIC_VIRTUALFILESYSTEM_H - -#include "clang/Basic/LLVM.h" -#include "llvm/ADT/IntrusiveRefCntPtr.h" -#include "llvm/ADT/None.h" -#include "llvm/ADT/Optional.h" -#include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/StringRef.h" -#include "llvm/ADT/Twine.h" -#include "llvm/Support/Chrono.h" -#include "llvm/Support/ErrorOr.h" -#include "llvm/Support/FileSystem.h" -#include "llvm/Support/SourceMgr.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace llvm { - -class MemoryBuffer; - -} // namespace llvm - -namespace clang { -namespace vfs { - -/// The result of a \p status operation. -class Status { - std::string Name; - llvm::sys::fs::UniqueID UID; - llvm::sys::TimePoint<> MTime; - uint32_t User; - uint32_t Group; - uint64_t Size; - llvm::sys::fs::file_type Type = llvm::sys::fs::file_type::status_error; - llvm::sys::fs::perms Perms; - -public: - // FIXME: remove when files support multiple names - bool IsVFSMapped = false; - - Status() = default; - Status(const llvm::sys::fs::file_status &Status); - Status(StringRef Name, llvm::sys::fs::UniqueID UID, - llvm::sys::TimePoint<> MTime, uint32_t User, uint32_t Group, - uint64_t Size, llvm::sys::fs::file_type Type, - llvm::sys::fs::perms Perms); - - /// Get a copy of a Status with a different name. - static Status copyWithNewName(const Status &In, StringRef NewName); - static Status copyWithNewName(const llvm::sys::fs::file_status &In, - StringRef NewName); - - /// Returns the name that should be used for this file or directory. - StringRef getName() const { return Name; } - - /// @name Status interface from llvm::sys::fs - /// @{ - llvm::sys::fs::file_type getType() const { return Type; } - llvm::sys::fs::perms getPermissions() const { return Perms; } - llvm::sys::TimePoint<> getLastModificationTime() const { return MTime; } - llvm::sys::fs::UniqueID getUniqueID() const { return UID; } - uint32_t getUser() const { return User; } - uint32_t getGroup() const { return Group; } - uint64_t getSize() const { return Size; } - /// @} - /// @name Status queries - /// These are static queries in llvm::sys::fs. - /// @{ - bool equivalent(const Status &Other) const; - bool isDirectory() const; - bool isRegularFile() const; - bool isOther() const; - bool isSymlink() const; - bool isStatusKnown() const; - bool exists() const; - /// @} -}; - -/// Represents an open file. -class File { -public: - /// Destroy the file after closing it (if open). - /// Sub-classes should generally call close() inside their destructors. We - /// cannot do that from the base class, since close is virtual. - virtual ~File(); - - /// Get the status of the file. - virtual llvm::ErrorOr status() = 0; - - /// Get the name of the file - virtual llvm::ErrorOr getName() { - if (auto Status = status()) - return Status->getName().str(); - else - return Status.getError(); - } - - /// Get the contents of the file as a \p MemoryBuffer. - virtual llvm::ErrorOr> - getBuffer(const Twine &Name, int64_t FileSize = -1, - bool RequiresNullTerminator = true, bool IsVolatile = false) = 0; - - /// Closes the file. - virtual std::error_code close() = 0; -}; - -/// A member of a directory, yielded by a directory_iterator. -/// Only information available on most platforms is included. -class directory_entry { - std::string Path; - llvm::sys::fs::file_type Type; - -public: - directory_entry() = default; - directory_entry(std::string Path, llvm::sys::fs::file_type Type) - : Path(std::move(Path)), Type(Type) {} - - llvm::StringRef path() const { return Path; } - llvm::sys::fs::file_type type() const { return Type; } -}; - -namespace detail { - -/// An interface for virtual file systems to provide an iterator over the -/// (non-recursive) contents of a directory. -struct DirIterImpl { - virtual ~DirIterImpl(); - - /// Sets \c CurrentEntry to the next entry in the directory on success, - /// to directory_entry() at end, or returns a system-defined \c error_code. - virtual std::error_code increment() = 0; - - directory_entry CurrentEntry; -}; - -} // namespace detail - -/// An input iterator over the entries in a virtual path, similar to -/// llvm::sys::fs::directory_iterator. -class directory_iterator { - std::shared_ptr Impl; // Input iterator semantics on copy - -public: - directory_iterator(std::shared_ptr I) - : Impl(std::move(I)) { - assert(Impl.get() != nullptr && "requires non-null implementation"); - if (Impl->CurrentEntry.path().empty()) - Impl.reset(); // Normalize the end iterator to Impl == nullptr. - } - - /// Construct an 'end' iterator. - directory_iterator() = default; - - /// Equivalent to operator++, with an error code. - directory_iterator &increment(std::error_code &EC) { - assert(Impl && "attempting to increment past end"); - EC = Impl->increment(); - if (Impl->CurrentEntry.path().empty()) - Impl.reset(); // Normalize the end iterator to Impl == nullptr. - return *this; - } - - const directory_entry &operator*() const { return Impl->CurrentEntry; } - const directory_entry *operator->() const { return &Impl->CurrentEntry; } - - bool operator==(const directory_iterator &RHS) const { - if (Impl && RHS.Impl) - return Impl->CurrentEntry.path() == RHS.Impl->CurrentEntry.path(); - return !Impl && !RHS.Impl; - } - bool operator!=(const directory_iterator &RHS) const { - return !(*this == RHS); - } -}; - -class FileSystem; - -/// An input iterator over the recursive contents of a virtual path, -/// similar to llvm::sys::fs::recursive_directory_iterator. -class recursive_directory_iterator { - using IterState = - std::stack>; - - FileSystem *FS; - std::shared_ptr State; // Input iterator semantics on copy. - -public: - recursive_directory_iterator(FileSystem &FS, const Twine &Path, - std::error_code &EC); - - /// Construct an 'end' iterator. - recursive_directory_iterator() = default; - - /// Equivalent to operator++, with an error code. - recursive_directory_iterator &increment(std::error_code &EC); - - const directory_entry &operator*() const { return *State->top(); } - const directory_entry *operator->() const { return &*State->top(); } - - bool operator==(const recursive_directory_iterator &Other) const { - return State == Other.State; // identity - } - bool operator!=(const recursive_directory_iterator &RHS) const { - return !(*this == RHS); - } - - /// Gets the current level. Starting path is at level 0. - int level() const { - assert(!State->empty() && "Cannot get level without any iteration state"); - return State->size()-1; - } -}; - -/// The virtual file system interface. -class FileSystem : public llvm::ThreadSafeRefCountedBase { -public: - virtual ~FileSystem(); - - /// Get the status of the entry at \p Path, if one exists. - virtual llvm::ErrorOr status(const Twine &Path) = 0; - - /// Get a \p File object for the file at \p Path, if one exists. - virtual llvm::ErrorOr> - openFileForRead(const Twine &Path) = 0; - - /// This is a convenience method that opens a file, gets its content and then - /// closes the file. - llvm::ErrorOr> - getBufferForFile(const Twine &Name, int64_t FileSize = -1, - bool RequiresNullTerminator = true, bool IsVolatile = false); - - /// Get a directory_iterator for \p Dir. - /// \note The 'end' iterator is directory_iterator(). - virtual directory_iterator dir_begin(const Twine &Dir, - std::error_code &EC) = 0; - - /// Set the working directory. This will affect all following operations on - /// this file system and may propagate down for nested file systems. - virtual std::error_code setCurrentWorkingDirectory(const Twine &Path) = 0; - - /// Get the working directory of this file system. - virtual llvm::ErrorOr getCurrentWorkingDirectory() const = 0; - - /// Gets real path of \p Path e.g. collapse all . and .. patterns, resolve - /// symlinks. For real file system, this uses `llvm::sys::fs::real_path`. - /// This returns errc::operation_not_permitted if not implemented by subclass. - virtual std::error_code getRealPath(const Twine &Path, - SmallVectorImpl &Output) const; - - /// Check whether a file exists. Provided for convenience. - bool exists(const Twine &Path); - - /// Make \a Path an absolute path. - /// - /// Makes \a Path absolute using the current directory if it is not already. - /// An empty \a Path will result in the current directory. - /// - /// /absolute/path => /absolute/path - /// relative/../path => /relative/../path - /// - /// \param Path A path that is modified to be an absolute path. - /// \returns success if \a path has been made absolute, otherwise a - /// platform-specific error_code. - std::error_code makeAbsolute(SmallVectorImpl &Path) const; -}; - -/// Gets an \p vfs::FileSystem for the 'real' file system, as seen by -/// the operating system. -IntrusiveRefCntPtr getRealFileSystem(); - -/// A file system that allows overlaying one \p AbstractFileSystem on top -/// of another. -/// -/// Consists of a stack of >=1 \p FileSystem objects, which are treated as being -/// one merged file system. When there is a directory that exists in more than -/// one file system, the \p OverlayFileSystem contains a directory containing -/// the union of their contents. The attributes (permissions, etc.) of the -/// top-most (most recently added) directory are used. When there is a file -/// that exists in more than one file system, the file in the top-most file -/// system overrides the other(s). -class OverlayFileSystem : public FileSystem { - using FileSystemList = SmallVector, 1>; - - /// The stack of file systems, implemented as a list in order of - /// their addition. - FileSystemList FSList; - -public: - OverlayFileSystem(IntrusiveRefCntPtr Base); - - /// Pushes a file system on top of the stack. - void pushOverlay(IntrusiveRefCntPtr FS); - - llvm::ErrorOr status(const Twine &Path) override; - llvm::ErrorOr> - openFileForRead(const Twine &Path) override; - directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override; - llvm::ErrorOr getCurrentWorkingDirectory() const override; - std::error_code setCurrentWorkingDirectory(const Twine &Path) override; - std::error_code getRealPath(const Twine &Path, - SmallVectorImpl &Output) const override; - - using iterator = FileSystemList::reverse_iterator; - using const_iterator = FileSystemList::const_reverse_iterator; - - /// Get an iterator pointing to the most recently added file system. - iterator overlays_begin() { return FSList.rbegin(); } - const_iterator overlays_begin() const { return FSList.rbegin(); } - - /// Get an iterator pointing one-past the least recently added file - /// system. - iterator overlays_end() { return FSList.rend(); } - const_iterator overlays_end() const { return FSList.rend(); } -}; - -/// By default, this delegates all calls to the underlying file system. This -/// is useful when derived file systems want to override some calls and still -/// proxy other calls. -class ProxyFileSystem : public FileSystem { -public: - explicit ProxyFileSystem(IntrusiveRefCntPtr FS) - : FS(std::move(FS)) {} - - llvm::ErrorOr status(const Twine &Path) override { - return FS->status(Path); - } - llvm::ErrorOr> - openFileForRead(const Twine &Path) override { - return FS->openFileForRead(Path); - } - directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override { - return FS->dir_begin(Dir, EC); - } - llvm::ErrorOr getCurrentWorkingDirectory() const override { - return FS->getCurrentWorkingDirectory(); - } - std::error_code setCurrentWorkingDirectory(const Twine &Path) override { - return FS->setCurrentWorkingDirectory(Path); - } - std::error_code getRealPath(const Twine &Path, - SmallVectorImpl &Output) const override { - return FS->getRealPath(Path, Output); - } - -protected: - FileSystem &getUnderlyingFS() { return *FS; } - -private: - IntrusiveRefCntPtr FS; -}; - -namespace detail { - -class InMemoryDirectory; -class InMemoryFile; - -} // namespace detail - -/// An in-memory file system. -class InMemoryFileSystem : public FileSystem { - std::unique_ptr Root; - std::string WorkingDirectory; - bool UseNormalizedPaths = true; - - /// If HardLinkTarget is non-null, a hardlink is created to the To path which - /// must be a file. If it is null then it adds the file as the public addFile. - bool addFile(const Twine &Path, time_t ModificationTime, - std::unique_ptr Buffer, - Optional User, Optional Group, - Optional Type, - Optional Perms, - const detail::InMemoryFile *HardLinkTarget); - -public: - explicit InMemoryFileSystem(bool UseNormalizedPaths = true); - ~InMemoryFileSystem() override; - - /// Add a file containing a buffer or a directory to the VFS with a - /// path. The VFS owns the buffer. If present, User, Group, Type - /// and Perms apply to the newly-created file or directory. - /// \return true if the file or directory was successfully added, - /// false if the file or directory already exists in the file system with - /// different contents. - bool addFile(const Twine &Path, time_t ModificationTime, - std::unique_ptr Buffer, - Optional User = None, Optional Group = None, - Optional Type = None, - Optional Perms = None); - - /// Add a hard link to a file. - /// Here hard links are not intended to be fully equivalent to the classical - /// filesystem. Both the hard link and the file share the same buffer and - /// status (and thus have the same UniqueID). Because of this there is no way - /// to distinguish between the link and the file after the link has been - /// added. - /// - /// The To path must be an existing file or a hardlink. The From file must not - /// have been added before. The To Path must not be a directory. The From Node - /// is added as a hard link which points to the resolved file of To Node. - /// \return true if the above condition is satisfied and hardlink was - /// successfully created, false otherwise. - bool addHardLink(const Twine &From, const Twine &To); - - /// Add a buffer to the VFS with a path. The VFS does not own the buffer. - /// If present, User, Group, Type and Perms apply to the newly-created file - /// or directory. - /// \return true if the file or directory was successfully added, - /// false if the file or directory already exists in the file system with - /// different contents. - bool addFileNoOwn(const Twine &Path, time_t ModificationTime, - llvm::MemoryBuffer *Buffer, - Optional User = None, - Optional Group = None, - Optional Type = None, - Optional Perms = None); - - std::string toString() const; - - /// Return true if this file system normalizes . and .. in paths. - bool useNormalizedPaths() const { return UseNormalizedPaths; } - - llvm::ErrorOr status(const Twine &Path) override; - llvm::ErrorOr> - openFileForRead(const Twine &Path) override; - directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override; - - llvm::ErrorOr getCurrentWorkingDirectory() const override { - return WorkingDirectory; - } - /// Canonicalizes \p Path by combining with the current working - /// directory and normalizing the path (e.g. remove dots). If the current - /// working directory is not set, this returns errc::operation_not_permitted. - /// - /// This doesn't resolve symlinks as they are not supported in in-memory file - /// system. - std::error_code getRealPath(const Twine &Path, - SmallVectorImpl &Output) const override; - - std::error_code setCurrentWorkingDirectory(const Twine &Path) override; -}; - -/// Get a globally unique ID for a virtual file or directory. -llvm::sys::fs::UniqueID getNextVirtualUniqueID(); - -/// Gets a \p FileSystem for a virtual file system described in YAML -/// format. -IntrusiveRefCntPtr -getVFSFromYAML(std::unique_ptr Buffer, - llvm::SourceMgr::DiagHandlerTy DiagHandler, - StringRef YAMLFilePath, - void *DiagContext = nullptr, - IntrusiveRefCntPtr ExternalFS = getRealFileSystem()); - -struct YAMLVFSEntry { - template YAMLVFSEntry(T1 &&VPath, T2 &&RPath) - : VPath(std::forward(VPath)), RPath(std::forward(RPath)) {} - std::string VPath; - std::string RPath; -}; - -/// Collect all pairs of entries from the -/// \p YAMLFilePath. This is used by the module dependency collector to forward -/// the entries into the reproducer output VFS YAML file. -void collectVFSFromYAML( - std::unique_ptr Buffer, - llvm::SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath, - SmallVectorImpl &CollectedEntries, - void *DiagContext = nullptr, - IntrusiveRefCntPtr ExternalFS = getRealFileSystem()); - -class YAMLVFSWriter { - std::vector Mappings; - Optional IsCaseSensitive; - Optional IsOverlayRelative; - Optional UseExternalNames; - Optional IgnoreNonExistentContents; - std::string OverlayDir; - -public: - YAMLVFSWriter() = default; - - void addFileMapping(StringRef VirtualPath, StringRef RealPath); - - void setCaseSensitivity(bool CaseSensitive) { - IsCaseSensitive = CaseSensitive; - } - - void setUseExternalNames(bool UseExtNames) { - UseExternalNames = UseExtNames; - } - - void setIgnoreNonExistentContents(bool IgnoreContents) { - IgnoreNonExistentContents = IgnoreContents; - } - - void setOverlayDir(StringRef OverlayDirectory) { - IsOverlayRelative = true; - OverlayDir.assign(OverlayDirectory.str()); - } - - void write(llvm::raw_ostream &OS); -}; - -} // namespace vfs -} // namespace clang - -#endif // LLVM_CLANG_BASIC_VIRTUALFILESYSTEM_H Index: cfe/trunk/include/clang/Driver/Distro.h =================================================================== --- cfe/trunk/include/clang/Driver/Distro.h +++ cfe/trunk/include/clang/Driver/Distro.h @@ -10,7 +10,7 @@ #ifndef LLVM_CLANG_DRIVER_DISTRO_H #define LLVM_CLANG_DRIVER_DISTRO_H -#include "clang/Basic/VirtualFileSystem.h" +#include "llvm/Support/VirtualFileSystem.h" namespace clang { namespace driver { @@ -80,7 +80,7 @@ Distro(DistroType D) : DistroVal(D) {} /// Detects the distribution using specified VFS. - explicit Distro(clang::vfs::FileSystem& VFS); + explicit Distro(llvm::vfs::FileSystem &VFS); bool operator==(const Distro &Other) const { return DistroVal == Other.DistroVal; Index: cfe/trunk/include/clang/Driver/Driver.h =================================================================== --- cfe/trunk/include/clang/Driver/Driver.h +++ cfe/trunk/include/clang/Driver/Driver.h @@ -28,13 +28,12 @@ namespace llvm { class Triple; -} - -namespace clang { - namespace vfs { class FileSystem; } +} // namespace llvm + +namespace clang { namespace driver { @@ -61,7 +60,7 @@ DiagnosticsEngine &Diags; - IntrusiveRefCntPtr VFS; + IntrusiveRefCntPtr VFS; enum DriverMode { GCCMode, @@ -284,7 +283,7 @@ public: Driver(StringRef ClangExecutable, StringRef TargetTriple, DiagnosticsEngine &Diags, - IntrusiveRefCntPtr VFS = nullptr); + IntrusiveRefCntPtr VFS = nullptr); /// @name Accessors /// @{ @@ -298,7 +297,7 @@ const DiagnosticsEngine &getDiags() const { return Diags; } - vfs::FileSystem &getVFS() const { return *VFS; } + llvm::vfs::FileSystem &getVFS() const { return *VFS; } bool getCheckInputsExist() const { return CheckInputsExist; } Index: cfe/trunk/include/clang/Driver/ToolChain.h =================================================================== --- cfe/trunk/include/clang/Driver/ToolChain.h +++ cfe/trunk/include/clang/Driver/ToolChain.h @@ -36,17 +36,16 @@ class DerivedArgList; } // namespace opt -} // namespace llvm - -namespace clang { - -class ObjCRuntime; - namespace vfs { class FileSystem; } // namespace vfs +} // namespace llvm + +namespace clang { + +class ObjCRuntime; namespace driver { @@ -183,7 +182,7 @@ // Accessors const Driver &getDriver() const { return D; } - vfs::FileSystem &getVFS() const; + llvm::vfs::FileSystem &getVFS() const; const llvm::Triple &getTriple() const { return Triple; } /// Get the toolchain's aux triple, if it has one. Index: cfe/trunk/include/clang/Format/Format.h =================================================================== --- cfe/trunk/include/clang/Format/Format.h +++ cfe/trunk/include/clang/Format/Format.h @@ -22,16 +22,18 @@ #include "llvm/Support/Regex.h" #include +namespace llvm { +namespace vfs { +class FileSystem; +} +} // namespace llvm + namespace clang { class Lexer; class SourceManager; class DiagnosticConsumer; -namespace vfs { -class FileSystem; -} - namespace format { enum class ParseError { Success = 0, Error, Unsuitable }; @@ -2039,7 +2041,7 @@ llvm::Expected getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle, StringRef Code = "", - vfs::FileSystem *FS = nullptr); + llvm::vfs::FileSystem *FS = nullptr); // Guesses the language from the ``FileName`` and ``Code`` to be formatted. // Defaults to FormatStyle::LK_Cpp. Index: cfe/trunk/include/clang/Frontend/ASTUnit.h =================================================================== --- cfe/trunk/include/clang/Frontend/ASTUnit.h +++ cfe/trunk/include/clang/Frontend/ASTUnit.h @@ -51,6 +51,11 @@ class MemoryBuffer; +namespace vfs { + +class FileSystem; + +} // namespace vfs } // namespace llvm namespace clang { @@ -75,12 +80,6 @@ class Sema; class TargetInfo; -namespace vfs { - -class FileSystem; - -} // namespace vfs - /// \brief Enumerates the available scopes for skipping function bodies. enum class SkipFunctionBodiesScope { None, Preamble, PreambleAndMainFile }; @@ -365,12 +364,12 @@ bool Parse(std::shared_ptr PCHContainerOps, std::unique_ptr OverrideMainBuffer, - IntrusiveRefCntPtr VFS); + IntrusiveRefCntPtr VFS); std::unique_ptr getMainBufferWithPrecompiledPreamble( std::shared_ptr PCHContainerOps, CompilerInvocation &PreambleInvocationIn, - IntrusiveRefCntPtr VFS, bool AllowRebuild = true, + IntrusiveRefCntPtr VFS, bool AllowRebuild = true, unsigned MaxLines = 0); void RealizeTopLevelDeclsFromPreamble(); @@ -698,17 +697,17 @@ /// of this translation unit should be precompiled, to improve the performance /// of reparsing. Set to zero to disable preambles. /// - /// \param VFS - A vfs::FileSystem to be used for all file accesses. Note that - /// preamble is saved to a temporary directory on a RealFileSystem, so in order - /// for it to be loaded correctly, VFS should have access to it(i.e., be an - /// overlay over RealFileSystem). + /// \param VFS - A llvm::vfs::FileSystem to be used for all file accesses. + /// Note that preamble is saved to a temporary directory on a RealFileSystem, + /// so in order for it to be loaded correctly, VFS should have access to + /// it(i.e., be an overlay over RealFileSystem). /// /// \returns \c true if a catastrophic failure occurred (which means that the /// \c ASTUnit itself is invalid), or \c false otherwise. bool LoadFromCompilerInvocation( std::shared_ptr PCHContainerOps, unsigned PrecompilePreambleAfterNParses, - IntrusiveRefCntPtr VFS); + IntrusiveRefCntPtr VFS); public: /// Create an ASTUnit from a source file, via a CompilerInvocation @@ -798,10 +797,11 @@ /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit /// mainly to allow the caller to see the diagnostics. /// - /// \param VFS - A vfs::FileSystem to be used for all file accesses. Note that - /// preamble is saved to a temporary directory on a RealFileSystem, so in order - /// for it to be loaded correctly, VFS should have access to it(i.e., be an - /// overlay over RealFileSystem). RealFileSystem will be used if \p VFS is nullptr. + /// \param VFS - A llvm::vfs::FileSystem to be used for all file accesses. + /// Note that preamble is saved to a temporary directory on a RealFileSystem, + /// so in order for it to be loaded correctly, VFS should have access to + /// it(i.e., be an overlay over RealFileSystem). RealFileSystem will be used + /// if \p VFS is nullptr. /// // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we // shouldn't need to specify them at construction time. @@ -823,22 +823,22 @@ bool ForSerialization = false, llvm::Optional ModuleFormat = llvm::None, std::unique_ptr *ErrAST = nullptr, - IntrusiveRefCntPtr VFS = nullptr); + IntrusiveRefCntPtr VFS = nullptr); /// Reparse the source files using the same command-line options that /// were originally used to produce this translation unit. /// - /// \param VFS - A vfs::FileSystem to be used for all file accesses. Note that - /// preamble is saved to a temporary directory on a RealFileSystem, so in order - /// for it to be loaded correctly, VFS should give an access to this(i.e. be an - /// overlay over RealFileSystem). FileMgr->getVirtualFileSystem() will be used if - /// \p VFS is nullptr. + /// \param VFS - A llvm::vfs::FileSystem to be used for all file accesses. + /// Note that preamble is saved to a temporary directory on a RealFileSystem, + /// so in order for it to be loaded correctly, VFS should give an access to + /// this(i.e. be an overlay over RealFileSystem). + /// FileMgr->getVirtualFileSystem() will be used if \p VFS is nullptr. /// /// \returns True if a failure occurred that causes the ASTUnit not to /// contain any translation-unit information, false otherwise. bool Reparse(std::shared_ptr PCHContainerOps, ArrayRef RemappedFiles = None, - IntrusiveRefCntPtr VFS = nullptr); + IntrusiveRefCntPtr VFS = nullptr); /// Free data that will be re-generated on the next parse. /// Index: cfe/trunk/include/clang/Frontend/CompilerInstance.h =================================================================== --- cfe/trunk/include/clang/Frontend/CompilerInstance.h +++ cfe/trunk/include/clang/Frontend/CompilerInstance.h @@ -83,7 +83,7 @@ IntrusiveRefCntPtr AuxTarget; /// The virtual file system. - IntrusiveRefCntPtr VirtualFileSystem; + IntrusiveRefCntPtr VirtualFileSystem; /// The file manager. IntrusiveRefCntPtr FileMgr; @@ -384,7 +384,7 @@ bool hasVirtualFileSystem() const { return VirtualFileSystem != nullptr; } - vfs::FileSystem &getVirtualFileSystem() const { + llvm::vfs::FileSystem &getVirtualFileSystem() const { assert(hasVirtualFileSystem() && "Compiler instance has no virtual file system"); return *VirtualFileSystem; @@ -394,7 +394,7 @@ /// /// \note Most clients should use setFileManager, which will implicitly reset /// the virtual file system to the one contained in the file manager. - void setVirtualFileSystem(IntrusiveRefCntPtr FS) { + void setVirtualFileSystem(IntrusiveRefCntPtr FS) { VirtualFileSystem = std::move(FS); } Index: cfe/trunk/include/clang/Frontend/CompilerInvocation.h =================================================================== --- cfe/trunk/include/clang/Frontend/CompilerInvocation.h +++ cfe/trunk/include/clang/Frontend/CompilerInvocation.h @@ -35,6 +35,12 @@ } // namespace opt +namespace vfs { + +class FileSystem; + +} // namespace vfs + } // namespace llvm namespace clang { @@ -217,20 +223,13 @@ /// @} }; -namespace vfs { - -class FileSystem; - -} // namespace vfs - -IntrusiveRefCntPtr +IntrusiveRefCntPtr createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags); -IntrusiveRefCntPtr -createVFSFromCompilerInvocation(const CompilerInvocation &CI, - DiagnosticsEngine &Diags, - IntrusiveRefCntPtr BaseFS); +IntrusiveRefCntPtr createVFSFromCompilerInvocation( + const CompilerInvocation &CI, DiagnosticsEngine &Diags, + IntrusiveRefCntPtr BaseFS); } // namespace clang Index: cfe/trunk/include/clang/Frontend/PrecompiledPreamble.h =================================================================== --- cfe/trunk/include/clang/Frontend/PrecompiledPreamble.h +++ cfe/trunk/include/clang/Frontend/PrecompiledPreamble.h @@ -26,13 +26,12 @@ namespace llvm { class MemoryBuffer; -} - -namespace clang { namespace vfs { class FileSystem; } +} // namespace llvm +namespace clang { class CompilerInstance; class CompilerInvocation; class DeclGroupRef; @@ -80,7 +79,8 @@ static llvm::ErrorOr Build(const CompilerInvocation &Invocation, const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, - DiagnosticsEngine &Diagnostics, IntrusiveRefCntPtr VFS, + DiagnosticsEngine &Diagnostics, + IntrusiveRefCntPtr VFS, std::shared_ptr PCHContainerOps, bool StoreInMemory, PreambleCallbacks &Callbacks); @@ -99,7 +99,7 @@ /// MainFileBuffer) of the main file. bool CanReuse(const CompilerInvocation &Invocation, const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, - vfs::FileSystem *VFS) const; + llvm::vfs::FileSystem *VFS) const; /// Changes options inside \p CI to use PCH from this preamble. Also remaps /// main file to \p MainFileBuffer and updates \p VFS to ensure the preamble @@ -110,14 +110,14 @@ /// responsible for making sure the PrecompiledPreamble instance outlives the /// compiler run and the AST that will be using the PCH. void AddImplicitPreamble(CompilerInvocation &CI, - IntrusiveRefCntPtr &VFS, + IntrusiveRefCntPtr &VFS, llvm::MemoryBuffer *MainFileBuffer) const; /// Configure \p CI to use this preamble. /// Like AddImplicitPreamble, but doesn't assume CanReuse() is true. /// If this preamble does not match the file, it may parse differently. void OverridePreamble(CompilerInvocation &CI, - IntrusiveRefCntPtr &VFS, + IntrusiveRefCntPtr &VFS, llvm::MemoryBuffer *MainFileBuffer) const; private: @@ -233,15 +233,16 @@ /// Helper function to set up PCH for the preamble into \p CI and \p VFS to /// with the specified \p Bounds. void configurePreamble(PreambleBounds Bounds, CompilerInvocation &CI, - IntrusiveRefCntPtr &VFS, + IntrusiveRefCntPtr &VFS, llvm::MemoryBuffer *MainFileBuffer) const; /// Sets up the PreprocessorOptions and changes VFS, so that PCH stored in \p /// Storage is accessible to clang. This method is an implementation detail of /// AddImplicitPreamble. - static void setupPreambleStorage(const PCHStorage &Storage, - PreprocessorOptions &PreprocessorOpts, - IntrusiveRefCntPtr &VFS); + static void + setupPreambleStorage(const PCHStorage &Storage, + PreprocessorOptions &PreprocessorOpts, + IntrusiveRefCntPtr &VFS); /// Manages the memory buffer or temporary file that stores the PCH. PCHStorage Storage; Index: cfe/trunk/include/clang/Frontend/Utils.h =================================================================== --- cfe/trunk/include/clang/Frontend/Utils.h +++ cfe/trunk/include/clang/Frontend/Utils.h @@ -16,13 +16,13 @@ #include "clang/Basic/Diagnostic.h" #include "clang/Basic/LLVM.h" -#include "clang/Basic/VirtualFileSystem.h" -#include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSet.h" #include "llvm/Option/OptSpecifier.h" +#include "llvm/Support/VirtualFileSystem.h" #include #include #include @@ -134,7 +134,7 @@ std::string DestDir; bool HasErrors = false; llvm::StringSet<> Seen; - vfs::YAMLVFSWriter VFSWriter; + llvm::vfs::YAMLVFSWriter VFSWriter; llvm::StringMap SymLinkMap; bool getRealPath(StringRef SrcPath, SmallVectorImpl &Result); @@ -201,7 +201,7 @@ ArrayRef Args, IntrusiveRefCntPtr Diags = IntrusiveRefCntPtr(), - IntrusiveRefCntPtr VFS = nullptr); + IntrusiveRefCntPtr VFS = nullptr); /// Return the value of the last argument as an integer, or a default. If Diags /// is non-null, emits an error if the argument is given, but non-integral. Index: cfe/trunk/include/clang/Tooling/StandaloneExecution.h =================================================================== --- cfe/trunk/include/clang/Tooling/StandaloneExecution.h +++ cfe/trunk/include/clang/Tooling/StandaloneExecution.h @@ -37,7 +37,8 @@ StandaloneToolExecutor( const CompilationDatabase &Compilations, llvm::ArrayRef SourcePaths, - IntrusiveRefCntPtr BaseFS = vfs::getRealFileSystem(), + IntrusiveRefCntPtr BaseFS = + llvm::vfs::getRealFileSystem(), std::shared_ptr PCHContainerOps = std::make_shared()); Index: cfe/trunk/include/clang/Tooling/Tooling.h =================================================================== --- cfe/trunk/include/clang/Tooling/Tooling.h +++ cfe/trunk/include/clang/Tooling/Tooling.h @@ -33,7 +33,6 @@ #include "clang/AST/ASTConsumer.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/LLVM.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Frontend/FrontendAction.h" #include "clang/Frontend/PCHContainerOperations.h" #include "clang/Tooling/ArgumentsAdjusters.h" @@ -44,6 +43,7 @@ #include "llvm/ADT/StringSet.h" #include "llvm/ADT/Twine.h" #include "llvm/Option/Option.h" +#include "llvm/Support/VirtualFileSystem.h" #include #include #include @@ -190,7 +190,7 @@ // Similar to the overload except this takes a VFS. bool runToolOnCodeWithArgs( FrontendAction *ToolAction, const Twine &Code, - llvm::IntrusiveRefCntPtr VFS, + llvm::IntrusiveRefCntPtr VFS, const std::vector &Args, const Twine &FileName = "input.cc", const Twine &ToolName = "clang-tool", std::shared_ptr PCHContainerOps = @@ -319,8 +319,8 @@ ArrayRef SourcePaths, std::shared_ptr PCHContainerOps = std::make_shared(), - IntrusiveRefCntPtr BaseFS = - vfs::getRealFileSystem()); + IntrusiveRefCntPtr BaseFS = + llvm::vfs::getRealFileSystem()); ~ClangTool(); @@ -373,8 +373,8 @@ std::vector SourcePaths; std::shared_ptr PCHContainerOps; - llvm::IntrusiveRefCntPtr OverlayFileSystem; - llvm::IntrusiveRefCntPtr InMemoryFileSystem; + llvm::IntrusiveRefCntPtr OverlayFileSystem; + llvm::IntrusiveRefCntPtr InMemoryFileSystem; llvm::IntrusiveRefCntPtr Files; // Contains a list of pairs (, ). @@ -467,7 +467,7 @@ std::string getAbsolutePath(StringRef File); /// An overload of getAbsolutePath that works over the provided \p FS. -llvm::Expected getAbsolutePath(vfs::FileSystem &FS, +llvm::Expected getAbsolutePath(llvm::vfs::FileSystem &FS, StringRef File); /// Changes CommandLine to contain implicit flags that would have been Index: cfe/trunk/lib/Basic/CMakeLists.txt =================================================================== --- cfe/trunk/lib/Basic/CMakeLists.txt +++ cfe/trunk/lib/Basic/CMakeLists.txt @@ -94,7 +94,6 @@ Targets/XCore.cpp TokenKinds.cpp Version.cpp - VirtualFileSystem.cpp Warnings.cpp XRayInstr.cpp XRayLists.cpp Index: cfe/trunk/lib/Basic/FileManager.cpp =================================================================== --- cfe/trunk/lib/Basic/FileManager.cpp +++ cfe/trunk/lib/Basic/FileManager.cpp @@ -49,7 +49,7 @@ //===----------------------------------------------------------------------===// FileManager::FileManager(const FileSystemOptions &FSO, - IntrusiveRefCntPtr FS) + IntrusiveRefCntPtr FS) : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) { NumDirLookups = NumFileLookups = 0; @@ -58,7 +58,7 @@ // If the caller doesn't provide a virtual file system, just grab the real // file system. if (!this->FS) - this->FS = vfs::getRealFileSystem(); + this->FS = llvm::vfs::getRealFileSystem(); } FileManager::~FileManager() = default; @@ -252,7 +252,7 @@ // FIXME: This will reduce the # syscalls. // Nope, there isn't. Check to see if the file exists. - std::unique_ptr F; + std::unique_ptr F; FileData Data; if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) { // There's no real file at the given path. @@ -475,7 +475,7 @@ /// false if it's an existent real file. If FileDescriptor is NULL, /// do directory look-up instead of file look-up. bool FileManager::getStatValue(StringRef Path, FileData &Data, bool isFile, - std::unique_ptr *F) { + std::unique_ptr *F) { // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be // absolute! if (FileSystemOpts.WorkingDir.empty()) @@ -489,11 +489,11 @@ } bool FileManager::getNoncachedStatValue(StringRef Path, - vfs::Status &Result) { + llvm::vfs::Status &Result) { SmallString<128> FilePath(Path); FixupRelativePath(FilePath); - llvm::ErrorOr S = FS->status(FilePath.c_str()); + llvm::ErrorOr S = FS->status(FilePath.c_str()); if (!S) return true; Result = *S; Index: cfe/trunk/lib/Basic/FileSystemStatCache.cpp =================================================================== --- cfe/trunk/lib/Basic/FileSystemStatCache.cpp +++ cfe/trunk/lib/Basic/FileSystemStatCache.cpp @@ -12,17 +12,17 @@ //===----------------------------------------------------------------------===// #include "clang/Basic/FileSystemStatCache.h" -#include "clang/Basic/VirtualFileSystem.h" #include "llvm/Support/Chrono.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/Path.h" +#include "llvm/Support/VirtualFileSystem.h" #include using namespace clang; void FileSystemStatCache::anchor() {} -static void copyStatusToFileData(const vfs::Status &Status, +static void copyStatusToFileData(const llvm::vfs::Status &Status, FileData &Data) { Data.Name = Status.getName(); Data.Size = Status.getSize(); @@ -44,8 +44,9 @@ /// implementation can optionally fill in FileDescriptor with a valid /// descriptor and the client guarantees that it will close it. bool FileSystemStatCache::get(StringRef Path, FileData &Data, bool isFile, - std::unique_ptr *F, - FileSystemStatCache *Cache, vfs::FileSystem &FS) { + std::unique_ptr *F, + FileSystemStatCache *Cache, + llvm::vfs::FileSystem &FS) { LookupResult R; bool isForDir = !isFile; @@ -55,7 +56,7 @@ else if (isForDir || !F) { // If this is a directory or a file descriptor is not needed and we have // no cache, just go to the file system. - llvm::ErrorOr Status = FS.status(Path); + llvm::ErrorOr Status = FS.status(Path); if (!Status) { R = CacheMissing; } else { @@ -79,7 +80,7 @@ // Otherwise, the open succeeded. Do an fstat to get the information // about the file. We'll end up returning the open file descriptor to the // client to do what they please with it. - llvm::ErrorOr Status = (*OwnedFile)->status(); + llvm::ErrorOr Status = (*OwnedFile)->status(); if (Status) { R = CacheExists; copyStatusToFileData(*Status, Data); @@ -111,7 +112,8 @@ MemorizeStatCalls::LookupResult MemorizeStatCalls::getStat(StringRef Path, FileData &Data, bool isFile, - std::unique_ptr *F, vfs::FileSystem &FS) { + std::unique_ptr *F, + llvm::vfs::FileSystem &FS) { LookupResult Result = statChained(Path, Data, isFile, F, FS); // Do not cache failed stats, it is easy to construct common inconsistent Index: cfe/trunk/lib/Basic/SourceManager.cpp =================================================================== --- cfe/trunk/lib/Basic/SourceManager.cpp +++ cfe/trunk/lib/Basic/SourceManager.cpp @@ -2263,8 +2263,8 @@ StringRef Content) { // This is referenced by `FileMgr` and will be released by `FileMgr` when it // is deleted. - IntrusiveRefCntPtr InMemoryFileSystem( - new vfs::InMemoryFileSystem); + IntrusiveRefCntPtr InMemoryFileSystem( + new llvm::vfs::InMemoryFileSystem); InMemoryFileSystem->addFile( FileName, 0, llvm::MemoryBuffer::getMemBuffer(Content, FileName, Index: cfe/trunk/lib/Basic/VirtualFileSystem.cpp =================================================================== --- cfe/trunk/lib/Basic/VirtualFileSystem.cpp +++ cfe/trunk/lib/Basic/VirtualFileSystem.cpp @@ -1,2142 +0,0 @@ -//===- VirtualFileSystem.cpp - Virtual File System Layer ------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file implements the VirtualFileSystem interface. -// -//===----------------------------------------------------------------------===// - -#include "clang/Basic/VirtualFileSystem.h" -#include "clang/Basic/LLVM.h" -#include "llvm/ADT/ArrayRef.h" -#include "llvm/ADT/DenseMap.h" -#include "llvm/ADT/IntrusiveRefCntPtr.h" -#include "llvm/ADT/None.h" -#include "llvm/ADT/Optional.h" -#include "llvm/ADT/STLExtras.h" -#include "llvm/ADT/SmallString.h" -#include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/StringRef.h" -#include "llvm/ADT/StringSet.h" -#include "llvm/ADT/Twine.h" -#include "llvm/ADT/iterator_range.h" -#include "llvm/Config/llvm-config.h" -#include "llvm/Support/Casting.h" -#include "llvm/Support/Chrono.h" -#include "llvm/Support/Compiler.h" -#include "llvm/Support/Debug.h" -#include "llvm/Support/Errc.h" -#include "llvm/Support/ErrorHandling.h" -#include "llvm/Support/ErrorOr.h" -#include "llvm/Support/FileSystem.h" -#include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/Path.h" -#include "llvm/Support/Process.h" -#include "llvm/Support/SMLoc.h" -#include "llvm/Support/SourceMgr.h" -#include "llvm/Support/YAMLParser.h" -#include "llvm/Support/raw_ostream.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace clang; -using namespace vfs; -using namespace llvm; - -using llvm::sys::fs::file_status; -using llvm::sys::fs::file_type; -using llvm::sys::fs::perms; -using llvm::sys::fs::UniqueID; - -Status::Status(const file_status &Status) - : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()), - User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()), - Type(Status.type()), Perms(Status.permissions()) {} - -Status::Status(StringRef Name, UniqueID UID, sys::TimePoint<> MTime, - uint32_t User, uint32_t Group, uint64_t Size, file_type Type, - perms Perms) - : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size), - Type(Type), Perms(Perms) {} - -Status Status::copyWithNewName(const Status &In, StringRef NewName) { - return Status(NewName, In.getUniqueID(), In.getLastModificationTime(), - In.getUser(), In.getGroup(), In.getSize(), In.getType(), - In.getPermissions()); -} - -Status Status::copyWithNewName(const file_status &In, StringRef NewName) { - return Status(NewName, In.getUniqueID(), In.getLastModificationTime(), - In.getUser(), In.getGroup(), In.getSize(), In.type(), - In.permissions()); -} - -bool Status::equivalent(const Status &Other) const { - assert(isStatusKnown() && Other.isStatusKnown()); - return getUniqueID() == Other.getUniqueID(); -} - -bool Status::isDirectory() const { - return Type == file_type::directory_file; -} - -bool Status::isRegularFile() const { - return Type == file_type::regular_file; -} - -bool Status::isOther() const { - return exists() && !isRegularFile() && !isDirectory() && !isSymlink(); -} - -bool Status::isSymlink() const { - return Type == file_type::symlink_file; -} - -bool Status::isStatusKnown() const { - return Type != file_type::status_error; -} - -bool Status::exists() const { - return isStatusKnown() && Type != file_type::file_not_found; -} - -File::~File() = default; - -FileSystem::~FileSystem() = default; - -ErrorOr> -FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize, - bool RequiresNullTerminator, bool IsVolatile) { - auto F = openFileForRead(Name); - if (!F) - return F.getError(); - - return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile); -} - -std::error_code FileSystem::makeAbsolute(SmallVectorImpl &Path) const { - if (llvm::sys::path::is_absolute(Path)) - return {}; - - auto WorkingDir = getCurrentWorkingDirectory(); - if (!WorkingDir) - return WorkingDir.getError(); - - return llvm::sys::fs::make_absolute(WorkingDir.get(), Path); -} - -std::error_code FileSystem::getRealPath(const Twine &Path, - SmallVectorImpl &Output) const { - return errc::operation_not_permitted; -} - -bool FileSystem::exists(const Twine &Path) { - auto Status = status(Path); - return Status && Status->exists(); -} - -#ifndef NDEBUG -static bool isTraversalComponent(StringRef Component) { - return Component.equals("..") || Component.equals("."); -} - -static bool pathHasTraversal(StringRef Path) { - using namespace llvm::sys; - - for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path))) - if (isTraversalComponent(Comp)) - return true; - return false; -} -#endif - -//===-----------------------------------------------------------------------===/ -// RealFileSystem implementation -//===-----------------------------------------------------------------------===/ - -namespace { - -/// Wrapper around a raw file descriptor. -class RealFile : public File { - friend class RealFileSystem; - - int FD; - Status S; - std::string RealName; - - RealFile(int FD, StringRef NewName, StringRef NewRealPathName) - : FD(FD), S(NewName, {}, {}, {}, {}, {}, - llvm::sys::fs::file_type::status_error, {}), - RealName(NewRealPathName.str()) { - assert(FD >= 0 && "Invalid or inactive file descriptor"); - } - -public: - ~RealFile() override; - - ErrorOr status() override; - ErrorOr getName() override; - ErrorOr> getBuffer(const Twine &Name, - int64_t FileSize, - bool RequiresNullTerminator, - bool IsVolatile) override; - std::error_code close() override; -}; - -} // namespace - -RealFile::~RealFile() { close(); } - -ErrorOr RealFile::status() { - assert(FD != -1 && "cannot stat closed file"); - if (!S.isStatusKnown()) { - file_status RealStatus; - if (std::error_code EC = sys::fs::status(FD, RealStatus)) - return EC; - S = Status::copyWithNewName(RealStatus, S.getName()); - } - return S; -} - -ErrorOr RealFile::getName() { - return RealName.empty() ? S.getName().str() : RealName; -} - -ErrorOr> -RealFile::getBuffer(const Twine &Name, int64_t FileSize, - bool RequiresNullTerminator, bool IsVolatile) { - assert(FD != -1 && "cannot get buffer for closed file"); - return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator, - IsVolatile); -} - -std::error_code RealFile::close() { - std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD); - FD = -1; - return EC; -} - -namespace { - -/// The file system according to your operating system. -class RealFileSystem : public FileSystem { -public: - ErrorOr status(const Twine &Path) override; - ErrorOr> openFileForRead(const Twine &Path) override; - directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override; - - llvm::ErrorOr getCurrentWorkingDirectory() const override; - std::error_code setCurrentWorkingDirectory(const Twine &Path) override; - std::error_code getRealPath(const Twine &Path, - SmallVectorImpl &Output) const override; -private: - mutable std::mutex CWDMutex; - mutable std::string CWDCache; -}; - -} // namespace - -ErrorOr RealFileSystem::status(const Twine &Path) { - sys::fs::file_status RealStatus; - if (std::error_code EC = sys::fs::status(Path, RealStatus)) - return EC; - return Status::copyWithNewName(RealStatus, Path.str()); -} - -ErrorOr> -RealFileSystem::openFileForRead(const Twine &Name) { - int FD; - SmallString<256> RealName; - if (std::error_code EC = - sys::fs::openFileForRead(Name, FD, sys::fs::OF_None, &RealName)) - return EC; - return std::unique_ptr(new RealFile(FD, Name.str(), RealName.str())); -} - -llvm::ErrorOr RealFileSystem::getCurrentWorkingDirectory() const { - std::lock_guard Lock(CWDMutex); - if (!CWDCache.empty()) - return CWDCache; - SmallString<256> Dir; - if (std::error_code EC = llvm::sys::fs::current_path(Dir)) - return EC; - CWDCache = Dir.str(); - return CWDCache; -} - -std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) { - // FIXME: chdir is thread hostile; on the other hand, creating the same - // behavior as chdir is complex: chdir resolves the path once, thus - // guaranteeing that all subsequent relative path operations work - // on the same path the original chdir resulted in. This makes a - // difference for example on network filesystems, where symlinks might be - // switched during runtime of the tool. Fixing this depends on having a - // file system abstraction that allows openat() style interactions. - if (auto EC = llvm::sys::fs::set_current_path(Path)) - return EC; - - // Invalidate cache. - std::lock_guard Lock(CWDMutex); - CWDCache.clear(); - return std::error_code(); -} - -std::error_code -RealFileSystem::getRealPath(const Twine &Path, - SmallVectorImpl &Output) const { - return llvm::sys::fs::real_path(Path, Output); -} - -IntrusiveRefCntPtr vfs::getRealFileSystem() { - static IntrusiveRefCntPtr FS = new RealFileSystem(); - return FS; -} - -namespace { - -class RealFSDirIter : public clang::vfs::detail::DirIterImpl { - llvm::sys::fs::directory_iterator Iter; - -public: - RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) { - if (Iter != llvm::sys::fs::directory_iterator()) - CurrentEntry = directory_entry(Iter->path(), Iter->type()); - } - - std::error_code increment() override { - std::error_code EC; - Iter.increment(EC); - CurrentEntry = (Iter == llvm::sys::fs::directory_iterator()) - ? directory_entry() - : directory_entry(Iter->path(), Iter->type()); - return EC; - } -}; - -} // namespace - -directory_iterator RealFileSystem::dir_begin(const Twine &Dir, - std::error_code &EC) { - return directory_iterator(std::make_shared(Dir, EC)); -} - -//===-----------------------------------------------------------------------===/ -// OverlayFileSystem implementation -//===-----------------------------------------------------------------------===/ - -OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr BaseFS) { - FSList.push_back(std::move(BaseFS)); -} - -void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr FS) { - FSList.push_back(FS); - // Synchronize added file systems by duplicating the working directory from - // the first one in the list. - FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get()); -} - -ErrorOr OverlayFileSystem::status(const Twine &Path) { - // FIXME: handle symlinks that cross file systems - for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) { - ErrorOr Status = (*I)->status(Path); - if (Status || Status.getError() != llvm::errc::no_such_file_or_directory) - return Status; - } - return make_error_code(llvm::errc::no_such_file_or_directory); -} - -ErrorOr> -OverlayFileSystem::openFileForRead(const llvm::Twine &Path) { - // FIXME: handle symlinks that cross file systems - for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) { - auto Result = (*I)->openFileForRead(Path); - if (Result || Result.getError() != llvm::errc::no_such_file_or_directory) - return Result; - } - return make_error_code(llvm::errc::no_such_file_or_directory); -} - -llvm::ErrorOr -OverlayFileSystem::getCurrentWorkingDirectory() const { - // All file systems are synchronized, just take the first working directory. - return FSList.front()->getCurrentWorkingDirectory(); -} - -std::error_code -OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) { - for (auto &FS : FSList) - if (std::error_code EC = FS->setCurrentWorkingDirectory(Path)) - return EC; - return {}; -} - -std::error_code -OverlayFileSystem::getRealPath(const Twine &Path, - SmallVectorImpl &Output) const { - for (auto &FS : FSList) - if (FS->exists(Path)) - return FS->getRealPath(Path, Output); - return errc::no_such_file_or_directory; -} - -clang::vfs::detail::DirIterImpl::~DirIterImpl() = default; - -namespace { - -class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl { - OverlayFileSystem &Overlays; - std::string Path; - OverlayFileSystem::iterator CurrentFS; - directory_iterator CurrentDirIter; - llvm::StringSet<> SeenNames; - - std::error_code incrementFS() { - assert(CurrentFS != Overlays.overlays_end() && "incrementing past end"); - ++CurrentFS; - for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) { - std::error_code EC; - CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC); - if (EC && EC != errc::no_such_file_or_directory) - return EC; - if (CurrentDirIter != directory_iterator()) - break; // found - } - return {}; - } - - std::error_code incrementDirIter(bool IsFirstTime) { - assert((IsFirstTime || CurrentDirIter != directory_iterator()) && - "incrementing past end"); - std::error_code EC; - if (!IsFirstTime) - CurrentDirIter.increment(EC); - if (!EC && CurrentDirIter == directory_iterator()) - EC = incrementFS(); - return EC; - } - - std::error_code incrementImpl(bool IsFirstTime) { - while (true) { - std::error_code EC = incrementDirIter(IsFirstTime); - if (EC || CurrentDirIter == directory_iterator()) { - CurrentEntry = directory_entry(); - return EC; - } - CurrentEntry = *CurrentDirIter; - StringRef Name = llvm::sys::path::filename(CurrentEntry.path()); - if (SeenNames.insert(Name).second) - return EC; // name not seen before - } - llvm_unreachable("returned above"); - } - -public: - OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS, - std::error_code &EC) - : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) { - CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC); - EC = incrementImpl(true); - } - - std::error_code increment() override { return incrementImpl(false); } -}; - -} // namespace - -directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir, - std::error_code &EC) { - return directory_iterator( - std::make_shared(Dir, *this, EC)); -} - -namespace clang { -namespace vfs { - -namespace detail { - -enum InMemoryNodeKind { IME_File, IME_Directory, IME_HardLink }; - -/// The in memory file system is a tree of Nodes. Every node can either be a -/// file , hardlink or a directory. -class InMemoryNode { - InMemoryNodeKind Kind; - std::string FileName; - -public: - InMemoryNode(llvm::StringRef FileName, InMemoryNodeKind Kind) - : Kind(Kind), FileName(llvm::sys::path::filename(FileName)) {} - virtual ~InMemoryNode() = default; - - /// Get the filename of this node (the name without the directory part). - StringRef getFileName() const { return FileName; } - InMemoryNodeKind getKind() const { return Kind; } - virtual std::string toString(unsigned Indent) const = 0; -}; - -class InMemoryFile : public InMemoryNode { - Status Stat; - std::unique_ptr Buffer; - -public: - InMemoryFile(Status Stat, std::unique_ptr Buffer) - : InMemoryNode(Stat.getName(), IME_File), Stat(std::move(Stat)), - Buffer(std::move(Buffer)) {} - - /// Return the \p Status for this node. \p RequestedName should be the name - /// through which the caller referred to this node. It will override - /// \p Status::Name in the return value, to mimic the behavior of \p RealFile. - Status getStatus(StringRef RequestedName) const { - return Status::copyWithNewName(Stat, RequestedName); - } - llvm::MemoryBuffer *getBuffer() const { return Buffer.get(); } - - std::string toString(unsigned Indent) const override { - return (std::string(Indent, ' ') + Stat.getName() + "\n").str(); - } - - static bool classof(const InMemoryNode *N) { - return N->getKind() == IME_File; - } -}; - -namespace { - -class InMemoryHardLink : public InMemoryNode { - const InMemoryFile &ResolvedFile; - -public: - InMemoryHardLink(StringRef Path, const InMemoryFile &ResolvedFile) - : InMemoryNode(Path, IME_HardLink), ResolvedFile(ResolvedFile) {} - const InMemoryFile &getResolvedFile() const { return ResolvedFile; } - - std::string toString(unsigned Indent) const override { - return std::string(Indent, ' ') + "HardLink to -> " + - ResolvedFile.toString(0); - } - - static bool classof(const InMemoryNode *N) { - return N->getKind() == IME_HardLink; - } -}; - -/// Adapt a InMemoryFile for VFS' File interface. The goal is to make -/// \p InMemoryFileAdaptor mimic as much as possible the behavior of -/// \p RealFile. -class InMemoryFileAdaptor : public File { - const InMemoryFile &Node; - /// The name to use when returning a Status for this file. - std::string RequestedName; - -public: - explicit InMemoryFileAdaptor(const InMemoryFile &Node, - std::string RequestedName) - : Node(Node), RequestedName(std::move(RequestedName)) {} - - llvm::ErrorOr status() override { - return Node.getStatus(RequestedName); - } - - llvm::ErrorOr> - getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator, - bool IsVolatile) override { - llvm::MemoryBuffer *Buf = Node.getBuffer(); - return llvm::MemoryBuffer::getMemBuffer( - Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator); - } - - std::error_code close() override { return {}; } -}; -} // namespace - -class InMemoryDirectory : public InMemoryNode { - Status Stat; - llvm::StringMap> Entries; - -public: - InMemoryDirectory(Status Stat) - : InMemoryNode(Stat.getName(), IME_Directory), Stat(std::move(Stat)) {} - - /// Return the \p Status for this node. \p RequestedName should be the name - /// through which the caller referred to this node. It will override - /// \p Status::Name in the return value, to mimic the behavior of \p RealFile. - Status getStatus(StringRef RequestedName) const { - return Status::copyWithNewName(Stat, RequestedName); - } - InMemoryNode *getChild(StringRef Name) { - auto I = Entries.find(Name); - if (I != Entries.end()) - return I->second.get(); - return nullptr; - } - - InMemoryNode *addChild(StringRef Name, std::unique_ptr Child) { - return Entries.insert(make_pair(Name, std::move(Child))) - .first->second.get(); - } - - using const_iterator = decltype(Entries)::const_iterator; - - const_iterator begin() const { return Entries.begin(); } - const_iterator end() const { return Entries.end(); } - - std::string toString(unsigned Indent) const override { - std::string Result = - (std::string(Indent, ' ') + Stat.getName() + "\n").str(); - for (const auto &Entry : Entries) - Result += Entry.second->toString(Indent + 2); - return Result; - } - - static bool classof(const InMemoryNode *N) { - return N->getKind() == IME_Directory; - } -}; - -namespace { -Status getNodeStatus(const InMemoryNode *Node, StringRef RequestedName) { - if (auto Dir = dyn_cast(Node)) - return Dir->getStatus(RequestedName); - if (auto File = dyn_cast(Node)) - return File->getStatus(RequestedName); - if (auto Link = dyn_cast(Node)) - return Link->getResolvedFile().getStatus(RequestedName); - llvm_unreachable("Unknown node type"); -} -} // namespace -} // namespace detail - -InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths) - : Root(new detail::InMemoryDirectory( - Status("", getNextVirtualUniqueID(), llvm::sys::TimePoint<>(), 0, 0, - 0, llvm::sys::fs::file_type::directory_file, - llvm::sys::fs::perms::all_all))), - UseNormalizedPaths(UseNormalizedPaths) {} - -InMemoryFileSystem::~InMemoryFileSystem() = default; - -std::string InMemoryFileSystem::toString() const { - return Root->toString(/*Indent=*/0); -} - -bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime, - std::unique_ptr Buffer, - Optional User, - Optional Group, - Optional Type, - Optional Perms, - const detail::InMemoryFile *HardLinkTarget) { - SmallString<128> Path; - P.toVector(Path); - - // Fix up relative paths. This just prepends the current working directory. - std::error_code EC = makeAbsolute(Path); - assert(!EC); - (void)EC; - - if (useNormalizedPaths()) - llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true); - - if (Path.empty()) - return false; - - detail::InMemoryDirectory *Dir = Root.get(); - auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path); - const auto ResolvedUser = User.getValueOr(0); - const auto ResolvedGroup = Group.getValueOr(0); - const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file); - const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all); - assert(!(HardLinkTarget && Buffer) && "HardLink cannot have a buffer"); - // Any intermediate directories we create should be accessible by - // the owner, even if Perms says otherwise for the final path. - const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all; - while (true) { - StringRef Name = *I; - detail::InMemoryNode *Node = Dir->getChild(Name); - ++I; - if (!Node) { - if (I == E) { - // End of the path. - std::unique_ptr Child; - if (HardLinkTarget) - Child.reset(new detail::InMemoryHardLink(P.str(), *HardLinkTarget)); - else { - // Create a new file or directory. - Status Stat(P.str(), getNextVirtualUniqueID(), - llvm::sys::toTimePoint(ModificationTime), ResolvedUser, - ResolvedGroup, Buffer->getBufferSize(), ResolvedType, - ResolvedPerms); - if (ResolvedType == sys::fs::file_type::directory_file) { - Child.reset(new detail::InMemoryDirectory(std::move(Stat))); - } else { - Child.reset( - new detail::InMemoryFile(std::move(Stat), std::move(Buffer))); - } - } - Dir->addChild(Name, std::move(Child)); - return true; - } - - // Create a new directory. Use the path up to here. - Status Stat( - StringRef(Path.str().begin(), Name.end() - Path.str().begin()), - getNextVirtualUniqueID(), llvm::sys::toTimePoint(ModificationTime), - ResolvedUser, ResolvedGroup, 0, sys::fs::file_type::directory_file, - NewDirectoryPerms); - Dir = cast(Dir->addChild( - Name, llvm::make_unique(std::move(Stat)))); - continue; - } - - if (auto *NewDir = dyn_cast(Node)) { - Dir = NewDir; - } else { - assert((isa(Node) || - isa(Node)) && - "Must be either file, hardlink or directory!"); - - // Trying to insert a directory in place of a file. - if (I != E) - return false; - - // Return false only if the new file is different from the existing one. - if (auto Link = dyn_cast(Node)) { - return Link->getResolvedFile().getBuffer()->getBuffer() == - Buffer->getBuffer(); - } - return cast(Node)->getBuffer()->getBuffer() == - Buffer->getBuffer(); - } - } -} - -bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime, - std::unique_ptr Buffer, - Optional User, - Optional Group, - Optional Type, - Optional Perms) { - return addFile(P, ModificationTime, std::move(Buffer), User, Group, Type, - Perms, /*HardLinkTarget=*/nullptr); -} - -bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime, - llvm::MemoryBuffer *Buffer, - Optional User, - Optional Group, - Optional Type, - Optional Perms) { - return addFile(P, ModificationTime, - llvm::MemoryBuffer::getMemBuffer( - Buffer->getBuffer(), Buffer->getBufferIdentifier()), - std::move(User), std::move(Group), std::move(Type), - std::move(Perms)); -} - -static ErrorOr -lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir, - const Twine &P) { - SmallString<128> Path; - P.toVector(Path); - - // Fix up relative paths. This just prepends the current working directory. - std::error_code EC = FS.makeAbsolute(Path); - assert(!EC); - (void)EC; - - if (FS.useNormalizedPaths()) - llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true); - - if (Path.empty()) - return Dir; - - auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path); - while (true) { - detail::InMemoryNode *Node = Dir->getChild(*I); - ++I; - if (!Node) - return errc::no_such_file_or_directory; - - // Return the file if it's at the end of the path. - if (auto File = dyn_cast(Node)) { - if (I == E) - return File; - return errc::no_such_file_or_directory; - } - - // If Node is HardLink then return the resolved file. - if (auto File = dyn_cast(Node)) { - if (I == E) - return &File->getResolvedFile(); - return errc::no_such_file_or_directory; - } - // Traverse directories. - Dir = cast(Node); - if (I == E) - return Dir; - } -} - -bool InMemoryFileSystem::addHardLink(const Twine &FromPath, - const Twine &ToPath) { - auto FromNode = lookupInMemoryNode(*this, Root.get(), FromPath); - auto ToNode = lookupInMemoryNode(*this, Root.get(), ToPath); - // FromPath must not have been added before. ToPath must have been added - // before. Resolved ToPath must be a File. - if (!ToNode || FromNode || !isa(*ToNode)) - return false; - return this->addFile(FromPath, 0, nullptr, None, None, None, None, - cast(*ToNode)); -} - -llvm::ErrorOr InMemoryFileSystem::status(const Twine &Path) { - auto Node = lookupInMemoryNode(*this, Root.get(), Path); - if (Node) - return detail::getNodeStatus(*Node, Path.str()); - return Node.getError(); -} - -llvm::ErrorOr> -InMemoryFileSystem::openFileForRead(const Twine &Path) { - auto Node = lookupInMemoryNode(*this, Root.get(), Path); - if (!Node) - return Node.getError(); - - // When we have a file provide a heap-allocated wrapper for the memory buffer - // to match the ownership semantics for File. - if (auto *F = dyn_cast(*Node)) - return std::unique_ptr( - new detail::InMemoryFileAdaptor(*F, Path.str())); - - // FIXME: errc::not_a_file? - return make_error_code(llvm::errc::invalid_argument); -} - -namespace { - -/// Adaptor from InMemoryDir::iterator to directory_iterator. -class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl { - detail::InMemoryDirectory::const_iterator I; - detail::InMemoryDirectory::const_iterator E; - std::string RequestedDirName; - - void setCurrentEntry() { - if (I != E) { - SmallString<256> Path(RequestedDirName); - llvm::sys::path::append(Path, I->second->getFileName()); - sys::fs::file_type Type; - switch (I->second->getKind()) { - case detail::IME_File: - case detail::IME_HardLink: - Type = sys::fs::file_type::regular_file; - break; - case detail::IME_Directory: - Type = sys::fs::file_type::directory_file; - break; - } - CurrentEntry = directory_entry(Path.str(), Type); - } else { - // When we're at the end, make CurrentEntry invalid and DirIterImpl will - // do the rest. - CurrentEntry = directory_entry(); - } - } - -public: - InMemoryDirIterator() = default; - - explicit InMemoryDirIterator(const detail::InMemoryDirectory &Dir, - std::string RequestedDirName) - : I(Dir.begin()), E(Dir.end()), - RequestedDirName(std::move(RequestedDirName)) { - setCurrentEntry(); - } - - std::error_code increment() override { - ++I; - setCurrentEntry(); - return {}; - } -}; - -} // namespace - -directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir, - std::error_code &EC) { - auto Node = lookupInMemoryNode(*this, Root.get(), Dir); - if (!Node) { - EC = Node.getError(); - return directory_iterator(std::make_shared()); - } - - if (auto *DirNode = dyn_cast(*Node)) - return directory_iterator( - std::make_shared(*DirNode, Dir.str())); - - EC = make_error_code(llvm::errc::not_a_directory); - return directory_iterator(std::make_shared()); -} - -std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) { - SmallString<128> Path; - P.toVector(Path); - - // Fix up relative paths. This just prepends the current working directory. - std::error_code EC = makeAbsolute(Path); - assert(!EC); - (void)EC; - - if (useNormalizedPaths()) - llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true); - - if (!Path.empty()) - WorkingDirectory = Path.str(); - return {}; -} - -std::error_code -InMemoryFileSystem::getRealPath(const Twine &Path, - SmallVectorImpl &Output) const { - auto CWD = getCurrentWorkingDirectory(); - if (!CWD || CWD->empty()) - return errc::operation_not_permitted; - Path.toVector(Output); - if (auto EC = makeAbsolute(Output)) - return EC; - llvm::sys::path::remove_dots(Output, /*remove_dot_dot=*/true); - return {}; -} - -} // namespace vfs -} // namespace clang - -//===-----------------------------------------------------------------------===/ -// RedirectingFileSystem implementation -//===-----------------------------------------------------------------------===/ - -namespace { - -enum EntryKind { - EK_Directory, - EK_File -}; - -/// A single file or directory in the VFS. -class Entry { - EntryKind Kind; - std::string Name; - -public: - Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {} - virtual ~Entry() = default; - - StringRef getName() const { return Name; } - EntryKind getKind() const { return Kind; } -}; - -class RedirectingDirectoryEntry : public Entry { - std::vector> Contents; - Status S; - -public: - RedirectingDirectoryEntry(StringRef Name, - std::vector> Contents, - Status S) - : Entry(EK_Directory, Name), Contents(std::move(Contents)), - S(std::move(S)) {} - RedirectingDirectoryEntry(StringRef Name, Status S) - : Entry(EK_Directory, Name), S(std::move(S)) {} - - Status getStatus() { return S; } - - void addContent(std::unique_ptr Content) { - Contents.push_back(std::move(Content)); - } - - Entry *getLastContent() const { return Contents.back().get(); } - - using iterator = decltype(Contents)::iterator; - - iterator contents_begin() { return Contents.begin(); } - iterator contents_end() { return Contents.end(); } - - static bool classof(const Entry *E) { return E->getKind() == EK_Directory; } -}; - -class RedirectingFileEntry : public Entry { -public: - enum NameKind { - NK_NotSet, - NK_External, - NK_Virtual - }; - -private: - std::string ExternalContentsPath; - NameKind UseName; - -public: - RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath, - NameKind UseName) - : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath), - UseName(UseName) {} - - StringRef getExternalContentsPath() const { return ExternalContentsPath; } - - /// whether to use the external path as the name for this file. - bool useExternalName(bool GlobalUseExternalName) const { - return UseName == NK_NotSet ? GlobalUseExternalName - : (UseName == NK_External); - } - - NameKind getUseName() const { return UseName; } - - static bool classof(const Entry *E) { return E->getKind() == EK_File; } -}; - -class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl { - std::string Dir; - RedirectingDirectoryEntry::iterator Current, End; - - std::error_code incrementImpl(); - -public: - VFSFromYamlDirIterImpl(const Twine &Path, - RedirectingDirectoryEntry::iterator Begin, - RedirectingDirectoryEntry::iterator End, - std::error_code &EC); - - std::error_code increment() override; -}; - -/// A virtual file system parsed from a YAML file. -/// -/// Currently, this class allows creating virtual directories and mapping -/// virtual file paths to existing external files, available in \c ExternalFS. -/// -/// The basic structure of the parsed file is: -/// \verbatim -/// { -/// 'version': , -/// -/// 'roots': [ -/// -/// ] -/// } -/// \endverbatim -/// -/// All configuration options are optional. -/// 'case-sensitive': -/// 'use-external-names': -/// 'overlay-relative': -/// 'ignore-non-existent-contents': -/// -/// Virtual directories are represented as -/// \verbatim -/// { -/// 'type': 'directory', -/// 'name': , -/// 'contents': [ ] -/// } -/// \endverbatim -/// -/// The default attributes for virtual directories are: -/// \verbatim -/// MTime = now() when created -/// Perms = 0777 -/// User = Group = 0 -/// Size = 0 -/// UniqueID = unspecified unique value -/// \endverbatim -/// -/// Re-mapped files are represented as -/// \verbatim -/// { -/// 'type': 'file', -/// 'name': , -/// 'use-external-name': # Optional -/// 'external-contents': -/// } -/// \endverbatim -/// -/// and inherit their attributes from the external contents. -/// -/// In both cases, the 'name' field may contain multiple path components (e.g. -/// /path/to/file). However, any directory that contains more than one child -/// must be uniquely represented by a directory entry. -class RedirectingFileSystem : public vfs::FileSystem { - friend class RedirectingFileSystemParser; - - /// The root(s) of the virtual file system. - std::vector> Roots; - - /// The file system to use for external references. - IntrusiveRefCntPtr ExternalFS; - - /// If IsRelativeOverlay is set, this represents the directory - /// path that should be prefixed to each 'external-contents' entry - /// when reading from YAML files. - std::string ExternalContentsPrefixDir; - - /// @name Configuration - /// @{ - - /// Whether to perform case-sensitive comparisons. - /// - /// Currently, case-insensitive matching only works correctly with ASCII. - bool CaseSensitive = true; - - /// IsRelativeOverlay marks whether a ExternalContentsPrefixDir path must - /// be prefixed in every 'external-contents' when reading from YAML files. - bool IsRelativeOverlay = false; - - /// Whether to use to use the value of 'external-contents' for the - /// names of files. This global value is overridable on a per-file basis. - bool UseExternalNames = true; - - /// Whether an invalid path obtained via 'external-contents' should - /// cause iteration on the VFS to stop. If 'true', the VFS should ignore - /// the entry and continue with the next. Allows YAML files to be shared - /// across multiple compiler invocations regardless of prior existent - /// paths in 'external-contents'. This global value is overridable on a - /// per-file basis. - bool IgnoreNonExistentContents = true; - /// @} - - /// Virtual file paths and external files could be canonicalized without "..", - /// "." and "./" in their paths. FIXME: some unittests currently fail on - /// win32 when using remove_dots and remove_leading_dotslash on paths. - bool UseCanonicalizedPaths = -#ifdef _WIN32 - false; -#else - true; -#endif - -private: - RedirectingFileSystem(IntrusiveRefCntPtr ExternalFS) - : ExternalFS(std::move(ExternalFS)) {} - - /// Looks up the path [Start, End) in \p From, possibly - /// recursing into the contents of \p From if it is a directory. - ErrorOr lookupPath(sys::path::const_iterator Start, - sys::path::const_iterator End, Entry *From); - - /// Get the status of a given an \c Entry. - ErrorOr status(const Twine &Path, Entry *E); - -public: - /// Looks up \p Path in \c Roots. - ErrorOr lookupPath(const Twine &Path); - - /// Parses \p Buffer, which is expected to be in YAML format and - /// returns a virtual file system representing its contents. - static RedirectingFileSystem * - create(std::unique_ptr Buffer, - SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath, - void *DiagContext, IntrusiveRefCntPtr ExternalFS); - - ErrorOr status(const Twine &Path) override; - ErrorOr> openFileForRead(const Twine &Path) override; - - llvm::ErrorOr getCurrentWorkingDirectory() const override { - return ExternalFS->getCurrentWorkingDirectory(); - } - - std::error_code setCurrentWorkingDirectory(const Twine &Path) override { - return ExternalFS->setCurrentWorkingDirectory(Path); - } - - directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{ - ErrorOr E = lookupPath(Dir); - if (!E) { - EC = E.getError(); - return {}; - } - ErrorOr S = status(Dir, *E); - if (!S) { - EC = S.getError(); - return {}; - } - if (!S->isDirectory()) { - EC = std::error_code(static_cast(errc::not_a_directory), - std::system_category()); - return {}; - } - - auto *D = cast(*E); - return directory_iterator(std::make_shared( - Dir, D->contents_begin(), D->contents_end(), EC)); - } - - void setExternalContentsPrefixDir(StringRef PrefixDir) { - ExternalContentsPrefixDir = PrefixDir.str(); - } - - StringRef getExternalContentsPrefixDir() const { - return ExternalContentsPrefixDir; - } - - bool ignoreNonExistentContents() const { - return IgnoreNonExistentContents; - } - -#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) -LLVM_DUMP_METHOD void dump() const { - for (const auto &Root : Roots) - dumpEntry(Root.get()); - } - -LLVM_DUMP_METHOD void dumpEntry(Entry *E, int NumSpaces = 0) const { - StringRef Name = E->getName(); - for (int i = 0, e = NumSpaces; i < e; ++i) - dbgs() << " "; - dbgs() << "'" << Name.str().c_str() << "'" << "\n"; - - if (E->getKind() == EK_Directory) { - auto *DE = dyn_cast(E); - assert(DE && "Should be a directory"); - - for (std::unique_ptr &SubEntry : - llvm::make_range(DE->contents_begin(), DE->contents_end())) - dumpEntry(SubEntry.get(), NumSpaces+2); - } - } -#endif -}; - -/// A helper class to hold the common YAML parsing state. -class RedirectingFileSystemParser { - yaml::Stream &Stream; - - void error(yaml::Node *N, const Twine &Msg) { - Stream.printError(N, Msg); - } - - // false on error - bool parseScalarString(yaml::Node *N, StringRef &Result, - SmallVectorImpl &Storage) { - const auto *S = dyn_cast(N); - - if (!S) { - error(N, "expected string"); - return false; - } - Result = S->getValue(Storage); - return true; - } - - // false on error - bool parseScalarBool(yaml::Node *N, bool &Result) { - SmallString<5> Storage; - StringRef Value; - if (!parseScalarString(N, Value, Storage)) - return false; - - if (Value.equals_lower("true") || Value.equals_lower("on") || - Value.equals_lower("yes") || Value == "1") { - Result = true; - return true; - } else if (Value.equals_lower("false") || Value.equals_lower("off") || - Value.equals_lower("no") || Value == "0") { - Result = false; - return true; - } - - error(N, "expected boolean value"); - return false; - } - - struct KeyStatus { - bool Required; - bool Seen = false; - - KeyStatus(bool Required = false) : Required(Required) {} - }; - - using KeyStatusPair = std::pair; - - // false on error - bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key, - DenseMap &Keys) { - if (!Keys.count(Key)) { - error(KeyNode, "unknown key"); - return false; - } - KeyStatus &S = Keys[Key]; - if (S.Seen) { - error(KeyNode, Twine("duplicate key '") + Key + "'"); - return false; - } - S.Seen = true; - return true; - } - - // false on error - bool checkMissingKeys(yaml::Node *Obj, DenseMap &Keys) { - for (const auto &I : Keys) { - if (I.second.Required && !I.second.Seen) { - error(Obj, Twine("missing key '") + I.first + "'"); - return false; - } - } - return true; - } - - Entry *lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name, - Entry *ParentEntry = nullptr) { - if (!ParentEntry) { // Look for a existent root - for (const auto &Root : FS->Roots) { - if (Name.equals(Root->getName())) { - ParentEntry = Root.get(); - return ParentEntry; - } - } - } else { // Advance to the next component - auto *DE = dyn_cast(ParentEntry); - for (std::unique_ptr &Content : - llvm::make_range(DE->contents_begin(), DE->contents_end())) { - auto *DirContent = dyn_cast(Content.get()); - if (DirContent && Name.equals(Content->getName())) - return DirContent; - } - } - - // ... or create a new one - std::unique_ptr E = llvm::make_unique( - Name, - Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(), - 0, 0, 0, file_type::directory_file, sys::fs::all_all)); - - if (!ParentEntry) { // Add a new root to the overlay - FS->Roots.push_back(std::move(E)); - ParentEntry = FS->Roots.back().get(); - return ParentEntry; - } - - auto *DE = dyn_cast(ParentEntry); - DE->addContent(std::move(E)); - return DE->getLastContent(); - } - - void uniqueOverlayTree(RedirectingFileSystem *FS, Entry *SrcE, - Entry *NewParentE = nullptr) { - StringRef Name = SrcE->getName(); - switch (SrcE->getKind()) { - case EK_Directory: { - auto *DE = dyn_cast(SrcE); - assert(DE && "Must be a directory"); - // Empty directories could be present in the YAML as a way to - // describe a file for a current directory after some of its subdir - // is parsed. This only leads to redundant walks, ignore it. - if (!Name.empty()) - NewParentE = lookupOrCreateEntry(FS, Name, NewParentE); - for (std::unique_ptr &SubEntry : - llvm::make_range(DE->contents_begin(), DE->contents_end())) - uniqueOverlayTree(FS, SubEntry.get(), NewParentE); - break; - } - case EK_File: { - auto *FE = dyn_cast(SrcE); - assert(FE && "Must be a file"); - assert(NewParentE && "Parent entry must exist"); - auto *DE = dyn_cast(NewParentE); - DE->addContent(llvm::make_unique( - Name, FE->getExternalContentsPath(), FE->getUseName())); - break; - } - } - } - - std::unique_ptr parseEntry(yaml::Node *N, RedirectingFileSystem *FS, - bool IsRootEntry) { - auto *M = dyn_cast(N); - if (!M) { - error(N, "expected mapping node for file or directory entry"); - return nullptr; - } - - KeyStatusPair Fields[] = { - KeyStatusPair("name", true), - KeyStatusPair("type", true), - KeyStatusPair("contents", false), - KeyStatusPair("external-contents", false), - KeyStatusPair("use-external-name", false), - }; - - DenseMap Keys(std::begin(Fields), std::end(Fields)); - - bool HasContents = false; // external or otherwise - std::vector> EntryArrayContents; - std::string ExternalContentsPath; - std::string Name; - yaml::Node *NameValueNode; - auto UseExternalName = RedirectingFileEntry::NK_NotSet; - EntryKind Kind; - - for (auto &I : *M) { - StringRef Key; - // Reuse the buffer for key and value, since we don't look at key after - // parsing value. - SmallString<256> Buffer; - if (!parseScalarString(I.getKey(), Key, Buffer)) - return nullptr; - - if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys)) - return nullptr; - - StringRef Value; - if (Key == "name") { - if (!parseScalarString(I.getValue(), Value, Buffer)) - return nullptr; - - NameValueNode = I.getValue(); - if (FS->UseCanonicalizedPaths) { - SmallString<256> Path(Value); - // Guarantee that old YAML files containing paths with ".." and "." - // are properly canonicalized before read into the VFS. - Path = sys::path::remove_leading_dotslash(Path); - sys::path::remove_dots(Path, /*remove_dot_dot=*/true); - Name = Path.str(); - } else { - Name = Value; - } - } else if (Key == "type") { - if (!parseScalarString(I.getValue(), Value, Buffer)) - return nullptr; - if (Value == "file") - Kind = EK_File; - else if (Value == "directory") - Kind = EK_Directory; - else { - error(I.getValue(), "unknown value for 'type'"); - return nullptr; - } - } else if (Key == "contents") { - if (HasContents) { - error(I.getKey(), - "entry already has 'contents' or 'external-contents'"); - return nullptr; - } - HasContents = true; - auto *Contents = dyn_cast(I.getValue()); - if (!Contents) { - // FIXME: this is only for directories, what about files? - error(I.getValue(), "expected array"); - return nullptr; - } - - for (auto &I : *Contents) { - if (std::unique_ptr E = - parseEntry(&I, FS, /*IsRootEntry*/ false)) - EntryArrayContents.push_back(std::move(E)); - else - return nullptr; - } - } else if (Key == "external-contents") { - if (HasContents) { - error(I.getKey(), - "entry already has 'contents' or 'external-contents'"); - return nullptr; - } - HasContents = true; - if (!parseScalarString(I.getValue(), Value, Buffer)) - return nullptr; - - SmallString<256> FullPath; - if (FS->IsRelativeOverlay) { - FullPath = FS->getExternalContentsPrefixDir(); - assert(!FullPath.empty() && - "External contents prefix directory must exist"); - llvm::sys::path::append(FullPath, Value); - } else { - FullPath = Value; - } - - if (FS->UseCanonicalizedPaths) { - // Guarantee that old YAML files containing paths with ".." and "." - // are properly canonicalized before read into the VFS. - FullPath = sys::path::remove_leading_dotslash(FullPath); - sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true); - } - ExternalContentsPath = FullPath.str(); - } else if (Key == "use-external-name") { - bool Val; - if (!parseScalarBool(I.getValue(), Val)) - return nullptr; - UseExternalName = Val ? RedirectingFileEntry::NK_External - : RedirectingFileEntry::NK_Virtual; - } else { - llvm_unreachable("key missing from Keys"); - } - } - - if (Stream.failed()) - return nullptr; - - // check for missing keys - if (!HasContents) { - error(N, "missing key 'contents' or 'external-contents'"); - return nullptr; - } - if (!checkMissingKeys(N, Keys)) - return nullptr; - - // check invalid configuration - if (Kind == EK_Directory && - UseExternalName != RedirectingFileEntry::NK_NotSet) { - error(N, "'use-external-name' is not supported for directories"); - return nullptr; - } - - if (IsRootEntry && !sys::path::is_absolute(Name)) { - assert(NameValueNode && "Name presence should be checked earlier"); - error(NameValueNode, - "entry with relative path at the root level is not discoverable"); - return nullptr; - } - - // Remove trailing slash(es), being careful not to remove the root path - StringRef Trimmed(Name); - size_t RootPathLen = sys::path::root_path(Trimmed).size(); - while (Trimmed.size() > RootPathLen && - sys::path::is_separator(Trimmed.back())) - Trimmed = Trimmed.slice(0, Trimmed.size()-1); - // Get the last component - StringRef LastComponent = sys::path::filename(Trimmed); - - std::unique_ptr Result; - switch (Kind) { - case EK_File: - Result = llvm::make_unique( - LastComponent, std::move(ExternalContentsPath), UseExternalName); - break; - case EK_Directory: - Result = llvm::make_unique( - LastComponent, std::move(EntryArrayContents), - Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(), - 0, 0, 0, file_type::directory_file, sys::fs::all_all)); - break; - } - - StringRef Parent = sys::path::parent_path(Trimmed); - if (Parent.empty()) - return Result; - - // if 'name' contains multiple components, create implicit directory entries - for (sys::path::reverse_iterator I = sys::path::rbegin(Parent), - E = sys::path::rend(Parent); - I != E; ++I) { - std::vector> Entries; - Entries.push_back(std::move(Result)); - Result = llvm::make_unique( - *I, std::move(Entries), - Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(), - 0, 0, 0, file_type::directory_file, sys::fs::all_all)); - } - return Result; - } - -public: - RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {} - - // false on error - bool parse(yaml::Node *Root, RedirectingFileSystem *FS) { - auto *Top = dyn_cast(Root); - if (!Top) { - error(Root, "expected mapping node"); - return false; - } - - KeyStatusPair Fields[] = { - KeyStatusPair("version", true), - KeyStatusPair("case-sensitive", false), - KeyStatusPair("use-external-names", false), - KeyStatusPair("overlay-relative", false), - KeyStatusPair("ignore-non-existent-contents", false), - KeyStatusPair("roots", true), - }; - - DenseMap Keys(std::begin(Fields), std::end(Fields)); - std::vector> RootEntries; - - // Parse configuration and 'roots' - for (auto &I : *Top) { - SmallString<10> KeyBuffer; - StringRef Key; - if (!parseScalarString(I.getKey(), Key, KeyBuffer)) - return false; - - if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys)) - return false; - - if (Key == "roots") { - auto *Roots = dyn_cast(I.getValue()); - if (!Roots) { - error(I.getValue(), "expected array"); - return false; - } - - for (auto &I : *Roots) { - if (std::unique_ptr E = - parseEntry(&I, FS, /*IsRootEntry*/ true)) - RootEntries.push_back(std::move(E)); - else - return false; - } - } else if (Key == "version") { - StringRef VersionString; - SmallString<4> Storage; - if (!parseScalarString(I.getValue(), VersionString, Storage)) - return false; - int Version; - if (VersionString.getAsInteger(10, Version)) { - error(I.getValue(), "expected integer"); - return false; - } - if (Version < 0) { - error(I.getValue(), "invalid version number"); - return false; - } - if (Version != 0) { - error(I.getValue(), "version mismatch, expected 0"); - return false; - } - } else if (Key == "case-sensitive") { - if (!parseScalarBool(I.getValue(), FS->CaseSensitive)) - return false; - } else if (Key == "overlay-relative") { - if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay)) - return false; - } else if (Key == "use-external-names") { - if (!parseScalarBool(I.getValue(), FS->UseExternalNames)) - return false; - } else if (Key == "ignore-non-existent-contents") { - if (!parseScalarBool(I.getValue(), FS->IgnoreNonExistentContents)) - return false; - } else { - llvm_unreachable("key missing from Keys"); - } - } - - if (Stream.failed()) - return false; - - if (!checkMissingKeys(Top, Keys)) - return false; - - // Now that we sucessefully parsed the YAML file, canonicalize the internal - // representation to a proper directory tree so that we can search faster - // inside the VFS. - for (auto &E : RootEntries) - uniqueOverlayTree(FS, E.get()); - - return true; - } -}; - -} // namespace - -RedirectingFileSystem * -RedirectingFileSystem::create(std::unique_ptr Buffer, - SourceMgr::DiagHandlerTy DiagHandler, - StringRef YAMLFilePath, void *DiagContext, - IntrusiveRefCntPtr ExternalFS) { - SourceMgr SM; - yaml::Stream Stream(Buffer->getMemBufferRef(), SM); - - SM.setDiagHandler(DiagHandler, DiagContext); - yaml::document_iterator DI = Stream.begin(); - yaml::Node *Root = DI->getRoot(); - if (DI == Stream.end() || !Root) { - SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node"); - return nullptr; - } - - RedirectingFileSystemParser P(Stream); - - std::unique_ptr FS( - new RedirectingFileSystem(std::move(ExternalFS))); - - if (!YAMLFilePath.empty()) { - // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed - // to each 'external-contents' path. - // - // Example: - // -ivfsoverlay dummy.cache/vfs/vfs.yaml - // yields: - // FS->ExternalContentsPrefixDir => //dummy.cache/vfs - // - SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath); - std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir); - assert(!EC && "Overlay dir final path must be absolute"); - (void)EC; - FS->setExternalContentsPrefixDir(OverlayAbsDir); - } - - if (!P.parse(Root, FS.get())) - return nullptr; - - return FS.release(); -} - -ErrorOr RedirectingFileSystem::lookupPath(const Twine &Path_) { - SmallString<256> Path; - Path_.toVector(Path); - - // Handle relative paths - if (std::error_code EC = makeAbsolute(Path)) - return EC; - - // Canonicalize path by removing ".", "..", "./", etc components. This is - // a VFS request, do bot bother about symlinks in the path components - // but canonicalize in order to perform the correct entry search. - if (UseCanonicalizedPaths) { - Path = sys::path::remove_leading_dotslash(Path); - sys::path::remove_dots(Path, /*remove_dot_dot=*/true); - } - - if (Path.empty()) - return make_error_code(llvm::errc::invalid_argument); - - sys::path::const_iterator Start = sys::path::begin(Path); - sys::path::const_iterator End = sys::path::end(Path); - for (const auto &Root : Roots) { - ErrorOr Result = lookupPath(Start, End, Root.get()); - if (Result || Result.getError() != llvm::errc::no_such_file_or_directory) - return Result; - } - return make_error_code(llvm::errc::no_such_file_or_directory); -} - -ErrorOr -RedirectingFileSystem::lookupPath(sys::path::const_iterator Start, - sys::path::const_iterator End, Entry *From) { -#ifndef _WIN32 - assert(!isTraversalComponent(*Start) && - !isTraversalComponent(From->getName()) && - "Paths should not contain traversal components"); -#else - // FIXME: this is here to support windows, remove it once canonicalized - // paths become globally default. - if (Start->equals(".")) - ++Start; -#endif - - StringRef FromName = From->getName(); - - // Forward the search to the next component in case this is an empty one. - if (!FromName.empty()) { - if (CaseSensitive ? !Start->equals(FromName) - : !Start->equals_lower(FromName)) - // failure to match - return make_error_code(llvm::errc::no_such_file_or_directory); - - ++Start; - - if (Start == End) { - // Match! - return From; - } - } - - auto *DE = dyn_cast(From); - if (!DE) - return make_error_code(llvm::errc::not_a_directory); - - for (const std::unique_ptr &DirEntry : - llvm::make_range(DE->contents_begin(), DE->contents_end())) { - ErrorOr Result = lookupPath(Start, End, DirEntry.get()); - if (Result || Result.getError() != llvm::errc::no_such_file_or_directory) - return Result; - } - return make_error_code(llvm::errc::no_such_file_or_directory); -} - -static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames, - Status ExternalStatus) { - Status S = ExternalStatus; - if (!UseExternalNames) - S = Status::copyWithNewName(S, Path.str()); - S.IsVFSMapped = true; - return S; -} - -ErrorOr RedirectingFileSystem::status(const Twine &Path, Entry *E) { - assert(E != nullptr); - if (auto *F = dyn_cast(E)) { - ErrorOr S = ExternalFS->status(F->getExternalContentsPath()); - assert(!S || S->getName() == F->getExternalContentsPath()); - if (S) - return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames), - *S); - return S; - } else { // directory - auto *DE = cast(E); - return Status::copyWithNewName(DE->getStatus(), Path.str()); - } -} - -ErrorOr RedirectingFileSystem::status(const Twine &Path) { - ErrorOr Result = lookupPath(Path); - if (!Result) - return Result.getError(); - return status(Path, *Result); -} - -namespace { - -/// Provide a file wrapper with an overriden status. -class FileWithFixedStatus : public File { - std::unique_ptr InnerFile; - Status S; - -public: - FileWithFixedStatus(std::unique_ptr InnerFile, Status S) - : InnerFile(std::move(InnerFile)), S(std::move(S)) {} - - ErrorOr status() override { return S; } - ErrorOr> - - getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator, - bool IsVolatile) override { - return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator, - IsVolatile); - } - - std::error_code close() override { return InnerFile->close(); } -}; - -} // namespace - -ErrorOr> -RedirectingFileSystem::openFileForRead(const Twine &Path) { - ErrorOr E = lookupPath(Path); - if (!E) - return E.getError(); - - auto *F = dyn_cast(*E); - if (!F) // FIXME: errc::not_a_file? - return make_error_code(llvm::errc::invalid_argument); - - auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath()); - if (!Result) - return Result; - - auto ExternalStatus = (*Result)->status(); - if (!ExternalStatus) - return ExternalStatus.getError(); - - // FIXME: Update the status with the name and VFSMapped. - Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames), - *ExternalStatus); - return std::unique_ptr( - llvm::make_unique(std::move(*Result), S)); -} - -IntrusiveRefCntPtr -vfs::getVFSFromYAML(std::unique_ptr Buffer, - SourceMgr::DiagHandlerTy DiagHandler, - StringRef YAMLFilePath, - void *DiagContext, - IntrusiveRefCntPtr ExternalFS) { - return RedirectingFileSystem::create(std::move(Buffer), DiagHandler, - YAMLFilePath, DiagContext, - std::move(ExternalFS)); -} - -static void getVFSEntries(Entry *SrcE, SmallVectorImpl &Path, - SmallVectorImpl &Entries) { - auto Kind = SrcE->getKind(); - if (Kind == EK_Directory) { - auto *DE = dyn_cast(SrcE); - assert(DE && "Must be a directory"); - for (std::unique_ptr &SubEntry : - llvm::make_range(DE->contents_begin(), DE->contents_end())) { - Path.push_back(SubEntry->getName()); - getVFSEntries(SubEntry.get(), Path, Entries); - Path.pop_back(); - } - return; - } - - assert(Kind == EK_File && "Must be a EK_File"); - auto *FE = dyn_cast(SrcE); - assert(FE && "Must be a file"); - SmallString<128> VPath; - for (auto &Comp : Path) - llvm::sys::path::append(VPath, Comp); - Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath())); -} - -void vfs::collectVFSFromYAML(std::unique_ptr Buffer, - SourceMgr::DiagHandlerTy DiagHandler, - StringRef YAMLFilePath, - SmallVectorImpl &CollectedEntries, - void *DiagContext, - IntrusiveRefCntPtr ExternalFS) { - RedirectingFileSystem *VFS = RedirectingFileSystem::create( - std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext, - std::move(ExternalFS)); - ErrorOr RootE = VFS->lookupPath("/"); - if (!RootE) - return; - SmallVector Components; - Components.push_back("/"); - getVFSEntries(*RootE, Components, CollectedEntries); -} - -UniqueID vfs::getNextVirtualUniqueID() { - static std::atomic UID; - unsigned ID = ++UID; - // The following assumes that uint64_t max will never collide with a real - // dev_t value from the OS. - return UniqueID(std::numeric_limits::max(), ID); -} - -void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) { - assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute"); - assert(sys::path::is_absolute(RealPath) && "real path not absolute"); - assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported"); - Mappings.emplace_back(VirtualPath, RealPath); -} - -namespace { - -class JSONWriter { - llvm::raw_ostream &OS; - SmallVector DirStack; - - unsigned getDirIndent() { return 4 * DirStack.size(); } - unsigned getFileIndent() { return 4 * (DirStack.size() + 1); } - bool containedIn(StringRef Parent, StringRef Path); - StringRef containedPart(StringRef Parent, StringRef Path); - void startDirectory(StringRef Path); - void endDirectory(); - void writeEntry(StringRef VPath, StringRef RPath); - -public: - JSONWriter(llvm::raw_ostream &OS) : OS(OS) {} - - void write(ArrayRef Entries, Optional UseExternalNames, - Optional IsCaseSensitive, Optional IsOverlayRelative, - Optional IgnoreNonExistentContents, StringRef OverlayDir); -}; - -} // namespace - -bool JSONWriter::containedIn(StringRef Parent, StringRef Path) { - using namespace llvm::sys; - - // Compare each path component. - auto IParent = path::begin(Parent), EParent = path::end(Parent); - for (auto IChild = path::begin(Path), EChild = path::end(Path); - IParent != EParent && IChild != EChild; ++IParent, ++IChild) { - if (*IParent != *IChild) - return false; - } - // Have we exhausted the parent path? - return IParent == EParent; -} - -StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) { - assert(!Parent.empty()); - assert(containedIn(Parent, Path)); - return Path.slice(Parent.size() + 1, StringRef::npos); -} - -void JSONWriter::startDirectory(StringRef Path) { - StringRef Name = - DirStack.empty() ? Path : containedPart(DirStack.back(), Path); - DirStack.push_back(Path); - unsigned Indent = getDirIndent(); - OS.indent(Indent) << "{\n"; - OS.indent(Indent + 2) << "'type': 'directory',\n"; - OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n"; - OS.indent(Indent + 2) << "'contents': [\n"; -} - -void JSONWriter::endDirectory() { - unsigned Indent = getDirIndent(); - OS.indent(Indent + 2) << "]\n"; - OS.indent(Indent) << "}"; - - DirStack.pop_back(); -} - -void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) { - unsigned Indent = getFileIndent(); - OS.indent(Indent) << "{\n"; - OS.indent(Indent + 2) << "'type': 'file',\n"; - OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n"; - OS.indent(Indent + 2) << "'external-contents': \"" - << llvm::yaml::escape(RPath) << "\"\n"; - OS.indent(Indent) << "}"; -} - -void JSONWriter::write(ArrayRef Entries, - Optional UseExternalNames, - Optional IsCaseSensitive, - Optional IsOverlayRelative, - Optional IgnoreNonExistentContents, - StringRef OverlayDir) { - using namespace llvm::sys; - - OS << "{\n" - " 'version': 0,\n"; - if (IsCaseSensitive.hasValue()) - OS << " 'case-sensitive': '" - << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n"; - if (UseExternalNames.hasValue()) - OS << " 'use-external-names': '" - << (UseExternalNames.getValue() ? "true" : "false") << "',\n"; - bool UseOverlayRelative = false; - if (IsOverlayRelative.hasValue()) { - UseOverlayRelative = IsOverlayRelative.getValue(); - OS << " 'overlay-relative': '" - << (UseOverlayRelative ? "true" : "false") << "',\n"; - } - if (IgnoreNonExistentContents.hasValue()) - OS << " 'ignore-non-existent-contents': '" - << (IgnoreNonExistentContents.getValue() ? "true" : "false") << "',\n"; - OS << " 'roots': [\n"; - - if (!Entries.empty()) { - const YAMLVFSEntry &Entry = Entries.front(); - startDirectory(path::parent_path(Entry.VPath)); - - StringRef RPath = Entry.RPath; - if (UseOverlayRelative) { - unsigned OverlayDirLen = OverlayDir.size(); - assert(RPath.substr(0, OverlayDirLen) == OverlayDir && - "Overlay dir must be contained in RPath"); - RPath = RPath.slice(OverlayDirLen, RPath.size()); - } - - writeEntry(path::filename(Entry.VPath), RPath); - - for (const auto &Entry : Entries.slice(1)) { - StringRef Dir = path::parent_path(Entry.VPath); - if (Dir == DirStack.back()) - OS << ",\n"; - else { - while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) { - OS << "\n"; - endDirectory(); - } - OS << ",\n"; - startDirectory(Dir); - } - StringRef RPath = Entry.RPath; - if (UseOverlayRelative) { - unsigned OverlayDirLen = OverlayDir.size(); - assert(RPath.substr(0, OverlayDirLen) == OverlayDir && - "Overlay dir must be contained in RPath"); - RPath = RPath.slice(OverlayDirLen, RPath.size()); - } - writeEntry(path::filename(Entry.VPath), RPath); - } - - while (!DirStack.empty()) { - OS << "\n"; - endDirectory(); - } - OS << "\n"; - } - - OS << " ]\n" - << "}\n"; -} - -void YAMLVFSWriter::write(llvm::raw_ostream &OS) { - llvm::sort(Mappings, [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) { - return LHS.VPath < RHS.VPath; - }); - - JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive, - IsOverlayRelative, IgnoreNonExistentContents, - OverlayDir); -} - -VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl( - const Twine &_Path, RedirectingDirectoryEntry::iterator Begin, - RedirectingDirectoryEntry::iterator End, std::error_code &EC) - : Dir(_Path.str()), Current(Begin), End(End) { - EC = incrementImpl(); -} - -std::error_code VFSFromYamlDirIterImpl::increment() { - assert(Current != End && "cannot iterate past end"); - ++Current; - return incrementImpl(); -} - -std::error_code VFSFromYamlDirIterImpl::incrementImpl() { - while (Current != End) { - SmallString<128> PathStr(Dir); - llvm::sys::path::append(PathStr, (*Current)->getName()); - sys::fs::file_type Type; - switch ((*Current)->getKind()) { - case EK_Directory: - Type = sys::fs::file_type::directory_file; - break; - case EK_File: - Type = sys::fs::file_type::regular_file; - break; - } - CurrentEntry = directory_entry(PathStr.str(), Type); - break; - } - - if (Current == End) - CurrentEntry = directory_entry(); - return {}; -} - -vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_, - const Twine &Path, - std::error_code &EC) - : FS(&FS_) { - directory_iterator I = FS->dir_begin(Path, EC); - if (I != directory_iterator()) { - State = std::make_shared(); - State->push(I); - } -} - -vfs::recursive_directory_iterator & -recursive_directory_iterator::increment(std::error_code &EC) { - assert(FS && State && !State->empty() && "incrementing past end"); - assert(!State->top()->path().empty() && "non-canonical end iterator"); - vfs::directory_iterator End; - if (State->top()->type() == sys::fs::file_type::directory_file) { - vfs::directory_iterator I = FS->dir_begin(State->top()->path(), EC); - if (I != End) { - State->push(I); - return *this; - } - } - - while (!State->empty() && State->top().increment(EC) == End) - State->pop(); - - if (State->empty()) - State.reset(); // end iterator - - return *this; -} Index: cfe/trunk/lib/Driver/Distro.cpp =================================================================== --- cfe/trunk/lib/Driver/Distro.cpp +++ cfe/trunk/lib/Driver/Distro.cpp @@ -8,6 +8,7 @@ //===----------------------------------------------------------------------===// #include "clang/Driver/Distro.h" +#include "clang/Basic/LLVM.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" @@ -17,7 +18,7 @@ using namespace clang::driver; using namespace clang; -static Distro::DistroType DetectDistro(vfs::FileSystem &VFS) { +static Distro::DistroType DetectDistro(llvm::vfs::FileSystem &VFS) { llvm::ErrorOr> File = VFS.getBufferForFile("/etc/lsb-release"); if (File) { @@ -139,4 +140,4 @@ return Distro::UnknownDistro; } -Distro::Distro(vfs::FileSystem &VFS) : DistroVal(DetectDistro(VFS)) {} +Distro::Distro(llvm::vfs::FileSystem &VFS) : DistroVal(DetectDistro(VFS)) {} Index: cfe/trunk/lib/Driver/Driver.cpp =================================================================== --- cfe/trunk/lib/Driver/Driver.cpp +++ cfe/trunk/lib/Driver/Driver.cpp @@ -43,7 +43,6 @@ #include "ToolChains/WebAssembly.h" #include "ToolChains/XCore.h" #include "clang/Basic/Version.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Config/config.h" #include "clang/Driver/Action.h" #include "clang/Driver/Compilation.h" @@ -75,6 +74,7 @@ #include "llvm/Support/Program.h" #include "llvm/Support/StringSaver.h" #include "llvm/Support/TargetRegistry.h" +#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include #include @@ -89,7 +89,7 @@ Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple, DiagnosticsEngine &Diags, - IntrusiveRefCntPtr VFS) + IntrusiveRefCntPtr VFS) : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None), ClangExecutable(ClangExecutable), @@ -104,7 +104,7 @@ // Provide a sane fallback if no VFS is specified. if (!this->VFS) - this->VFS = vfs::getRealFileSystem(); + this->VFS = llvm::vfs::getRealFileSystem(); Name = llvm::sys::path::filename(ClangExecutable); Dir = llvm::sys::path::parent_path(ClangExecutable); Index: cfe/trunk/lib/Driver/ToolChain.cpp =================================================================== --- cfe/trunk/lib/Driver/ToolChain.cpp +++ cfe/trunk/lib/Driver/ToolChain.cpp @@ -13,7 +13,6 @@ #include "ToolChains/Clang.h" #include "clang/Basic/ObjCRuntime.h" #include "clang/Basic/Sanitizers.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Config/config.h" #include "clang/Driver/Action.h" #include "clang/Driver/Driver.h" @@ -39,6 +38,7 @@ #include "llvm/Support/TargetParser.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/VersionTuple.h" +#include "llvm/Support/VirtualFileSystem.h" #include #include #include @@ -99,7 +99,9 @@ ToolChain::~ToolChain() = default; -vfs::FileSystem &ToolChain::getVFS() const { return getDriver().getVFS(); } +llvm::vfs::FileSystem &ToolChain::getVFS() const { + return getDriver().getVFS(); +} bool ToolChain::useIntegratedAs() const { return Args.hasFlag(options::OPT_fintegrated_as, Index: cfe/trunk/lib/Driver/ToolChains/BareMetal.cpp =================================================================== --- cfe/trunk/lib/Driver/ToolChains/BareMetal.cpp +++ cfe/trunk/lib/Driver/ToolChains/BareMetal.cpp @@ -13,13 +13,13 @@ #include "InputInfo.h" #include "Gnu.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Options.h" #include "llvm/Option/ArgList.h" #include "llvm/Support/Path.h" +#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" using namespace llvm::opt; @@ -119,8 +119,9 @@ std::error_code EC; Generic_GCC::GCCVersion Version = {"", -1, -1, -1, "", "", ""}; // Walk the subdirs, and find the one with the newest gcc version: - for (vfs::directory_iterator LI = - getDriver().getVFS().dir_begin(Dir.str(), EC), LE; + for (llvm::vfs::directory_iterator + LI = getDriver().getVFS().dir_begin(Dir.str(), EC), + LE; !EC && LI != LE; LI = LI.increment(EC)) { StringRef VersionText = llvm::sys::path::filename(LI->path()); auto CandidateVersion = Generic_GCC::GCCVersion::Parse(VersionText); Index: cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp =================================================================== --- cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp +++ cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp @@ -14,14 +14,13 @@ #include "Arch/PPC.h" #include "Arch/SystemZ.h" #include "Arch/X86.h" -#include "Hexagon.h" #include "HIP.h" +#include "Hexagon.h" #include "InputInfo.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/ObjCRuntime.h" #include "clang/Basic/Version.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Config/config.h" #include "clang/Driver/Action.h" #include "clang/Driver/Compilation.h" @@ -52,6 +51,7 @@ #include "llvm/Support/Program.h" #include "llvm/Support/ScopedPrinter.h" #include "llvm/Support/TargetParser.h" +#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/YAMLParser.h" using namespace clang::driver; Index: cfe/trunk/lib/Driver/ToolChains/Cuda.cpp =================================================================== --- cfe/trunk/lib/Driver/ToolChains/Cuda.cpp +++ cfe/trunk/lib/Driver/ToolChains/Cuda.cpp @@ -11,7 +11,6 @@ #include "CommonArgs.h" #include "InputInfo.h" #include "clang/Basic/Cuda.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Config/config.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Distro.h" @@ -23,6 +22,7 @@ #include "llvm/Support/Path.h" #include "llvm/Support/Process.h" #include "llvm/Support/Program.h" +#include "llvm/Support/VirtualFileSystem.h" #include using namespace clang::driver; Index: cfe/trunk/lib/Driver/ToolChains/Darwin.cpp =================================================================== --- cfe/trunk/lib/Driver/ToolChains/Darwin.cpp +++ cfe/trunk/lib/Driver/ToolChains/Darwin.cpp @@ -12,7 +12,6 @@ #include "CommonArgs.h" #include "clang/Basic/AlignedAllocation.h" #include "clang/Basic/ObjCRuntime.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" @@ -23,6 +22,7 @@ #include "llvm/Support/Path.h" #include "llvm/Support/ScopedPrinter.h" #include "llvm/Support/TargetParser.h" +#include "llvm/Support/VirtualFileSystem.h" #include // ::getenv using namespace clang::driver; Index: cfe/trunk/lib/Driver/ToolChains/FreeBSD.cpp =================================================================== --- cfe/trunk/lib/Driver/ToolChains/FreeBSD.cpp +++ cfe/trunk/lib/Driver/ToolChains/FreeBSD.cpp @@ -12,11 +12,11 @@ #include "Arch/Mips.h" #include "Arch/Sparc.h" #include "CommonArgs.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Options.h" #include "clang/Driver/SanitizerArgs.h" #include "llvm/Option/ArgList.h" +#include "llvm/Support/VirtualFileSystem.h" using namespace clang::driver; using namespace clang::driver::tools; Index: cfe/trunk/lib/Driver/ToolChains/Gnu.cpp =================================================================== --- cfe/trunk/lib/Driver/ToolChains/Gnu.cpp +++ cfe/trunk/lib/Driver/ToolChains/Gnu.cpp @@ -16,7 +16,6 @@ #include "Arch/SystemZ.h" #include "CommonArgs.h" #include "Linux.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" @@ -27,6 +26,7 @@ #include "llvm/Support/CodeGen.h" #include "llvm/Support/Path.h" #include "llvm/Support/TargetParser.h" +#include "llvm/Support/VirtualFileSystem.h" #include using namespace clang::driver; @@ -791,10 +791,10 @@ // Filter to remove Multilibs that don't exist as a suffix to Path class FilterNonExistent { StringRef Base, File; - vfs::FileSystem &VFS; + llvm::vfs::FileSystem &VFS; public: - FilterNonExistent(StringRef Base, StringRef File, vfs::FileSystem &VFS) + FilterNonExistent(StringRef Base, StringRef File, llvm::vfs::FileSystem &VFS) : Base(Base), File(File), VFS(VFS) {} bool operator()(const Multilib &M) { return !VFS.exists(Base + M.gccSuffix() + File); @@ -940,7 +940,7 @@ return false; } -static bool findMipsAndroidMultilibs(vfs::FileSystem &VFS, StringRef Path, +static bool findMipsAndroidMultilibs(llvm::vfs::FileSystem &VFS, StringRef Path, const Multilib::flags_list &Flags, FilterNonExistent &NonExistent, DetectedMultilibs &Result) { @@ -1762,7 +1762,8 @@ std::string PrefixDir = SysRoot.str() + "/usr/gcc"; std::error_code EC; - for (vfs::directory_iterator LI = D.getVFS().dir_begin(PrefixDir, EC), LE; + for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(PrefixDir, EC), + LE; !EC && LI != LE; LI = LI.increment(EC)) { StringRef VersionText = llvm::sys::path::filename(LI->path()); GCCVersion CandidateVersion = GCCVersion::Parse(VersionText); @@ -2205,7 +2206,7 @@ StringRef LibSuffix = Suffix.LibSuffix; std::error_code EC; - for (vfs::directory_iterator + for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(LibDir + "/" + LibSuffix, EC), LE; !EC && LI != LE; LI = LI.increment(EC)) { Index: cfe/trunk/lib/Driver/ToolChains/Hexagon.cpp =================================================================== --- cfe/trunk/lib/Driver/ToolChains/Hexagon.cpp +++ cfe/trunk/lib/Driver/ToolChains/Hexagon.cpp @@ -8,9 +8,8 @@ //===----------------------------------------------------------------------===// #include "Hexagon.h" -#include "InputInfo.h" #include "CommonArgs.h" -#include "clang/Basic/VirtualFileSystem.h" +#include "InputInfo.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" @@ -19,6 +18,7 @@ #include "llvm/Option/ArgList.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" +#include "llvm/Support/VirtualFileSystem.h" using namespace clang::driver; using namespace clang::driver::tools; Index: cfe/trunk/lib/Driver/ToolChains/Linux.cpp =================================================================== --- cfe/trunk/lib/Driver/ToolChains/Linux.cpp +++ cfe/trunk/lib/Driver/ToolChains/Linux.cpp @@ -13,7 +13,6 @@ #include "Arch/PPC.h" #include "Arch/RISCV.h" #include "CommonArgs.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Config/config.h" #include "clang/Driver/Distro.h" #include "clang/Driver/Driver.h" @@ -23,6 +22,7 @@ #include "llvm/ProfileData/InstrProf.h" #include "llvm/Support/Path.h" #include "llvm/Support/ScopedPrinter.h" +#include "llvm/Support/VirtualFileSystem.h" #include using namespace clang::driver; Index: cfe/trunk/lib/Driver/ToolChains/Minix.cpp =================================================================== --- cfe/trunk/lib/Driver/ToolChains/Minix.cpp +++ cfe/trunk/lib/Driver/ToolChains/Minix.cpp @@ -8,13 +8,13 @@ //===----------------------------------------------------------------------===// #include "Minix.h" -#include "InputInfo.h" #include "CommonArgs.h" -#include "clang/Basic/VirtualFileSystem.h" +#include "InputInfo.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/Options.h" #include "llvm/Option/ArgList.h" +#include "llvm/Support/VirtualFileSystem.h" using namespace clang::driver; using namespace clang; Index: cfe/trunk/lib/Format/Format.cpp =================================================================== --- cfe/trunk/lib/Format/Format.cpp +++ cfe/trunk/lib/Format/Format.cpp @@ -29,7 +29,6 @@ #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Basic/SourceManager.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Lex/Lexer.h" #include "clang/Tooling/Inclusions/HeaderIncludes.h" #include "llvm/ADT/STLExtras.h" @@ -38,6 +37,7 @@ #include "llvm/Support/Debug.h" #include "llvm/Support/Path.h" #include "llvm/Support/Regex.h" +#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/YAMLTraits.h" #include #include @@ -2326,9 +2326,10 @@ llvm::Expected getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyleName, - StringRef Code, vfs::FileSystem *FS) { + StringRef Code, + llvm::vfs::FileSystem *FS) { if (!FS) { - FS = vfs::getRealFileSystem().get(); + FS = llvm::vfs::getRealFileSystem().get(); } FormatStyle Style = getLLVMStyle(); Style.Language = guessLanguage(FileName, Code); Index: cfe/trunk/lib/Frontend/ASTUnit.cpp =================================================================== --- cfe/trunk/lib/Frontend/ASTUnit.cpp +++ cfe/trunk/lib/Frontend/ASTUnit.cpp @@ -37,7 +37,6 @@ #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/TargetOptions.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/CompilerInvocation.h" #include "clang/Frontend/FrontendAction.h" @@ -88,6 +87,7 @@ #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Mutex.h" #include "llvm/Support/Timer.h" +#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include #include @@ -155,9 +155,8 @@ /// and file-to-buffer remappings inside \p Invocation. static std::unique_ptr getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation, - vfs::FileSystem *VFS, - StringRef FilePath, - bool isVolatile) { + llvm::vfs::FileSystem *VFS, + StringRef FilePath, bool isVolatile) { const auto &PreprocessorOpts = Invocation.getPreprocessorOpts(); // Try to determine if the main file has been remapped, either from the @@ -752,7 +751,8 @@ AST->OnlyLocalDecls = OnlyLocalDecls; AST->CaptureDiagnostics = CaptureDiagnostics; AST->Diagnostics = Diags; - IntrusiveRefCntPtr VFS = vfs::getRealFileSystem(); + IntrusiveRefCntPtr VFS = + llvm::vfs::getRealFileSystem(); AST->FileMgr = new FileManager(FileSystemOpts, VFS); AST->UserFilesAreVolatile = UserFilesAreVolatile; AST->SourceMgr = new SourceManager(AST->getDiagnostics(), @@ -1074,7 +1074,7 @@ /// contain any translation-unit information, false otherwise. bool ASTUnit::Parse(std::shared_ptr PCHContainerOps, std::unique_ptr OverrideMainBuffer, - IntrusiveRefCntPtr VFS) { + IntrusiveRefCntPtr VFS) { if (!Invocation) return true; @@ -1082,7 +1082,7 @@ if (OverrideMainBuffer) { assert(Preamble && "No preamble was built, but OverrideMainBuffer is not null"); - IntrusiveRefCntPtr OldVFS = VFS; + IntrusiveRefCntPtr OldVFS = VFS; Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get()); if (OldVFS != VFS && FileMgr) { assert(OldVFS == FileMgr->getVirtualFileSystem() && @@ -1279,7 +1279,7 @@ ASTUnit::getMainBufferWithPrecompiledPreamble( std::shared_ptr PCHContainerOps, CompilerInvocation &PreambleInvocationIn, - IntrusiveRefCntPtr VFS, bool AllowRebuild, + IntrusiveRefCntPtr VFS, bool AllowRebuild, unsigned MaxLines) { auto MainFilePath = PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile(); @@ -1468,7 +1468,7 @@ bool CaptureDiagnostics, bool UserFilesAreVolatile) { std::unique_ptr AST(new ASTUnit(false)); ConfigureDiags(Diags, *AST, CaptureDiagnostics); - IntrusiveRefCntPtr VFS = + IntrusiveRefCntPtr VFS = createVFSFromCompilerInvocation(*CI, *Diags); AST->Diagnostics = Diags; AST->FileSystemOpts = CI->getFileSystemOpts(); @@ -1630,7 +1630,7 @@ bool ASTUnit::LoadFromCompilerInvocation( std::shared_ptr PCHContainerOps, unsigned PrecompilePreambleAfterNParses, - IntrusiveRefCntPtr VFS) { + IntrusiveRefCntPtr VFS) { if (!Invocation) return true; @@ -1709,7 +1709,7 @@ bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies, bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization, llvm::Optional ModuleFormat, std::unique_ptr *ErrAST, - IntrusiveRefCntPtr VFS) { + IntrusiveRefCntPtr VFS) { assert(Diags.get() && "no DiagnosticsEngine was provided"); SmallVector StoredDiagnostics; @@ -1754,7 +1754,7 @@ AST->Diagnostics = Diags; AST->FileSystemOpts = CI->getFileSystemOpts(); if (!VFS) - VFS = vfs::getRealFileSystem(); + VFS = llvm::vfs::getRealFileSystem(); VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS); AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS); AST->PCMCache = new MemoryBufferCache; @@ -1794,7 +1794,7 @@ bool ASTUnit::Reparse(std::shared_ptr PCHContainerOps, ArrayRef RemappedFiles, - IntrusiveRefCntPtr VFS) { + IntrusiveRefCntPtr VFS) { if (!Invocation) return true; Index: cfe/trunk/lib/Frontend/CacheTokens.cpp =================================================================== --- cfe/trunk/lib/Frontend/CacheTokens.cpp +++ cfe/trunk/lib/Frontend/CacheTokens.cpp @@ -556,8 +556,8 @@ ~StatListener() override {} LookupResult getStat(StringRef Path, FileData &Data, bool isFile, - std::unique_ptr *F, - vfs::FileSystem &FS) override { + std::unique_ptr *F, + llvm::vfs::FileSystem &FS) override { LookupResult Result = statChained(Path, Data, isFile, F, FS); if (Result == CacheMissing) // Failed 'stat'. Index: cfe/trunk/lib/Frontend/CompilerInstance.cpp =================================================================== --- cfe/trunk/lib/Frontend/CompilerInstance.cpp +++ cfe/trunk/lib/Frontend/CompilerInstance.cpp @@ -177,9 +177,9 @@ std::error_code EC; SmallString<128> DirNative; llvm::sys::path::native(PCHDir->getName(), DirNative); - vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); + llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); SimpleASTReaderListener Validator(CI.getPreprocessor()); - for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; + for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; Dir != DirEnd && !EC; Dir.increment(EC)) { // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not // used here since we're not interested in validating the PCH at this time, @@ -198,14 +198,14 @@ return; // Collect all VFS found. - SmallVector VFSEntries; + SmallVector VFSEntries; for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) { llvm::ErrorOr> Buffer = llvm::MemoryBuffer::getFile(VFSFile); if (!Buffer) return; - vfs::collectVFSFromYAML(std::move(Buffer.get()), /*DiagHandler*/ nullptr, - VFSFile, VFSEntries); + llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()), + /*DiagHandler*/ nullptr, VFSFile, VFSEntries); } for (auto &E : VFSEntries) @@ -303,7 +303,7 @@ FileManager *CompilerInstance::createFileManager() { if (!hasVirtualFileSystem()) { - IntrusiveRefCntPtr VFS = + IntrusiveRefCntPtr VFS = createVFSFromCompilerInvocation(getInvocation(), getDiagnostics()); setVirtualFileSystem(VFS); } Index: cfe/trunk/lib/Frontend/CompilerInvocation.cpp =================================================================== --- cfe/trunk/lib/Frontend/CompilerInvocation.cpp +++ cfe/trunk/lib/Frontend/CompilerInvocation.cpp @@ -23,7 +23,6 @@ #include "clang/Basic/SourceLocation.h" #include "clang/Basic/TargetOptions.h" #include "clang/Basic/Version.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Basic/Visibility.h" #include "clang/Basic/XRayInstr.h" #include "clang/Config/config.h" @@ -77,6 +76,7 @@ #include "llvm/Support/Process.h" #include "llvm/Support/Regex.h" #include "llvm/Support/VersionTuple.h" +#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetOptions.h" #include @@ -3245,21 +3245,21 @@ GraveYard[Idx] = Ptr; } -IntrusiveRefCntPtr +IntrusiveRefCntPtr createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags) { - return createVFSFromCompilerInvocation(CI, Diags, vfs::getRealFileSystem()); + return createVFSFromCompilerInvocation(CI, Diags, + llvm::vfs::getRealFileSystem()); } -IntrusiveRefCntPtr -createVFSFromCompilerInvocation(const CompilerInvocation &CI, - DiagnosticsEngine &Diags, - IntrusiveRefCntPtr BaseFS) { +IntrusiveRefCntPtr createVFSFromCompilerInvocation( + const CompilerInvocation &CI, DiagnosticsEngine &Diags, + IntrusiveRefCntPtr BaseFS) { if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty()) return BaseFS; - IntrusiveRefCntPtr Overlay( - new vfs::OverlayFileSystem(BaseFS)); + IntrusiveRefCntPtr Overlay( + new llvm::vfs::OverlayFileSystem(BaseFS)); // earlier vfs files are on the bottom for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) { llvm::ErrorOr> Buffer = @@ -3269,7 +3269,7 @@ continue; } - IntrusiveRefCntPtr FS = vfs::getVFSFromYAML( + IntrusiveRefCntPtr FS = llvm::vfs::getVFSFromYAML( std::move(Buffer.get()), /*DiagHandler*/ nullptr, File); if (FS) Overlay->pushOverlay(FS); Index: cfe/trunk/lib/Frontend/CreateInvocationFromCommandLine.cpp =================================================================== --- cfe/trunk/lib/Frontend/CreateInvocationFromCommandLine.cpp +++ cfe/trunk/lib/Frontend/CreateInvocationFromCommandLine.cpp @@ -32,7 +32,7 @@ /// argument vector. std::unique_ptr clang::createInvocationFromCommandLine( ArrayRef ArgList, IntrusiveRefCntPtr Diags, - IntrusiveRefCntPtr VFS) { + IntrusiveRefCntPtr VFS) { if (!Diags.get()) { // No diagnostics engine was provided, so create our own diagnostics object // with the default options. Index: cfe/trunk/lib/Frontend/FrontendAction.cpp =================================================================== --- cfe/trunk/lib/Frontend/FrontendAction.cpp +++ cfe/trunk/lib/Frontend/FrontendAction.cpp @@ -342,8 +342,8 @@ SmallString<128> DirNative; llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative); - vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); - for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End; + llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); + for (llvm::vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End; Dir != End && !EC; Dir.increment(EC)) { // Check whether this entry has an extension typically associated with // headers. @@ -696,8 +696,9 @@ SmallString<128> DirNative; llvm::sys::path::native(PCHDir->getName(), DirNative); bool Found = false; - vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); - for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; + llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); + for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), + DirEnd; Dir != DirEnd && !EC; Dir.increment(EC)) { // Check whether this is an acceptable AST file. if (ASTReader::isAcceptableASTFile( Index: cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp =================================================================== --- cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp +++ cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp @@ -14,7 +14,6 @@ #include "clang/Frontend/PrecompiledPreamble.h" #include "clang/AST/DeclObjC.h" #include "clang/Basic/TargetInfo.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/CompilerInvocation.h" #include "clang/Frontend/FrontendActions.h" @@ -30,6 +29,7 @@ #include "llvm/Support/Mutex.h" #include "llvm/Support/MutexGuard.h" #include "llvm/Support/Process.h" +#include "llvm/Support/VirtualFileSystem.h" #include #include @@ -48,17 +48,17 @@ #endif } -IntrusiveRefCntPtr +IntrusiveRefCntPtr createVFSOverlayForPreamblePCH(StringRef PCHFilename, std::unique_ptr PCHBuffer, - IntrusiveRefCntPtr VFS) { + IntrusiveRefCntPtr VFS) { // We want only the PCH file from the real filesystem to be available, // so we create an in-memory VFS with just that and overlay it on top. - IntrusiveRefCntPtr PCHFS( - new vfs::InMemoryFileSystem()); + IntrusiveRefCntPtr PCHFS( + new llvm::vfs::InMemoryFileSystem()); PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer)); - IntrusiveRefCntPtr Overlay( - new vfs::OverlayFileSystem(VFS)); + IntrusiveRefCntPtr Overlay( + new llvm::vfs::OverlayFileSystem(VFS)); Overlay->pushOverlay(PCHFS); return Overlay; } @@ -232,7 +232,8 @@ llvm::ErrorOr PrecompiledPreamble::Build( const CompilerInvocation &Invocation, const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, - DiagnosticsEngine &Diagnostics, IntrusiveRefCntPtr VFS, + DiagnosticsEngine &Diagnostics, + IntrusiveRefCntPtr VFS, std::shared_ptr PCHContainerOps, bool StoreInMemory, PreambleCallbacks &Callbacks) { assert(VFS && "VFS is null"); @@ -410,7 +411,7 @@ bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation, const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, - vfs::FileSystem *VFS) const { + llvm::vfs::FileSystem *VFS) const { assert( Bounds.Size <= MainFileBuffer->getBufferSize() && @@ -437,7 +438,7 @@ // remapping or unsaved_files. std::map OverriddenFiles; for (const auto &R : PreprocessorOpts.RemappedFiles) { - vfs::Status Status; + llvm::vfs::Status Status; if (!moveOnNoError(VFS->status(R.second), Status)) { // If we can't stat the file we're remapping to, assume that something // horrible happened. @@ -449,7 +450,7 @@ } for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) { - vfs::Status Status; + llvm::vfs::Status Status; if (!moveOnNoError(VFS->status(RB.first), Status)) return false; @@ -459,7 +460,7 @@ // Check whether anything has changed. for (const auto &F : FilesInPreamble) { - vfs::Status Status; + llvm::vfs::Status Status; if (!moveOnNoError(VFS->status(F.first()), Status)) { // If we can't stat the file, assume that something horrible happened. return false; @@ -485,14 +486,14 @@ } void PrecompiledPreamble::AddImplicitPreamble( - CompilerInvocation &CI, IntrusiveRefCntPtr &VFS, + CompilerInvocation &CI, IntrusiveRefCntPtr &VFS, llvm::MemoryBuffer *MainFileBuffer) const { PreambleBounds Bounds(PreambleBytes.size(), PreambleEndsAtStartOfLine); configurePreamble(Bounds, CI, VFS, MainFileBuffer); } void PrecompiledPreamble::OverridePreamble( - CompilerInvocation &CI, IntrusiveRefCntPtr &VFS, + CompilerInvocation &CI, IntrusiveRefCntPtr &VFS, llvm::MemoryBuffer *MainFileBuffer) const { auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), MainFileBuffer, 0); configurePreamble(Bounds, CI, VFS, MainFileBuffer); @@ -680,7 +681,7 @@ void PrecompiledPreamble::configurePreamble( PreambleBounds Bounds, CompilerInvocation &CI, - IntrusiveRefCntPtr &VFS, + IntrusiveRefCntPtr &VFS, llvm::MemoryBuffer *MainFileBuffer) const { assert(VFS); @@ -701,13 +702,14 @@ void PrecompiledPreamble::setupPreambleStorage( const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts, - IntrusiveRefCntPtr &VFS) { + IntrusiveRefCntPtr &VFS) { if (Storage.getKind() == PCHStorage::Kind::TempFile) { const TempPCHFile &PCHFile = Storage.asFile(); PreprocessorOpts.ImplicitPCHInclude = PCHFile.getFilePath(); // Make sure we can access the PCH file even if we're using a VFS - IntrusiveRefCntPtr RealFS = vfs::getRealFileSystem(); + IntrusiveRefCntPtr RealFS = + llvm::vfs::getRealFileSystem(); auto PCHPath = PCHFile.getFilePath(); if (VFS == RealFS || VFS->exists(PCHPath)) return; Index: cfe/trunk/lib/Index/SimpleFormatContext.h =================================================================== --- cfe/trunk/lib/Index/SimpleFormatContext.h +++ cfe/trunk/lib/Index/SimpleFormatContext.h @@ -36,12 +36,10 @@ public: SimpleFormatContext(LangOptions Options) : DiagOpts(new DiagnosticOptions()), - Diagnostics(new DiagnosticsEngine(new DiagnosticIDs, - DiagOpts.get())), - InMemoryFileSystem(new vfs::InMemoryFileSystem), + Diagnostics(new DiagnosticsEngine(new DiagnosticIDs, DiagOpts.get())), + InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem), Files(FileSystemOptions(), InMemoryFileSystem), - Sources(*Diagnostics, Files), - Rewrite(Sources, Options) { + Sources(*Diagnostics, Files), Rewrite(Sources, Options) { Diagnostics->setClient(new IgnoringDiagConsumer, true); } @@ -63,7 +61,7 @@ IntrusiveRefCntPtr DiagOpts; IntrusiveRefCntPtr Diagnostics; - IntrusiveRefCntPtr InMemoryFileSystem; + IntrusiveRefCntPtr InMemoryFileSystem; FileManager Files; SourceManager Sources; Rewriter Rewrite; Index: cfe/trunk/lib/Lex/HeaderSearch.cpp =================================================================== --- cfe/trunk/lib/Lex/HeaderSearch.cpp +++ cfe/trunk/lib/Lex/HeaderSearch.cpp @@ -17,7 +17,6 @@ #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/Module.h" #include "clang/Basic/SourceManager.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Lex/DirectoryLookup.h" #include "clang/Lex/ExternalPreprocessorSource.h" #include "clang/Lex/HeaderMap.h" @@ -35,6 +34,7 @@ #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" +#include "llvm/Support/VirtualFileSystem.h" #include #include #include @@ -1571,8 +1571,9 @@ DirNative); // Search each of the ".framework" directories to load them as modules. - vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); - for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; + llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); + for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), + DirEnd; Dir != DirEnd && !EC; Dir.increment(EC)) { if (llvm::sys::path::extension(Dir->path()) != ".framework") continue; @@ -1639,8 +1640,8 @@ std::error_code EC; SmallString<128> DirNative; llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative); - vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); - for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; + llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); + for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; Dir != DirEnd && !EC; Dir.increment(EC)) { bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework"; if (IsFramework == SearchDir.isFramework()) Index: cfe/trunk/lib/Lex/ModuleMap.cpp =================================================================== --- cfe/trunk/lib/Lex/ModuleMap.cpp +++ cfe/trunk/lib/Lex/ModuleMap.cpp @@ -22,7 +22,6 @@ #include "clang/Basic/SourceLocation.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/HeaderSearchOptions.h" #include "clang/Lex/LexDiagnostic.h" @@ -43,6 +42,7 @@ #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" +#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include #include @@ -1020,9 +1020,10 @@ = StringRef(FrameworkDir->getName()); llvm::sys::path::append(SubframeworksDirName, "Frameworks"); llvm::sys::path::native(SubframeworksDirName); - vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); - for (vfs::directory_iterator Dir = FS.dir_begin(SubframeworksDirName, EC), - DirEnd; + llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); + for (llvm::vfs::directory_iterator + Dir = FS.dir_begin(SubframeworksDirName, EC), + DirEnd; Dir != DirEnd && !EC; Dir.increment(EC)) { if (!StringRef(Dir->path()).endswith(".framework")) continue; @@ -2394,8 +2395,9 @@ // uncommonly used Tcl module on Darwin platforms. std::error_code EC; SmallVector Headers; - vfs::FileSystem &FS = *SourceMgr.getFileManager().getVirtualFileSystem(); - for (vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E; + llvm::vfs::FileSystem &FS = + *SourceMgr.getFileManager().getVirtualFileSystem(); + for (llvm::vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E; I != E && !EC; I.increment(EC)) { if (const FileEntry *FE = SourceMgr.getFileManager().getFile(I->path())) { Index: cfe/trunk/lib/Lex/PPLexerChange.cpp =================================================================== --- cfe/trunk/lib/Lex/PPLexerChange.cpp +++ cfe/trunk/lib/Lex/PPLexerChange.cpp @@ -304,9 +304,10 @@ ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap(); const DirectoryEntry *Dir = Mod.getUmbrellaDir().Entry; - vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); + llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); std::error_code EC; - for (vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC), End; + for (llvm::vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC), + End; Entry != End && !EC; Entry.increment(EC)) { using llvm::StringSwitch; Index: cfe/trunk/lib/Lex/PTHLexer.cpp =================================================================== --- cfe/trunk/lib/Lex/PTHLexer.cpp +++ cfe/trunk/lib/Lex/PTHLexer.cpp @@ -715,8 +715,8 @@ FL.getBase()) {} LookupResult getStat(StringRef Path, FileData &Data, bool isFile, - std::unique_ptr *F, - vfs::FileSystem &FS) override { + std::unique_ptr *F, + llvm::vfs::FileSystem &FS) override { // Do the lookup for the file's data in the PTH file. CacheTy::iterator I = Cache.find(Path); Index: cfe/trunk/lib/Sema/SemaCodeComplete.cpp =================================================================== --- cfe/trunk/lib/Sema/SemaCodeComplete.cpp +++ cfe/trunk/lib/Sema/SemaCodeComplete.cpp @@ -8152,7 +8152,7 @@ std::error_code EC; unsigned Count = 0; for (auto It = FS->dir_begin(Dir, EC); - !EC && It != vfs::directory_iterator(); It.increment(EC)) { + !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) { if (++Count == 2500) // If we happen to hit a huge directory, break; // bail out early so we're not too slow. StringRef Filename = llvm::sys::path::filename(It->path()); Index: cfe/trunk/lib/Serialization/ModuleManager.cpp =================================================================== --- cfe/trunk/lib/Serialization/ModuleManager.cpp +++ cfe/trunk/lib/Serialization/ModuleManager.cpp @@ -16,7 +16,6 @@ #include "clang/Basic/FileManager.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/MemoryBufferCache.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Frontend/PCHContainerOperations.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/ModuleMap.h" @@ -33,6 +32,7 @@ #include "llvm/Support/ErrorOr.h" #include "llvm/Support/GraphWriter.h" #include "llvm/Support/MemoryBuffer.h" +#include "llvm/Support/VirtualFileSystem.h" #include #include #include @@ -150,7 +150,7 @@ if (NewModule->Kind == MK_ImplicitModule) { std::string TimestampFilename = NewModule->getTimestampFilename(); - vfs::Status Status; + llvm::vfs::Status Status; // A cached stat value would be fine as well. if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status)) NewModule->InputFilesValidationTimestamp = Index: cfe/trunk/lib/Tooling/Core/Replacement.cpp =================================================================== --- cfe/trunk/lib/Tooling/Core/Replacement.cpp +++ cfe/trunk/lib/Tooling/Core/Replacement.cpp @@ -19,7 +19,6 @@ #include "clang/Basic/FileSystemOptions.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/SourceManager.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Lex/Lexer.h" #include "clang/Rewrite/Core/RewriteBuffer.h" #include "clang/Rewrite/Core/Rewriter.h" @@ -29,6 +28,7 @@ #include "llvm/Support/Error.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MemoryBuffer.h" +#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include #include @@ -583,8 +583,8 @@ if (Replaces.empty()) return Code.str(); - IntrusiveRefCntPtr InMemoryFileSystem( - new vfs::InMemoryFileSystem); + IntrusiveRefCntPtr InMemoryFileSystem( + new llvm::vfs::InMemoryFileSystem); FileManager Files(FileSystemOptions(), InMemoryFileSystem); DiagnosticsEngine Diagnostics( IntrusiveRefCntPtr(new DiagnosticIDs), Index: cfe/trunk/lib/Tooling/StandaloneExecution.cpp =================================================================== --- cfe/trunk/lib/Tooling/StandaloneExecution.cpp +++ cfe/trunk/lib/Tooling/StandaloneExecution.cpp @@ -30,7 +30,7 @@ StandaloneToolExecutor::StandaloneToolExecutor( const CompilationDatabase &Compilations, llvm::ArrayRef SourcePaths, - IntrusiveRefCntPtr BaseFS, + IntrusiveRefCntPtr BaseFS, std::shared_ptr PCHContainerOps) : Tool(Compilations, SourcePaths, std::move(PCHContainerOps), std::move(BaseFS)), Index: cfe/trunk/lib/Tooling/Tooling.cpp =================================================================== --- cfe/trunk/lib/Tooling/Tooling.cpp +++ cfe/trunk/lib/Tooling/Tooling.cpp @@ -19,7 +19,6 @@ #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemOptions.h" #include "clang/Basic/LLVM.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/Job.h" @@ -51,6 +50,7 @@ #include "llvm/Support/Host.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" +#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include #include @@ -74,9 +74,9 @@ // it to be based on the same framework. /// Builds a clang driver initialized for running clang tools. -static driver::Driver *newDriver( - DiagnosticsEngine *Diagnostics, const char *BinaryName, - IntrusiveRefCntPtr VFS) { +static driver::Driver * +newDriver(DiagnosticsEngine *Diagnostics, const char *BinaryName, + IntrusiveRefCntPtr VFS) { driver::Driver *CompilerDriver = new driver::Driver(BinaryName, llvm::sys::getDefaultTargetTriple(), *Diagnostics, std::move(VFS)); @@ -155,7 +155,7 @@ bool runToolOnCodeWithArgs( FrontendAction *ToolAction, const Twine &Code, - llvm::IntrusiveRefCntPtr VFS, + llvm::IntrusiveRefCntPtr VFS, const std::vector &Args, const Twine &FileName, const Twine &ToolName, std::shared_ptr PCHContainerOps) { @@ -178,10 +178,10 @@ const Twine &ToolName, std::shared_ptr PCHContainerOps, const FileContentMappings &VirtualMappedFiles) { - llvm::IntrusiveRefCntPtr OverlayFileSystem( - new vfs::OverlayFileSystem(vfs::getRealFileSystem())); - llvm::IntrusiveRefCntPtr InMemoryFileSystem( - new vfs::InMemoryFileSystem); + llvm::IntrusiveRefCntPtr OverlayFileSystem( + new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())); + llvm::IntrusiveRefCntPtr InMemoryFileSystem( + new llvm::vfs::InMemoryFileSystem); OverlayFileSystem->pushOverlay(InMemoryFileSystem); SmallString<1024> CodeStorage; @@ -199,7 +199,7 @@ FileName, ToolName); } -llvm::Expected getAbsolutePath(vfs::FileSystem &FS, +llvm::Expected getAbsolutePath(llvm::vfs::FileSystem &FS, StringRef File) { StringRef RelativePath(File); // FIXME: Should '.\\' be accepted on Win32? @@ -215,7 +215,7 @@ } std::string getAbsolutePath(StringRef File) { - return llvm::cantFail(getAbsolutePath(*vfs::getRealFileSystem(), File)); + return llvm::cantFail(getAbsolutePath(*llvm::vfs::getRealFileSystem(), File)); } void addTargetAndModeForProgramName(std::vector &CommandLine, @@ -372,11 +372,11 @@ ClangTool::ClangTool(const CompilationDatabase &Compilations, ArrayRef SourcePaths, std::shared_ptr PCHContainerOps, - IntrusiveRefCntPtr BaseFS) + IntrusiveRefCntPtr BaseFS) : Compilations(Compilations), SourcePaths(SourcePaths), PCHContainerOps(std::move(PCHContainerOps)), - OverlayFileSystem(new vfs::OverlayFileSystem(std::move(BaseFS))), - InMemoryFileSystem(new vfs::InMemoryFileSystem), + OverlayFileSystem(new llvm::vfs::OverlayFileSystem(std::move(BaseFS))), + InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem), Files(new FileManager(FileSystemOptions(), OverlayFileSystem)) { OverlayFileSystem->pushOverlay(InMemoryFileSystem); appendArgumentsAdjuster(getClangStripOutputAdjuster()); @@ -586,10 +586,10 @@ std::vector> ASTs; ASTBuilderAction Action(ASTs); - llvm::IntrusiveRefCntPtr OverlayFileSystem( - new vfs::OverlayFileSystem(vfs::getRealFileSystem())); - llvm::IntrusiveRefCntPtr InMemoryFileSystem( - new vfs::InMemoryFileSystem); + llvm::IntrusiveRefCntPtr OverlayFileSystem( + new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())); + llvm::IntrusiveRefCntPtr InMemoryFileSystem( + new llvm::vfs::InMemoryFileSystem); OverlayFileSystem->pushOverlay(InMemoryFileSystem); llvm::IntrusiveRefCntPtr Files( new FileManager(FileSystemOptions(), OverlayFileSystem)); Index: cfe/trunk/tools/clang-format/ClangFormat.cpp =================================================================== --- cfe/trunk/tools/clang-format/ClangFormat.cpp +++ cfe/trunk/tools/clang-format/ClangFormat.cpp @@ -116,7 +116,7 @@ static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source, SourceManager &Sources, FileManager &Files, - vfs::InMemoryFileSystem *MemFS) { + llvm::vfs::InMemoryFileSystem *MemFS) { MemFS->addFileNoOwn(FileName, 0, Source); return Sources.createFileID(Files.getFile(FileName), SourceLocation(), SrcMgr::C_User); @@ -133,8 +133,8 @@ static bool fillRanges(MemoryBuffer *Code, std::vector &Ranges) { - IntrusiveRefCntPtr InMemoryFileSystem( - new vfs::InMemoryFileSystem); + IntrusiveRefCntPtr InMemoryFileSystem( + new llvm::vfs::InMemoryFileSystem); FileManager Files(FileSystemOptions(), InMemoryFileSystem); DiagnosticsEngine Diagnostics( IntrusiveRefCntPtr(new DiagnosticIDs), @@ -301,8 +301,8 @@ outputReplacementsXML(Replaces); outs() << "\n"; } else { - IntrusiveRefCntPtr InMemoryFileSystem( - new vfs::InMemoryFileSystem); + IntrusiveRefCntPtr InMemoryFileSystem( + new llvm::vfs::InMemoryFileSystem); FileManager Files(FileSystemOptions(), InMemoryFileSystem); DiagnosticsEngine Diagnostics( IntrusiveRefCntPtr(new DiagnosticIDs), Index: cfe/trunk/tools/driver/cc1gen_reproducer_main.cpp =================================================================== --- cfe/trunk/tools/driver/cc1gen_reproducer_main.cpp +++ cfe/trunk/tools/driver/cc1gen_reproducer_main.cpp @@ -14,13 +14,13 @@ #include "clang/Basic/Diagnostic.h" #include "clang/Basic/LLVM.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/TargetSelect.h" +#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/YAMLTraits.h" #include "llvm/Support/raw_ostream.h" Index: cfe/trunk/tools/libclang/BuildSystem.cpp =================================================================== --- cfe/trunk/tools/libclang/BuildSystem.cpp +++ cfe/trunk/tools/libclang/BuildSystem.cpp @@ -13,12 +13,12 @@ #include "clang-c/BuildSystem.h" #include "CXString.h" -#include "clang/Basic/VirtualFileSystem.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/CBindingWrapping.h" #include "llvm/Support/Chrono.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Path.h" +#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" using namespace clang; @@ -28,11 +28,11 @@ return llvm::sys::toTimeT(std::chrono::system_clock::now()); } -DEFINE_SIMPLE_CONVERSION_FUNCTIONS(clang::vfs::YAMLVFSWriter, +DEFINE_SIMPLE_CONVERSION_FUNCTIONS(llvm::vfs::YAMLVFSWriter, CXVirtualFileOverlay) CXVirtualFileOverlay clang_VirtualFileOverlay_create(unsigned) { - return wrap(new clang::vfs::YAMLVFSWriter()); + return wrap(new llvm::vfs::YAMLVFSWriter()); } enum CXErrorCode Index: cfe/trunk/unittests/AST/ASTImporterTest.cpp =================================================================== --- cfe/trunk/unittests/AST/ASTImporterTest.cpp +++ cfe/trunk/unittests/AST/ASTImporterTest.cpp @@ -37,10 +37,10 @@ std::unique_ptr &&Buffer) { assert(ToAST); ASTContext &ToCtx = ToAST->getASTContext(); - auto *OFS = static_cast( + auto *OFS = static_cast( ToCtx.getSourceManager().getFileManager().getVirtualFileSystem().get()); - auto *MFS = - static_cast(OFS->overlays_begin()->get()); + auto *MFS = static_cast( + OFS->overlays_begin()->get()); MFS->addFile(FileName, 0, std::move(Buffer)); } @@ -2482,7 +2482,7 @@ LookupRes = ToTU->noload_lookup(ToName); EXPECT_EQ(LookupRes.size(), 1u); EXPECT_EQ(DeclCounter().match(ToTU, Pattern), 1u); - + auto *ToFriendF = cast(Import(FromFriendF, Lang_CXX)); LookupRes = ToTU->noload_lookup(ToName); EXPECT_EQ(LookupRes.size(), 1u); @@ -2758,7 +2758,7 @@ ToR2 = Import(FromR, Lang_CXX); } - + EXPECT_EQ(ToR1, ToR2); } Index: cfe/trunk/unittests/AST/CommentTextTest.cpp =================================================================== --- cfe/trunk/unittests/AST/CommentTextTest.cpp +++ cfe/trunk/unittests/AST/CommentTextTest.cpp @@ -20,8 +20,8 @@ #include "clang/Basic/FileSystemOptions.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/SourceManager.h" -#include "clang/Basic/VirtualFileSystem.h" #include "llvm/Support/MemoryBuffer.h" +#include "llvm/Support/VirtualFileSystem.h" #include namespace clang { Index: cfe/trunk/unittests/Basic/CMakeLists.txt =================================================================== --- cfe/trunk/unittests/Basic/CMakeLists.txt +++ cfe/trunk/unittests/Basic/CMakeLists.txt @@ -9,7 +9,6 @@ FixedPointTest.cpp MemoryBufferCacheTest.cpp SourceManagerTest.cpp - VirtualFileSystemTest.cpp ) target_link_libraries(BasicTests Index: cfe/trunk/unittests/Basic/FileManagerTest.cpp =================================================================== --- cfe/trunk/unittests/Basic/FileManagerTest.cpp +++ cfe/trunk/unittests/Basic/FileManagerTest.cpp @@ -10,9 +10,9 @@ #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemOptions.h" #include "clang/Basic/FileSystemStatCache.h" -#include "clang/Basic/VirtualFileSystem.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Path.h" +#include "llvm/Support/VirtualFileSystem.h" #include "gtest/gtest.h" using namespace llvm; @@ -60,8 +60,8 @@ // Implement FileSystemStatCache::getStat(). LookupResult getStat(StringRef Path, FileData &Data, bool isFile, - std::unique_ptr *F, - vfs::FileSystem &FS) override { + std::unique_ptr *F, + llvm::vfs::FileSystem &FS) override { #ifndef _WIN32 SmallString<128> NormalizedPath(Path); llvm::sys::path::native(NormalizedPath); @@ -305,8 +305,8 @@ #endif llvm::sys::path::append(CustomWorkingDir, "some", "weird", "path"); - auto FS = - IntrusiveRefCntPtr(new vfs::InMemoryFileSystem); + auto FS = IntrusiveRefCntPtr( + new llvm::vfs::InMemoryFileSystem); // setCurrentworkingdirectory must finish without error. ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir)); Index: cfe/trunk/unittests/Basic/VirtualFileSystemTest.cpp =================================================================== --- cfe/trunk/unittests/Basic/VirtualFileSystemTest.cpp +++ cfe/trunk/unittests/Basic/VirtualFileSystemTest.cpp @@ -1,1592 +0,0 @@ -//===- unittests/Basic/VirtualFileSystem.cpp ---------------- VFS tests ---===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "clang/Basic/VirtualFileSystem.h" -#include "llvm/ADT/Triple.h" -#include "llvm/Config/llvm-config.h" -#include "llvm/Support/Errc.h" -#include "llvm/Support/Host.h" -#include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/Path.h" -#include "llvm/Support/SourceMgr.h" -#include "gmock/gmock.h" -#include "gtest/gtest.h" -#include -#include - -using namespace clang; -using namespace llvm; -using llvm::sys::fs::UniqueID; -using testing::ElementsAre; -using testing::Pair; -using testing::UnorderedElementsAre; - -namespace { -struct DummyFile : public vfs::File { - vfs::Status S; - explicit DummyFile(vfs::Status S) : S(S) {} - llvm::ErrorOr status() override { return S; } - llvm::ErrorOr> - getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator, - bool IsVolatile) override { - llvm_unreachable("unimplemented"); - } - std::error_code close() override { return std::error_code(); } -}; - -class DummyFileSystem : public vfs::FileSystem { - int FSID; // used to produce UniqueIDs - int FileID; // used to produce UniqueIDs - std::map FilesAndDirs; - - static int getNextFSID() { - static int Count = 0; - return Count++; - } - -public: - DummyFileSystem() : FSID(getNextFSID()), FileID(0) {} - - ErrorOr status(const Twine &Path) override { - std::map::iterator I = - FilesAndDirs.find(Path.str()); - if (I == FilesAndDirs.end()) - return make_error_code(llvm::errc::no_such_file_or_directory); - return I->second; - } - ErrorOr> - openFileForRead(const Twine &Path) override { - auto S = status(Path); - if (S) - return std::unique_ptr(new DummyFile{*S}); - return S.getError(); - } - llvm::ErrorOr getCurrentWorkingDirectory() const override { - return std::string(); - } - std::error_code setCurrentWorkingDirectory(const Twine &Path) override { - return std::error_code(); - } - // Map any symlink to "/symlink". - std::error_code getRealPath(const Twine &Path, - SmallVectorImpl &Output) const override { - auto I = FilesAndDirs.find(Path.str()); - if (I == FilesAndDirs.end()) - return make_error_code(llvm::errc::no_such_file_or_directory); - if (I->second.isSymlink()) { - Output.clear(); - Twine("/symlink").toVector(Output); - return std::error_code(); - } - Output.clear(); - Path.toVector(Output); - return std::error_code(); - } - - struct DirIterImpl : public clang::vfs::detail::DirIterImpl { - std::map &FilesAndDirs; - std::map::iterator I; - std::string Path; - bool isInPath(StringRef S) { - if (Path.size() < S.size() && S.find(Path) == 0) { - auto LastSep = S.find_last_of('/'); - if (LastSep == Path.size() || LastSep == Path.size()-1) - return true; - } - return false; - } - DirIterImpl(std::map &FilesAndDirs, - const Twine &_Path) - : FilesAndDirs(FilesAndDirs), I(FilesAndDirs.begin()), - Path(_Path.str()) { - for ( ; I != FilesAndDirs.end(); ++I) { - if (isInPath(I->first)) { - CurrentEntry = - vfs::directory_entry(I->second.getName(), I->second.getType()); - break; - } - } - } - std::error_code increment() override { - ++I; - for ( ; I != FilesAndDirs.end(); ++I) { - if (isInPath(I->first)) { - CurrentEntry = - vfs::directory_entry(I->second.getName(), I->second.getType()); - break; - } - } - if (I == FilesAndDirs.end()) - CurrentEntry = vfs::directory_entry(); - return std::error_code(); - } - }; - - vfs::directory_iterator dir_begin(const Twine &Dir, - std::error_code &EC) override { - return vfs::directory_iterator( - std::make_shared(FilesAndDirs, Dir)); - } - - void addEntry(StringRef Path, const vfs::Status &Status) { - FilesAndDirs[Path] = Status; - } - - void addRegularFile(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) { - vfs::Status S(Path, UniqueID(FSID, FileID++), - std::chrono::system_clock::now(), 0, 0, 1024, - sys::fs::file_type::regular_file, Perms); - addEntry(Path, S); - } - - void addDirectory(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) { - vfs::Status S(Path, UniqueID(FSID, FileID++), - std::chrono::system_clock::now(), 0, 0, 0, - sys::fs::file_type::directory_file, Perms); - addEntry(Path, S); - } - - void addSymlink(StringRef Path) { - vfs::Status S(Path, UniqueID(FSID, FileID++), - std::chrono::system_clock::now(), 0, 0, 0, - sys::fs::file_type::symlink_file, sys::fs::all_all); - addEntry(Path, S); - } -}; - -/// Replace back-slashes by front-slashes. -std::string getPosixPath(std::string S) { - SmallString<128> Result; - llvm::sys::path::native(S, Result, llvm::sys::path::Style::posix); - return Result.str(); -} -} // end anonymous namespace - -TEST(VirtualFileSystemTest, StatusQueries) { - IntrusiveRefCntPtr D(new DummyFileSystem()); - ErrorOr Status((std::error_code())); - - D->addRegularFile("/foo"); - Status = D->status("/foo"); - ASSERT_FALSE(Status.getError()); - EXPECT_TRUE(Status->isStatusKnown()); - EXPECT_FALSE(Status->isDirectory()); - EXPECT_TRUE(Status->isRegularFile()); - EXPECT_FALSE(Status->isSymlink()); - EXPECT_FALSE(Status->isOther()); - EXPECT_TRUE(Status->exists()); - - D->addDirectory("/bar"); - Status = D->status("/bar"); - ASSERT_FALSE(Status.getError()); - EXPECT_TRUE(Status->isStatusKnown()); - EXPECT_TRUE(Status->isDirectory()); - EXPECT_FALSE(Status->isRegularFile()); - EXPECT_FALSE(Status->isSymlink()); - EXPECT_FALSE(Status->isOther()); - EXPECT_TRUE(Status->exists()); - - D->addSymlink("/baz"); - Status = D->status("/baz"); - ASSERT_FALSE(Status.getError()); - EXPECT_TRUE(Status->isStatusKnown()); - EXPECT_FALSE(Status->isDirectory()); - EXPECT_FALSE(Status->isRegularFile()); - EXPECT_TRUE(Status->isSymlink()); - EXPECT_FALSE(Status->isOther()); - EXPECT_TRUE(Status->exists()); - - EXPECT_TRUE(Status->equivalent(*Status)); - ErrorOr Status2 = D->status("/foo"); - ASSERT_FALSE(Status2.getError()); - EXPECT_FALSE(Status->equivalent(*Status2)); -} - -TEST(VirtualFileSystemTest, BaseOnlyOverlay) { - IntrusiveRefCntPtr D(new DummyFileSystem()); - ErrorOr Status((std::error_code())); - EXPECT_FALSE(Status = D->status("/foo")); - - IntrusiveRefCntPtr O(new vfs::OverlayFileSystem(D)); - EXPECT_FALSE(Status = O->status("/foo")); - - D->addRegularFile("/foo"); - Status = D->status("/foo"); - EXPECT_FALSE(Status.getError()); - - ErrorOr Status2((std::error_code())); - Status2 = O->status("/foo"); - EXPECT_FALSE(Status2.getError()); - EXPECT_TRUE(Status->equivalent(*Status2)); -} - -TEST(VirtualFileSystemTest, GetRealPathInOverlay) { - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - Lower->addRegularFile("/foo"); - Lower->addSymlink("/lower_link"); - IntrusiveRefCntPtr Upper(new DummyFileSystem()); - - IntrusiveRefCntPtr O( - new vfs::OverlayFileSystem(Lower)); - O->pushOverlay(Upper); - - // Regular file. - SmallString<16> RealPath; - EXPECT_FALSE(O->getRealPath("/foo", RealPath)); - EXPECT_EQ(RealPath.str(), "/foo"); - - // Expect no error getting real path for symlink in lower overlay. - EXPECT_FALSE(O->getRealPath("/lower_link", RealPath)); - EXPECT_EQ(RealPath.str(), "/symlink"); - - // Try a non-existing link. - EXPECT_EQ(O->getRealPath("/upper_link", RealPath), - errc::no_such_file_or_directory); - - // Add a new symlink in upper. - Upper->addSymlink("/upper_link"); - EXPECT_FALSE(O->getRealPath("/upper_link", RealPath)); - EXPECT_EQ(RealPath.str(), "/symlink"); -} - -TEST(VirtualFileSystemTest, OverlayFiles) { - IntrusiveRefCntPtr Base(new DummyFileSystem()); - IntrusiveRefCntPtr Middle(new DummyFileSystem()); - IntrusiveRefCntPtr Top(new DummyFileSystem()); - IntrusiveRefCntPtr O( - new vfs::OverlayFileSystem(Base)); - O->pushOverlay(Middle); - O->pushOverlay(Top); - - ErrorOr Status1((std::error_code())), - Status2((std::error_code())), Status3((std::error_code())), - StatusB((std::error_code())), StatusM((std::error_code())), - StatusT((std::error_code())); - - Base->addRegularFile("/foo"); - StatusB = Base->status("/foo"); - ASSERT_FALSE(StatusB.getError()); - Status1 = O->status("/foo"); - ASSERT_FALSE(Status1.getError()); - Middle->addRegularFile("/foo"); - StatusM = Middle->status("/foo"); - ASSERT_FALSE(StatusM.getError()); - Status2 = O->status("/foo"); - ASSERT_FALSE(Status2.getError()); - Top->addRegularFile("/foo"); - StatusT = Top->status("/foo"); - ASSERT_FALSE(StatusT.getError()); - Status3 = O->status("/foo"); - ASSERT_FALSE(Status3.getError()); - - EXPECT_TRUE(Status1->equivalent(*StatusB)); - EXPECT_TRUE(Status2->equivalent(*StatusM)); - EXPECT_TRUE(Status3->equivalent(*StatusT)); - - EXPECT_FALSE(Status1->equivalent(*Status2)); - EXPECT_FALSE(Status2->equivalent(*Status3)); - EXPECT_FALSE(Status1->equivalent(*Status3)); -} - -TEST(VirtualFileSystemTest, OverlayDirsNonMerged) { - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - IntrusiveRefCntPtr Upper(new DummyFileSystem()); - IntrusiveRefCntPtr O( - new vfs::OverlayFileSystem(Lower)); - O->pushOverlay(Upper); - - Lower->addDirectory("/lower-only"); - Upper->addDirectory("/upper-only"); - - // non-merged paths should be the same - ErrorOr Status1 = Lower->status("/lower-only"); - ASSERT_FALSE(Status1.getError()); - ErrorOr Status2 = O->status("/lower-only"); - ASSERT_FALSE(Status2.getError()); - EXPECT_TRUE(Status1->equivalent(*Status2)); - - Status1 = Upper->status("/upper-only"); - ASSERT_FALSE(Status1.getError()); - Status2 = O->status("/upper-only"); - ASSERT_FALSE(Status2.getError()); - EXPECT_TRUE(Status1->equivalent(*Status2)); -} - -TEST(VirtualFileSystemTest, MergedDirPermissions) { - // merged directories get the permissions of the upper dir - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - IntrusiveRefCntPtr Upper(new DummyFileSystem()); - IntrusiveRefCntPtr O( - new vfs::OverlayFileSystem(Lower)); - O->pushOverlay(Upper); - - ErrorOr Status((std::error_code())); - Lower->addDirectory("/both", sys::fs::owner_read); - Upper->addDirectory("/both", sys::fs::owner_all | sys::fs::group_read); - Status = O->status("/both"); - ASSERT_FALSE(Status.getError()); - EXPECT_EQ(0740, Status->getPermissions()); - - // permissions (as usual) are not recursively applied - Lower->addRegularFile("/both/foo", sys::fs::owner_read); - Upper->addRegularFile("/both/bar", sys::fs::owner_write); - Status = O->status("/both/foo"); - ASSERT_FALSE( Status.getError()); - EXPECT_EQ(0400, Status->getPermissions()); - Status = O->status("/both/bar"); - ASSERT_FALSE(Status.getError()); - EXPECT_EQ(0200, Status->getPermissions()); -} - -namespace { -struct ScopedDir { - SmallString<128> Path; - ScopedDir(const Twine &Name, bool Unique=false) { - std::error_code EC; - if (Unique) { - EC = llvm::sys::fs::createUniqueDirectory(Name, Path); - } else { - Path = Name.str(); - EC = llvm::sys::fs::create_directory(Twine(Path)); - } - if (EC) - Path = ""; - EXPECT_FALSE(EC); - } - ~ScopedDir() { - if (Path != "") { - EXPECT_FALSE(llvm::sys::fs::remove(Path.str())); - } - } - operator StringRef() { return Path.str(); } -}; - -struct ScopedLink { - SmallString<128> Path; - ScopedLink(const Twine &To, const Twine &From) { - Path = From.str(); - std::error_code EC = sys::fs::create_link(To, From); - if (EC) - Path = ""; - EXPECT_FALSE(EC); - } - ~ScopedLink() { - if (Path != "") { - EXPECT_FALSE(llvm::sys::fs::remove(Path.str())); - } - } - operator StringRef() { return Path.str(); } -}; -} // end anonymous namespace - -TEST(VirtualFileSystemTest, BasicRealFSIteration) { - ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/true); - IntrusiveRefCntPtr FS = vfs::getRealFileSystem(); - - std::error_code EC; - vfs::directory_iterator I = FS->dir_begin(Twine(TestDirectory), EC); - ASSERT_FALSE(EC); - EXPECT_EQ(vfs::directory_iterator(), I); // empty directory is empty - - ScopedDir _a(TestDirectory+"/a"); - ScopedDir _ab(TestDirectory+"/a/b"); - ScopedDir _c(TestDirectory+"/c"); - ScopedDir _cd(TestDirectory+"/c/d"); - - I = FS->dir_begin(Twine(TestDirectory), EC); - ASSERT_FALSE(EC); - ASSERT_NE(vfs::directory_iterator(), I); - // Check either a or c, since we can't rely on the iteration order. - EXPECT_TRUE(I->path().endswith("a") || I->path().endswith("c")); - I.increment(EC); - ASSERT_FALSE(EC); - ASSERT_NE(vfs::directory_iterator(), I); - EXPECT_TRUE(I->path().endswith("a") || I->path().endswith("c")); - I.increment(EC); - EXPECT_EQ(vfs::directory_iterator(), I); -} - -#ifdef LLVM_ON_UNIX -TEST(VirtualFileSystemTest, BrokenSymlinkRealFSIteration) { - ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/ true); - IntrusiveRefCntPtr FS = vfs::getRealFileSystem(); - - ScopedLink _a("no_such_file", TestDirectory + "/a"); - ScopedDir _b(TestDirectory + "/b"); - ScopedLink _c("no_such_file", TestDirectory + "/c"); - - // Should get no iteration error, but a stat error for the broken symlinks. - std::map StatResults; - std::error_code EC; - for (vfs::directory_iterator I = FS->dir_begin(Twine(TestDirectory), EC), E; - I != E; I.increment(EC)) { - EXPECT_FALSE(EC); - StatResults[sys::path::filename(I->path())] = - FS->status(I->path()).getError(); - } - EXPECT_THAT( - StatResults, - ElementsAre( - Pair("a", std::make_error_code(std::errc::no_such_file_or_directory)), - Pair("b", std::error_code()), - Pair("c", - std::make_error_code(std::errc::no_such_file_or_directory)))); -} -#endif - -TEST(VirtualFileSystemTest, BasicRealFSRecursiveIteration) { - ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/true); - IntrusiveRefCntPtr FS = vfs::getRealFileSystem(); - - std::error_code EC; - auto I = vfs::recursive_directory_iterator(*FS, Twine(TestDirectory), EC); - ASSERT_FALSE(EC); - EXPECT_EQ(vfs::recursive_directory_iterator(), I); // empty directory is empty - - ScopedDir _a(TestDirectory+"/a"); - ScopedDir _ab(TestDirectory+"/a/b"); - ScopedDir _c(TestDirectory+"/c"); - ScopedDir _cd(TestDirectory+"/c/d"); - - I = vfs::recursive_directory_iterator(*FS, Twine(TestDirectory), EC); - ASSERT_FALSE(EC); - ASSERT_NE(vfs::recursive_directory_iterator(), I); - - std::vector Contents; - for (auto E = vfs::recursive_directory_iterator(); !EC && I != E; - I.increment(EC)) { - Contents.push_back(I->path()); - } - - // Check contents, which may be in any order - EXPECT_EQ(4U, Contents.size()); - int Counts[4] = { 0, 0, 0, 0 }; - for (const std::string &Name : Contents) { - ASSERT_FALSE(Name.empty()); - int Index = Name[Name.size()-1] - 'a'; - ASSERT_TRUE(Index >= 0 && Index < 4); - Counts[Index]++; - } - EXPECT_EQ(1, Counts[0]); // a - EXPECT_EQ(1, Counts[1]); // b - EXPECT_EQ(1, Counts[2]); // c - EXPECT_EQ(1, Counts[3]); // d -} - -#ifdef LLVM_ON_UNIX -TEST(VirtualFileSystemTest, BrokenSymlinkRealFSRecursiveIteration) { - ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/ true); - IntrusiveRefCntPtr FS = vfs::getRealFileSystem(); - - ScopedLink _a("no_such_file", TestDirectory + "/a"); - ScopedDir _b(TestDirectory + "/b"); - ScopedLink _ba("no_such_file", TestDirectory + "/b/a"); - ScopedDir _bb(TestDirectory + "/b/b"); - ScopedLink _bc("no_such_file", TestDirectory + "/b/c"); - ScopedLink _c("no_such_file", TestDirectory + "/c"); - ScopedDir _d(TestDirectory + "/d"); - ScopedDir _dd(TestDirectory + "/d/d"); - ScopedDir _ddd(TestDirectory + "/d/d/d"); - ScopedLink _e("no_such_file", TestDirectory + "/e"); - - std::vector VisitedBrokenSymlinks; - std::vector VisitedNonBrokenSymlinks; - std::error_code EC; - for (vfs::recursive_directory_iterator I(*FS, Twine(TestDirectory), EC), E; - I != E; I.increment(EC)) { - EXPECT_FALSE(EC); - (FS->status(I->path()) ? VisitedNonBrokenSymlinks : VisitedBrokenSymlinks) - .push_back(I->path()); - } - - // Check visited file names. - EXPECT_THAT(VisitedBrokenSymlinks, - UnorderedElementsAre(StringRef(_a), StringRef(_ba), - StringRef(_bc), StringRef(_c), - StringRef(_e))); - EXPECT_THAT(VisitedNonBrokenSymlinks, - UnorderedElementsAre(StringRef(_b), StringRef(_bb), StringRef(_d), - StringRef(_dd), StringRef(_ddd))); -} -#endif - -template -static void checkContents(DirIter I, ArrayRef ExpectedOut) { - std::error_code EC; - SmallVector Expected(ExpectedOut.begin(), ExpectedOut.end()); - SmallVector InputToCheck; - - // Do not rely on iteration order to check for contents, sort both - // content vectors before comparison. - for (DirIter E; !EC && I != E; I.increment(EC)) - InputToCheck.push_back(I->path()); - - llvm::sort(InputToCheck); - llvm::sort(Expected); - EXPECT_EQ(InputToCheck.size(), Expected.size()); - - unsigned LastElt = std::min(InputToCheck.size(), Expected.size()); - for (unsigned Idx = 0; Idx != LastElt; ++Idx) - EXPECT_EQ(StringRef(InputToCheck[Idx]), Expected[Idx]); -} - -TEST(VirtualFileSystemTest, OverlayIteration) { - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - IntrusiveRefCntPtr Upper(new DummyFileSystem()); - IntrusiveRefCntPtr O( - new vfs::OverlayFileSystem(Lower)); - O->pushOverlay(Upper); - - std::error_code EC; - checkContents(O->dir_begin("/", EC), ArrayRef()); - - Lower->addRegularFile("/file1"); - checkContents(O->dir_begin("/", EC), ArrayRef("/file1")); - - Upper->addRegularFile("/file2"); - checkContents(O->dir_begin("/", EC), {"/file2", "/file1"}); - - Lower->addDirectory("/dir1"); - Lower->addRegularFile("/dir1/foo"); - Upper->addDirectory("/dir2"); - Upper->addRegularFile("/dir2/foo"); - checkContents(O->dir_begin("/dir2", EC), ArrayRef("/dir2/foo")); - checkContents(O->dir_begin("/", EC), {"/dir2", "/file2", "/dir1", "/file1"}); -} - -TEST(VirtualFileSystemTest, OverlayRecursiveIteration) { - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - IntrusiveRefCntPtr Middle(new DummyFileSystem()); - IntrusiveRefCntPtr Upper(new DummyFileSystem()); - IntrusiveRefCntPtr O( - new vfs::OverlayFileSystem(Lower)); - O->pushOverlay(Middle); - O->pushOverlay(Upper); - - std::error_code EC; - checkContents(vfs::recursive_directory_iterator(*O, "/", EC), - ArrayRef()); - - Lower->addRegularFile("/file1"); - checkContents(vfs::recursive_directory_iterator(*O, "/", EC), - ArrayRef("/file1")); - - Upper->addDirectory("/dir"); - Upper->addRegularFile("/dir/file2"); - checkContents(vfs::recursive_directory_iterator(*O, "/", EC), - {"/dir", "/dir/file2", "/file1"}); - - Lower->addDirectory("/dir1"); - Lower->addRegularFile("/dir1/foo"); - Lower->addDirectory("/dir1/a"); - Lower->addRegularFile("/dir1/a/b"); - Middle->addDirectory("/a"); - Middle->addDirectory("/a/b"); - Middle->addDirectory("/a/b/c"); - Middle->addRegularFile("/a/b/c/d"); - Middle->addRegularFile("/hiddenByUp"); - Upper->addDirectory("/dir2"); - Upper->addRegularFile("/dir2/foo"); - Upper->addRegularFile("/hiddenByUp"); - checkContents(vfs::recursive_directory_iterator(*O, "/dir2", EC), - ArrayRef("/dir2/foo")); - checkContents(vfs::recursive_directory_iterator(*O, "/", EC), - {"/dir", "/dir/file2", "/dir2", "/dir2/foo", "/hiddenByUp", - "/a", "/a/b", "/a/b/c", "/a/b/c/d", "/dir1", "/dir1/a", - "/dir1/a/b", "/dir1/foo", "/file1"}); -} - -TEST(VirtualFileSystemTest, ThreeLevelIteration) { - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - IntrusiveRefCntPtr Middle(new DummyFileSystem()); - IntrusiveRefCntPtr Upper(new DummyFileSystem()); - IntrusiveRefCntPtr O( - new vfs::OverlayFileSystem(Lower)); - O->pushOverlay(Middle); - O->pushOverlay(Upper); - - std::error_code EC; - checkContents(O->dir_begin("/", EC), ArrayRef()); - - Middle->addRegularFile("/file2"); - checkContents(O->dir_begin("/", EC), ArrayRef("/file2")); - - Lower->addRegularFile("/file1"); - Upper->addRegularFile("/file3"); - checkContents(O->dir_begin("/", EC), {"/file3", "/file2", "/file1"}); -} - -TEST(VirtualFileSystemTest, HiddenInIteration) { - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - IntrusiveRefCntPtr Middle(new DummyFileSystem()); - IntrusiveRefCntPtr Upper(new DummyFileSystem()); - IntrusiveRefCntPtr O( - new vfs::OverlayFileSystem(Lower)); - O->pushOverlay(Middle); - O->pushOverlay(Upper); - - std::error_code EC; - Lower->addRegularFile("/onlyInLow"); - Lower->addDirectory("/hiddenByMid"); - Lower->addDirectory("/hiddenByUp"); - Middle->addRegularFile("/onlyInMid"); - Middle->addRegularFile("/hiddenByMid"); - Middle->addDirectory("/hiddenByUp"); - Upper->addRegularFile("/onlyInUp"); - Upper->addRegularFile("/hiddenByUp"); - checkContents( - O->dir_begin("/", EC), - {"/hiddenByUp", "/onlyInUp", "/hiddenByMid", "/onlyInMid", "/onlyInLow"}); - - // Make sure we get the top-most entry - { - std::error_code EC; - vfs::directory_iterator I = O->dir_begin("/", EC), E; - for ( ; !EC && I != E; I.increment(EC)) - if (I->path() == "/hiddenByUp") - break; - ASSERT_NE(E, I); - EXPECT_EQ(sys::fs::file_type::regular_file, I->type()); - } - { - std::error_code EC; - vfs::directory_iterator I = O->dir_begin("/", EC), E; - for ( ; !EC && I != E; I.increment(EC)) - if (I->path() == "/hiddenByMid") - break; - ASSERT_NE(E, I); - EXPECT_EQ(sys::fs::file_type::regular_file, I->type()); - } -} - -class InMemoryFileSystemTest : public ::testing::Test { -protected: - clang::vfs::InMemoryFileSystem FS; - clang::vfs::InMemoryFileSystem NormalizedFS; - - InMemoryFileSystemTest() - : FS(/*UseNormalizedPaths=*/false), - NormalizedFS(/*UseNormalizedPaths=*/true) {} -}; - -MATCHER_P2(IsHardLinkTo, FS, Target, "") { - StringRef From = arg; - StringRef To = Target; - auto OpenedFrom = FS->openFileForRead(From); - auto OpenedTo = FS->openFileForRead(To); - return !OpenedFrom.getError() && !OpenedTo.getError() && - (*OpenedFrom)->status()->getUniqueID() == - (*OpenedTo)->status()->getUniqueID(); -} - -TEST_F(InMemoryFileSystemTest, IsEmpty) { - auto Stat = FS.status("/a"); - ASSERT_EQ(Stat.getError(),errc::no_such_file_or_directory) << FS.toString(); - Stat = FS.status("/"); - ASSERT_EQ(Stat.getError(), errc::no_such_file_or_directory) << FS.toString(); -} - -TEST_F(InMemoryFileSystemTest, WindowsPath) { - FS.addFile("c:/windows/system128/foo.cpp", 0, MemoryBuffer::getMemBuffer("")); - auto Stat = FS.status("c:"); -#if !defined(_WIN32) - ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString(); -#endif - Stat = FS.status("c:/windows/system128/foo.cpp"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString(); - FS.addFile("d:/windows/foo.cpp", 0, MemoryBuffer::getMemBuffer("")); - Stat = FS.status("d:/windows/foo.cpp"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString(); -} - -TEST_F(InMemoryFileSystemTest, OverlayFile) { - FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a")); - NormalizedFS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a")); - auto Stat = FS.status("/"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString(); - Stat = FS.status("/."); - ASSERT_FALSE(Stat); - Stat = NormalizedFS.status("/."); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString(); - Stat = FS.status("/a"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_EQ("/a", Stat->getName()); -} - -TEST_F(InMemoryFileSystemTest, OverlayFileNoOwn) { - auto Buf = MemoryBuffer::getMemBuffer("a"); - FS.addFileNoOwn("/a", 0, Buf.get()); - auto Stat = FS.status("/a"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_EQ("/a", Stat->getName()); -} - -TEST_F(InMemoryFileSystemTest, OpenFileForRead) { - FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a")); - FS.addFile("././c", 0, MemoryBuffer::getMemBuffer("c")); - FS.addFile("./d/../d", 0, MemoryBuffer::getMemBuffer("d")); - NormalizedFS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a")); - NormalizedFS.addFile("././c", 0, MemoryBuffer::getMemBuffer("c")); - NormalizedFS.addFile("./d/../d", 0, MemoryBuffer::getMemBuffer("d")); - auto File = FS.openFileForRead("/a"); - ASSERT_EQ("a", (*(*File)->getBuffer("ignored"))->getBuffer()); - File = FS.openFileForRead("/a"); // Open again. - ASSERT_EQ("a", (*(*File)->getBuffer("ignored"))->getBuffer()); - File = NormalizedFS.openFileForRead("/././a"); // Open again. - ASSERT_EQ("a", (*(*File)->getBuffer("ignored"))->getBuffer()); - File = FS.openFileForRead("/"); - ASSERT_EQ(File.getError(), errc::invalid_argument) << FS.toString(); - File = FS.openFileForRead("/b"); - ASSERT_EQ(File.getError(), errc::no_such_file_or_directory) << FS.toString(); - File = FS.openFileForRead("./c"); - ASSERT_FALSE(File); - File = FS.openFileForRead("e/../d"); - ASSERT_FALSE(File); - File = NormalizedFS.openFileForRead("./c"); - ASSERT_EQ("c", (*(*File)->getBuffer("ignored"))->getBuffer()); - File = NormalizedFS.openFileForRead("e/../d"); - ASSERT_EQ("d", (*(*File)->getBuffer("ignored"))->getBuffer()); -} - -TEST_F(InMemoryFileSystemTest, DuplicatedFile) { - ASSERT_TRUE(FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a"))); - ASSERT_FALSE(FS.addFile("/a/b", 0, MemoryBuffer::getMemBuffer("a"))); - ASSERT_TRUE(FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a"))); - ASSERT_FALSE(FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("b"))); -} - -TEST_F(InMemoryFileSystemTest, DirectoryIteration) { - FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("")); - FS.addFile("/b/c", 0, MemoryBuffer::getMemBuffer("")); - - std::error_code EC; - vfs::directory_iterator I = FS.dir_begin("/", EC); - ASSERT_FALSE(EC); - ASSERT_EQ("/a", I->path()); - I.increment(EC); - ASSERT_FALSE(EC); - ASSERT_EQ("/b", I->path()); - I.increment(EC); - ASSERT_FALSE(EC); - ASSERT_EQ(vfs::directory_iterator(), I); - - I = FS.dir_begin("/b", EC); - ASSERT_FALSE(EC); - // When on Windows, we end up with "/b\\c" as the name. Convert to Posix - // path for the sake of the comparison. - ASSERT_EQ("/b/c", getPosixPath(I->path())); - I.increment(EC); - ASSERT_FALSE(EC); - ASSERT_EQ(vfs::directory_iterator(), I); -} - -TEST_F(InMemoryFileSystemTest, WorkingDirectory) { - FS.setCurrentWorkingDirectory("/b"); - FS.addFile("c", 0, MemoryBuffer::getMemBuffer("")); - - auto Stat = FS.status("/b/c"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_EQ("/b/c", Stat->getName()); - ASSERT_EQ("/b", *FS.getCurrentWorkingDirectory()); - - Stat = FS.status("c"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - - NormalizedFS.setCurrentWorkingDirectory("/b/c"); - NormalizedFS.setCurrentWorkingDirectory("."); - ASSERT_EQ("/b/c", - getPosixPath(NormalizedFS.getCurrentWorkingDirectory().get())); - NormalizedFS.setCurrentWorkingDirectory(".."); - ASSERT_EQ("/b", - getPosixPath(NormalizedFS.getCurrentWorkingDirectory().get())); -} - -#if !defined(_WIN32) -TEST_F(InMemoryFileSystemTest, GetRealPath) { - SmallString<16> Path; - EXPECT_EQ(FS.getRealPath("b", Path), errc::operation_not_permitted); - - auto GetRealPath = [this](StringRef P) { - SmallString<16> Output; - auto EC = FS.getRealPath(P, Output); - EXPECT_FALSE(EC); - return Output.str().str(); - }; - - FS.setCurrentWorkingDirectory("a"); - EXPECT_EQ(GetRealPath("b"), "a/b"); - EXPECT_EQ(GetRealPath("../b"), "b"); - EXPECT_EQ(GetRealPath("b/./c"), "a/b/c"); - - FS.setCurrentWorkingDirectory("/a"); - EXPECT_EQ(GetRealPath("b"), "/a/b"); - EXPECT_EQ(GetRealPath("../b"), "/b"); - EXPECT_EQ(GetRealPath("b/./c"), "/a/b/c"); -} -#endif // _WIN32 - -TEST_F(InMemoryFileSystemTest, AddFileWithUser) { - FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), 0xFEEDFACE); - auto Stat = FS.status("/a"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_TRUE(Stat->isDirectory()); - ASSERT_EQ(0xFEEDFACE, Stat->getUser()); - Stat = FS.status("/a/b"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_TRUE(Stat->isDirectory()); - ASSERT_EQ(0xFEEDFACE, Stat->getUser()); - Stat = FS.status("/a/b/c"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_TRUE(Stat->isRegularFile()); - ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions()); - ASSERT_EQ(0xFEEDFACE, Stat->getUser()); -} - -TEST_F(InMemoryFileSystemTest, AddFileWithGroup) { - FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, 0xDABBAD00); - auto Stat = FS.status("/a"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_TRUE(Stat->isDirectory()); - ASSERT_EQ(0xDABBAD00, Stat->getGroup()); - Stat = FS.status("/a/b"); - ASSERT_TRUE(Stat->isDirectory()); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_EQ(0xDABBAD00, Stat->getGroup()); - Stat = FS.status("/a/b/c"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_TRUE(Stat->isRegularFile()); - ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions()); - ASSERT_EQ(0xDABBAD00, Stat->getGroup()); -} - -TEST_F(InMemoryFileSystemTest, AddFileWithFileType) { - FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, None, - sys::fs::file_type::socket_file); - auto Stat = FS.status("/a"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_TRUE(Stat->isDirectory()); - Stat = FS.status("/a/b"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_TRUE(Stat->isDirectory()); - Stat = FS.status("/a/b/c"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_EQ(sys::fs::file_type::socket_file, Stat->getType()); - ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions()); -} - -TEST_F(InMemoryFileSystemTest, AddFileWithPerms) { - FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, None, - None, sys::fs::perms::owner_read | sys::fs::perms::owner_write); - auto Stat = FS.status("/a"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_TRUE(Stat->isDirectory()); - ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write | - sys::fs::perms::owner_exe, Stat->getPermissions()); - Stat = FS.status("/a/b"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_TRUE(Stat->isDirectory()); - ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write | - sys::fs::perms::owner_exe, Stat->getPermissions()); - Stat = FS.status("/a/b/c"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_TRUE(Stat->isRegularFile()); - ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write, - Stat->getPermissions()); -} - -TEST_F(InMemoryFileSystemTest, AddDirectoryThenAddChild) { - FS.addFile("/a", 0, MemoryBuffer::getMemBuffer(""), /*User=*/None, - /*Group=*/None, sys::fs::file_type::directory_file); - FS.addFile("/a/b", 0, MemoryBuffer::getMemBuffer("abc"), /*User=*/None, - /*Group=*/None, sys::fs::file_type::regular_file); - auto Stat = FS.status("/a"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_TRUE(Stat->isDirectory()); - Stat = FS.status("/a/b"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); - ASSERT_TRUE(Stat->isRegularFile()); -} - -// Test that the name returned by status() is in the same form as the path that -// was requested (to match the behavior of RealFileSystem). -TEST_F(InMemoryFileSystemTest, StatusName) { - NormalizedFS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), - /*User=*/None, - /*Group=*/None, sys::fs::file_type::regular_file); - NormalizedFS.setCurrentWorkingDirectory("/a/b"); - - // Access using InMemoryFileSystem::status. - auto Stat = NormalizedFS.status("../b/c"); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" - << NormalizedFS.toString(); - ASSERT_TRUE(Stat->isRegularFile()); - ASSERT_EQ("../b/c", Stat->getName()); - - // Access using InMemoryFileAdaptor::status. - auto File = NormalizedFS.openFileForRead("../b/c"); - ASSERT_FALSE(File.getError()) << File.getError() << "\n" - << NormalizedFS.toString(); - Stat = (*File)->status(); - ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" - << NormalizedFS.toString(); - ASSERT_TRUE(Stat->isRegularFile()); - ASSERT_EQ("../b/c", Stat->getName()); - - // Access using a directory iterator. - std::error_code EC; - clang::vfs::directory_iterator It = NormalizedFS.dir_begin("../b", EC); - // When on Windows, we end up with "../b\\c" as the name. Convert to Posix - // path for the sake of the comparison. - ASSERT_EQ("../b/c", getPosixPath(It->path())); -} - -TEST_F(InMemoryFileSystemTest, AddHardLinkToFile) { - StringRef FromLink = "/path/to/FROM/link"; - StringRef Target = "/path/to/TO/file"; - FS.addFile(Target, 0, MemoryBuffer::getMemBuffer("content of target")); - EXPECT_TRUE(FS.addHardLink(FromLink, Target)); - EXPECT_THAT(FromLink, IsHardLinkTo(&FS, Target)); - EXPECT_TRUE(FS.status(FromLink)->getSize() == FS.status(Target)->getSize()); - EXPECT_TRUE(FS.getBufferForFile(FromLink)->get()->getBuffer() == - FS.getBufferForFile(Target)->get()->getBuffer()); -} - -TEST_F(InMemoryFileSystemTest, AddHardLinkInChainPattern) { - StringRef Link0 = "/path/to/0/link"; - StringRef Link1 = "/path/to/1/link"; - StringRef Link2 = "/path/to/2/link"; - StringRef Target = "/path/to/target"; - FS.addFile(Target, 0, MemoryBuffer::getMemBuffer("content of target file")); - EXPECT_TRUE(FS.addHardLink(Link2, Target)); - EXPECT_TRUE(FS.addHardLink(Link1, Link2)); - EXPECT_TRUE(FS.addHardLink(Link0, Link1)); - EXPECT_THAT(Link0, IsHardLinkTo(&FS, Target)); - EXPECT_THAT(Link1, IsHardLinkTo(&FS, Target)); - EXPECT_THAT(Link2, IsHardLinkTo(&FS, Target)); -} - -TEST_F(InMemoryFileSystemTest, AddHardLinkToAFileThatWasNotAddedBefore) { - EXPECT_FALSE(FS.addHardLink("/path/to/link", "/path/to/target")); -} - -TEST_F(InMemoryFileSystemTest, AddHardLinkFromAFileThatWasAddedBefore) { - StringRef Link = "/path/to/link"; - StringRef Target = "/path/to/target"; - FS.addFile(Target, 0, MemoryBuffer::getMemBuffer("content of target")); - FS.addFile(Link, 0, MemoryBuffer::getMemBuffer("content of link")); - EXPECT_FALSE(FS.addHardLink(Link, Target)); -} - -TEST_F(InMemoryFileSystemTest, AddSameHardLinkMoreThanOnce) { - StringRef Link = "/path/to/link"; - StringRef Target = "/path/to/target"; - FS.addFile(Target, 0, MemoryBuffer::getMemBuffer("content of target")); - EXPECT_TRUE(FS.addHardLink(Link, Target)); - EXPECT_FALSE(FS.addHardLink(Link, Target)); -} - -TEST_F(InMemoryFileSystemTest, AddFileInPlaceOfAHardLinkWithSameContent) { - StringRef Link = "/path/to/link"; - StringRef Target = "/path/to/target"; - StringRef Content = "content of target"; - EXPECT_TRUE(FS.addFile(Target, 0, MemoryBuffer::getMemBuffer(Content))); - EXPECT_TRUE(FS.addHardLink(Link, Target)); - EXPECT_TRUE(FS.addFile(Link, 0, MemoryBuffer::getMemBuffer(Content))); -} - -TEST_F(InMemoryFileSystemTest, AddFileInPlaceOfAHardLinkWithDifferentContent) { - StringRef Link = "/path/to/link"; - StringRef Target = "/path/to/target"; - StringRef Content = "content of target"; - StringRef LinkContent = "different content of link"; - EXPECT_TRUE(FS.addFile(Target, 0, MemoryBuffer::getMemBuffer(Content))); - EXPECT_TRUE(FS.addHardLink(Link, Target)); - EXPECT_FALSE(FS.addFile(Link, 0, MemoryBuffer::getMemBuffer(LinkContent))); -} - -TEST_F(InMemoryFileSystemTest, AddHardLinkToADirectory) { - StringRef Dir = "path/to/dummy/dir"; - StringRef Link = "/path/to/link"; - StringRef File = "path/to/dummy/dir/target"; - StringRef Content = "content of target"; - EXPECT_TRUE(FS.addFile(File, 0, MemoryBuffer::getMemBuffer(Content))); - EXPECT_FALSE(FS.addHardLink(Link, Dir)); -} - -TEST_F(InMemoryFileSystemTest, AddHardLinkFromADirectory) { - StringRef Dir = "path/to/dummy/dir"; - StringRef Target = "path/to/dummy/dir/target"; - StringRef Content = "content of target"; - EXPECT_TRUE(FS.addFile(Target, 0, MemoryBuffer::getMemBuffer(Content))); - EXPECT_FALSE(FS.addHardLink(Dir, Target)); -} - -TEST_F(InMemoryFileSystemTest, AddHardLinkUnderAFile) { - StringRef CommonContent = "content string"; - FS.addFile("/a/b", 0, MemoryBuffer::getMemBuffer(CommonContent)); - FS.addFile("/c/d", 0, MemoryBuffer::getMemBuffer(CommonContent)); - EXPECT_FALSE(FS.addHardLink("/c/d/e", "/a/b")); -} - -TEST_F(InMemoryFileSystemTest, RecursiveIterationWithHardLink) { - std::error_code EC; - FS.addFile("/a/b", 0, MemoryBuffer::getMemBuffer("content string")); - EXPECT_TRUE(FS.addHardLink("/c/d", "/a/b")); - auto I = vfs::recursive_directory_iterator(FS, "/", EC); - ASSERT_FALSE(EC); - std::vector Nodes; - for (auto E = vfs::recursive_directory_iterator(); !EC && I != E; - I.increment(EC)) { - Nodes.push_back(getPosixPath(I->path())); - } - EXPECT_THAT(Nodes, testing::UnorderedElementsAre("/a", "/a/b", "/c", "/c/d")); -} - -// NOTE: in the tests below, we use '//root/' as our root directory, since it is -// a legal *absolute* path on Windows as well as *nix. -class VFSFromYAMLTest : public ::testing::Test { -public: - int NumDiagnostics; - - void SetUp() override { NumDiagnostics = 0; } - - static void CountingDiagHandler(const SMDiagnostic &, void *Context) { - VFSFromYAMLTest *Test = static_cast(Context); - ++Test->NumDiagnostics; - } - - IntrusiveRefCntPtr - getFromYAMLRawString(StringRef Content, - IntrusiveRefCntPtr ExternalFS) { - std::unique_ptr Buffer = MemoryBuffer::getMemBuffer(Content); - return getVFSFromYAML(std::move(Buffer), CountingDiagHandler, "", this, - ExternalFS); - } - - IntrusiveRefCntPtr getFromYAMLString( - StringRef Content, - IntrusiveRefCntPtr ExternalFS = new DummyFileSystem()) { - std::string VersionPlusContent("{\n 'version':0,\n"); - VersionPlusContent += Content.slice(Content.find('{') + 1, StringRef::npos); - return getFromYAMLRawString(VersionPlusContent, ExternalFS); - } - - // This is intended as a "XFAIL" for windows hosts. - bool supportsSameDirMultipleYAMLEntries() { - Triple Host(Triple::normalize(sys::getProcessTriple())); - return !Host.isOSWindows(); - } -}; - -TEST_F(VFSFromYAMLTest, BasicVFSFromYAML) { - IntrusiveRefCntPtr FS; - FS = getFromYAMLString(""); - EXPECT_EQ(nullptr, FS.get()); - FS = getFromYAMLString("[]"); - EXPECT_EQ(nullptr, FS.get()); - FS = getFromYAMLString("'string'"); - EXPECT_EQ(nullptr, FS.get()); - EXPECT_EQ(3, NumDiagnostics); -} - -TEST_F(VFSFromYAMLTest, MappedFiles) { - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - Lower->addRegularFile("//root/foo/bar/a"); - IntrusiveRefCntPtr FS = - getFromYAMLString("{ 'roots': [\n" - "{\n" - " 'type': 'directory',\n" - " 'name': '//root/',\n" - " 'contents': [ {\n" - " 'type': 'file',\n" - " 'name': 'file1',\n" - " 'external-contents': '//root/foo/bar/a'\n" - " },\n" - " {\n" - " 'type': 'file',\n" - " 'name': 'file2',\n" - " 'external-contents': '//root/foo/b'\n" - " }\n" - " ]\n" - "}\n" - "]\n" - "}", - Lower); - ASSERT_TRUE(FS.get() != nullptr); - - IntrusiveRefCntPtr O( - new vfs::OverlayFileSystem(Lower)); - O->pushOverlay(FS); - - // file - ErrorOr S = O->status("//root/file1"); - ASSERT_FALSE(S.getError()); - EXPECT_EQ("//root/foo/bar/a", S->getName()); - EXPECT_TRUE(S->IsVFSMapped); - - ErrorOr SLower = O->status("//root/foo/bar/a"); - EXPECT_EQ("//root/foo/bar/a", SLower->getName()); - EXPECT_TRUE(S->equivalent(*SLower)); - EXPECT_FALSE(SLower->IsVFSMapped); - - // file after opening - auto OpenedF = O->openFileForRead("//root/file1"); - ASSERT_FALSE(OpenedF.getError()); - auto OpenedS = (*OpenedF)->status(); - ASSERT_FALSE(OpenedS.getError()); - EXPECT_EQ("//root/foo/bar/a", OpenedS->getName()); - EXPECT_TRUE(OpenedS->IsVFSMapped); - - // directory - S = O->status("//root/"); - ASSERT_FALSE(S.getError()); - EXPECT_TRUE(S->isDirectory()); - EXPECT_TRUE(S->equivalent(*O->status("//root/"))); // non-volatile UniqueID - - // broken mapping - EXPECT_EQ(O->status("//root/file2").getError(), - llvm::errc::no_such_file_or_directory); - EXPECT_EQ(0, NumDiagnostics); -} - -TEST_F(VFSFromYAMLTest, CaseInsensitive) { - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - Lower->addRegularFile("//root/foo/bar/a"); - IntrusiveRefCntPtr FS = - getFromYAMLString("{ 'case-sensitive': 'false',\n" - " 'roots': [\n" - "{\n" - " 'type': 'directory',\n" - " 'name': '//root/',\n" - " 'contents': [ {\n" - " 'type': 'file',\n" - " 'name': 'XX',\n" - " 'external-contents': '//root/foo/bar/a'\n" - " }\n" - " ]\n" - "}]}", - Lower); - ASSERT_TRUE(FS.get() != nullptr); - - IntrusiveRefCntPtr O( - new vfs::OverlayFileSystem(Lower)); - O->pushOverlay(FS); - - ErrorOr S = O->status("//root/XX"); - ASSERT_FALSE(S.getError()); - - ErrorOr SS = O->status("//root/xx"); - ASSERT_FALSE(SS.getError()); - EXPECT_TRUE(S->equivalent(*SS)); - SS = O->status("//root/xX"); - EXPECT_TRUE(S->equivalent(*SS)); - SS = O->status("//root/Xx"); - EXPECT_TRUE(S->equivalent(*SS)); - EXPECT_EQ(0, NumDiagnostics); -} - -TEST_F(VFSFromYAMLTest, CaseSensitive) { - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - Lower->addRegularFile("//root/foo/bar/a"); - IntrusiveRefCntPtr FS = - getFromYAMLString("{ 'case-sensitive': 'true',\n" - " 'roots': [\n" - "{\n" - " 'type': 'directory',\n" - " 'name': '//root/',\n" - " 'contents': [ {\n" - " 'type': 'file',\n" - " 'name': 'XX',\n" - " 'external-contents': '//root/foo/bar/a'\n" - " }\n" - " ]\n" - "}]}", - Lower); - ASSERT_TRUE(FS.get() != nullptr); - - IntrusiveRefCntPtr O( - new vfs::OverlayFileSystem(Lower)); - O->pushOverlay(FS); - - ErrorOr SS = O->status("//root/xx"); - EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory); - SS = O->status("//root/xX"); - EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory); - SS = O->status("//root/Xx"); - EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory); - EXPECT_EQ(0, NumDiagnostics); -} - -TEST_F(VFSFromYAMLTest, IllegalVFSFile) { - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - - // invalid YAML at top-level - IntrusiveRefCntPtr FS = getFromYAMLString("{]", Lower); - EXPECT_EQ(nullptr, FS.get()); - // invalid YAML in roots - FS = getFromYAMLString("{ 'roots':[}", Lower); - // invalid YAML in directory - FS = getFromYAMLString( - "{ 'roots':[ { 'name': 'foo', 'type': 'directory', 'contents': [}", - Lower); - EXPECT_EQ(nullptr, FS.get()); - - // invalid configuration - FS = getFromYAMLString("{ 'knobular': 'true', 'roots':[] }", Lower); - EXPECT_EQ(nullptr, FS.get()); - FS = getFromYAMLString("{ 'case-sensitive': 'maybe', 'roots':[] }", Lower); - EXPECT_EQ(nullptr, FS.get()); - - // invalid roots - FS = getFromYAMLString("{ 'roots':'' }", Lower); - EXPECT_EQ(nullptr, FS.get()); - FS = getFromYAMLString("{ 'roots':{} }", Lower); - EXPECT_EQ(nullptr, FS.get()); - - // invalid entries - FS = getFromYAMLString( - "{ 'roots':[ { 'type': 'other', 'name': 'me', 'contents': '' }", Lower); - EXPECT_EQ(nullptr, FS.get()); - FS = getFromYAMLString("{ 'roots':[ { 'type': 'file', 'name': [], " - "'external-contents': 'other' }", - Lower); - EXPECT_EQ(nullptr, FS.get()); - FS = getFromYAMLString( - "{ 'roots':[ { 'type': 'file', 'name': 'me', 'external-contents': [] }", - Lower); - EXPECT_EQ(nullptr, FS.get()); - FS = getFromYAMLString( - "{ 'roots':[ { 'type': 'file', 'name': 'me', 'external-contents': {} }", - Lower); - EXPECT_EQ(nullptr, FS.get()); - FS = getFromYAMLString( - "{ 'roots':[ { 'type': 'directory', 'name': 'me', 'contents': {} }", - Lower); - EXPECT_EQ(nullptr, FS.get()); - FS = getFromYAMLString( - "{ 'roots':[ { 'type': 'directory', 'name': 'me', 'contents': '' }", - Lower); - EXPECT_EQ(nullptr, FS.get()); - FS = getFromYAMLString( - "{ 'roots':[ { 'thingy': 'directory', 'name': 'me', 'contents': [] }", - Lower); - EXPECT_EQ(nullptr, FS.get()); - - // missing mandatory fields - FS = getFromYAMLString("{ 'roots':[ { 'type': 'file', 'name': 'me' }", Lower); - EXPECT_EQ(nullptr, FS.get()); - FS = getFromYAMLString( - "{ 'roots':[ { 'type': 'file', 'external-contents': 'other' }", Lower); - EXPECT_EQ(nullptr, FS.get()); - FS = getFromYAMLString("{ 'roots':[ { 'name': 'me', 'contents': [] }", Lower); - EXPECT_EQ(nullptr, FS.get()); - - // duplicate keys - FS = getFromYAMLString("{ 'roots':[], 'roots':[] }", Lower); - EXPECT_EQ(nullptr, FS.get()); - FS = getFromYAMLString( - "{ 'case-sensitive':'true', 'case-sensitive':'true', 'roots':[] }", - Lower); - EXPECT_EQ(nullptr, FS.get()); - FS = - getFromYAMLString("{ 'roots':[{'name':'me', 'name':'you', 'type':'file', " - "'external-contents':'blah' } ] }", - Lower); - EXPECT_EQ(nullptr, FS.get()); - - // missing version - FS = getFromYAMLRawString("{ 'roots':[] }", Lower); - EXPECT_EQ(nullptr, FS.get()); - - // bad version number - FS = getFromYAMLRawString("{ 'version':'foo', 'roots':[] }", Lower); - EXPECT_EQ(nullptr, FS.get()); - FS = getFromYAMLRawString("{ 'version':-1, 'roots':[] }", Lower); - EXPECT_EQ(nullptr, FS.get()); - FS = getFromYAMLRawString("{ 'version':100000, 'roots':[] }", Lower); - EXPECT_EQ(nullptr, FS.get()); - EXPECT_EQ(24, NumDiagnostics); -} - -TEST_F(VFSFromYAMLTest, UseExternalName) { - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - Lower->addRegularFile("//root/external/file"); - - IntrusiveRefCntPtr FS = getFromYAMLString( - "{ 'roots': [\n" - " { 'type': 'file', 'name': '//root/A',\n" - " 'external-contents': '//root/external/file'\n" - " },\n" - " { 'type': 'file', 'name': '//root/B',\n" - " 'use-external-name': true,\n" - " 'external-contents': '//root/external/file'\n" - " },\n" - " { 'type': 'file', 'name': '//root/C',\n" - " 'use-external-name': false,\n" - " 'external-contents': '//root/external/file'\n" - " }\n" - "] }", Lower); - ASSERT_TRUE(nullptr != FS.get()); - - // default true - EXPECT_EQ("//root/external/file", FS->status("//root/A")->getName()); - // explicit - EXPECT_EQ("//root/external/file", FS->status("//root/B")->getName()); - EXPECT_EQ("//root/C", FS->status("//root/C")->getName()); - - // global configuration - FS = getFromYAMLString( - "{ 'use-external-names': false,\n" - " 'roots': [\n" - " { 'type': 'file', 'name': '//root/A',\n" - " 'external-contents': '//root/external/file'\n" - " },\n" - " { 'type': 'file', 'name': '//root/B',\n" - " 'use-external-name': true,\n" - " 'external-contents': '//root/external/file'\n" - " },\n" - " { 'type': 'file', 'name': '//root/C',\n" - " 'use-external-name': false,\n" - " 'external-contents': '//root/external/file'\n" - " }\n" - "] }", Lower); - ASSERT_TRUE(nullptr != FS.get()); - - // default - EXPECT_EQ("//root/A", FS->status("//root/A")->getName()); - // explicit - EXPECT_EQ("//root/external/file", FS->status("//root/B")->getName()); - EXPECT_EQ("//root/C", FS->status("//root/C")->getName()); -} - -TEST_F(VFSFromYAMLTest, MultiComponentPath) { - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - Lower->addRegularFile("//root/other"); - - // file in roots - IntrusiveRefCntPtr FS = getFromYAMLString( - "{ 'roots': [\n" - " { 'type': 'file', 'name': '//root/path/to/file',\n" - " 'external-contents': '//root/other' }]\n" - "}", Lower); - ASSERT_TRUE(nullptr != FS.get()); - EXPECT_FALSE(FS->status("//root/path/to/file").getError()); - EXPECT_FALSE(FS->status("//root/path/to").getError()); - EXPECT_FALSE(FS->status("//root/path").getError()); - EXPECT_FALSE(FS->status("//root/").getError()); - - // at the start - FS = getFromYAMLString( - "{ 'roots': [\n" - " { 'type': 'directory', 'name': '//root/path/to',\n" - " 'contents': [ { 'type': 'file', 'name': 'file',\n" - " 'external-contents': '//root/other' }]}]\n" - "}", Lower); - ASSERT_TRUE(nullptr != FS.get()); - EXPECT_FALSE(FS->status("//root/path/to/file").getError()); - EXPECT_FALSE(FS->status("//root/path/to").getError()); - EXPECT_FALSE(FS->status("//root/path").getError()); - EXPECT_FALSE(FS->status("//root/").getError()); - - // at the end - FS = getFromYAMLString( - "{ 'roots': [\n" - " { 'type': 'directory', 'name': '//root/',\n" - " 'contents': [ { 'type': 'file', 'name': 'path/to/file',\n" - " 'external-contents': '//root/other' }]}]\n" - "}", Lower); - ASSERT_TRUE(nullptr != FS.get()); - EXPECT_FALSE(FS->status("//root/path/to/file").getError()); - EXPECT_FALSE(FS->status("//root/path/to").getError()); - EXPECT_FALSE(FS->status("//root/path").getError()); - EXPECT_FALSE(FS->status("//root/").getError()); -} - -TEST_F(VFSFromYAMLTest, TrailingSlashes) { - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - Lower->addRegularFile("//root/other"); - - // file in roots - IntrusiveRefCntPtr FS = getFromYAMLString( - "{ 'roots': [\n" - " { 'type': 'directory', 'name': '//root/path/to////',\n" - " 'contents': [ { 'type': 'file', 'name': 'file',\n" - " 'external-contents': '//root/other' }]}]\n" - "}", Lower); - ASSERT_TRUE(nullptr != FS.get()); - EXPECT_FALSE(FS->status("//root/path/to/file").getError()); - EXPECT_FALSE(FS->status("//root/path/to").getError()); - EXPECT_FALSE(FS->status("//root/path").getError()); - EXPECT_FALSE(FS->status("//root/").getError()); -} - -TEST_F(VFSFromYAMLTest, DirectoryIteration) { - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - Lower->addDirectory("//root/"); - Lower->addDirectory("//root/foo"); - Lower->addDirectory("//root/foo/bar"); - Lower->addRegularFile("//root/foo/bar/a"); - Lower->addRegularFile("//root/foo/bar/b"); - Lower->addRegularFile("//root/file3"); - IntrusiveRefCntPtr FS = - getFromYAMLString("{ 'use-external-names': false,\n" - " 'roots': [\n" - "{\n" - " 'type': 'directory',\n" - " 'name': '//root/',\n" - " 'contents': [ {\n" - " 'type': 'file',\n" - " 'name': 'file1',\n" - " 'external-contents': '//root/foo/bar/a'\n" - " },\n" - " {\n" - " 'type': 'file',\n" - " 'name': 'file2',\n" - " 'external-contents': '//root/foo/bar/b'\n" - " }\n" - " ]\n" - "}\n" - "]\n" - "}", - Lower); - ASSERT_TRUE(FS.get() != nullptr); - - IntrusiveRefCntPtr O( - new vfs::OverlayFileSystem(Lower)); - O->pushOverlay(FS); - - std::error_code EC; - checkContents(O->dir_begin("//root/", EC), - {"//root/file1", "//root/file2", "//root/file3", "//root/foo"}); - - checkContents(O->dir_begin("//root/foo/bar", EC), - {"//root/foo/bar/a", "//root/foo/bar/b"}); -} - -TEST_F(VFSFromYAMLTest, DirectoryIterationSameDirMultipleEntries) { - // https://llvm.org/bugs/show_bug.cgi?id=27725 - if (!supportsSameDirMultipleYAMLEntries()) - return; - - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - Lower->addDirectory("//root/zab"); - Lower->addDirectory("//root/baz"); - Lower->addRegularFile("//root/zab/a"); - Lower->addRegularFile("//root/zab/b"); - IntrusiveRefCntPtr FS = getFromYAMLString( - "{ 'use-external-names': false,\n" - " 'roots': [\n" - "{\n" - " 'type': 'directory',\n" - " 'name': '//root/baz/',\n" - " 'contents': [ {\n" - " 'type': 'file',\n" - " 'name': 'x',\n" - " 'external-contents': '//root/zab/a'\n" - " }\n" - " ]\n" - "},\n" - "{\n" - " 'type': 'directory',\n" - " 'name': '//root/baz/',\n" - " 'contents': [ {\n" - " 'type': 'file',\n" - " 'name': 'y',\n" - " 'external-contents': '//root/zab/b'\n" - " }\n" - " ]\n" - "}\n" - "]\n" - "}", - Lower); - ASSERT_TRUE(FS.get() != nullptr); - - IntrusiveRefCntPtr O( - new vfs::OverlayFileSystem(Lower)); - O->pushOverlay(FS); - - std::error_code EC; - - checkContents(O->dir_begin("//root/baz/", EC), - {"//root/baz/x", "//root/baz/y"}); -} - -TEST_F(VFSFromYAMLTest, RecursiveDirectoryIterationLevel) { - - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - Lower->addDirectory("//root/a"); - Lower->addDirectory("//root/a/b"); - Lower->addDirectory("//root/a/b/c"); - Lower->addRegularFile("//root/a/b/c/file"); - IntrusiveRefCntPtr FS = getFromYAMLString( - "{ 'use-external-names': false,\n" - " 'roots': [\n" - "{\n" - " 'type': 'directory',\n" - " 'name': '//root/a/b/c/',\n" - " 'contents': [ {\n" - " 'type': 'file',\n" - " 'name': 'file',\n" - " 'external-contents': '//root/a/b/c/file'\n" - " }\n" - " ]\n" - "},\n" - "]\n" - "}", - Lower); - ASSERT_TRUE(FS.get() != nullptr); - - IntrusiveRefCntPtr O( - new vfs::OverlayFileSystem(Lower)); - O->pushOverlay(FS); - - std::error_code EC; - - // Test recursive_directory_iterator level() - vfs::recursive_directory_iterator I = vfs::recursive_directory_iterator( - *O, "//root", EC), E; - ASSERT_FALSE(EC); - for (int l = 0; I != E; I.increment(EC), ++l) { - ASSERT_FALSE(EC); - EXPECT_EQ(I.level(), l); - } - EXPECT_EQ(I, E); -} - -TEST_F(VFSFromYAMLTest, RelativePaths) { - IntrusiveRefCntPtr Lower(new DummyFileSystem()); - // Filename at root level without a parent directory. - IntrusiveRefCntPtr FS = getFromYAMLString( - "{ 'roots': [\n" - " { 'type': 'file', 'name': 'file-not-in-directory.h',\n" - " 'external-contents': '//root/external/file'\n" - " }\n" - "] }", Lower); - EXPECT_EQ(nullptr, FS.get()); - - // Relative file path. - FS = getFromYAMLString( - "{ 'roots': [\n" - " { 'type': 'file', 'name': 'relative/file/path.h',\n" - " 'external-contents': '//root/external/file'\n" - " }\n" - "] }", Lower); - EXPECT_EQ(nullptr, FS.get()); - - // Relative directory path. - FS = getFromYAMLString( - "{ 'roots': [\n" - " { 'type': 'directory', 'name': 'relative/directory/path.h',\n" - " 'contents': []\n" - " }\n" - "] }", Lower); - EXPECT_EQ(nullptr, FS.get()); - - EXPECT_EQ(3, NumDiagnostics); -} Index: cfe/trunk/unittests/Driver/DistroTest.cpp =================================================================== --- cfe/trunk/unittests/Driver/DistroTest.cpp +++ cfe/trunk/unittests/Driver/DistroTest.cpp @@ -12,7 +12,7 @@ //===----------------------------------------------------------------------===// #include "clang/Driver/Distro.h" -#include "clang/Basic/VirtualFileSystem.h" +#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" using namespace clang; @@ -25,7 +25,7 @@ // accidentally result in incorrect distribution guess. TEST(DistroTest, DetectUbuntu) { - vfs::InMemoryFileSystem UbuntuTrustyFileSystem; + llvm::vfs::InMemoryFileSystem UbuntuTrustyFileSystem; // Ubuntu uses Debian Sid version. UbuntuTrustyFileSystem.addFile("/etc/debian_version", 0, llvm::MemoryBuffer::getMemBuffer("jessie/sid\n")); @@ -52,7 +52,7 @@ ASSERT_FALSE(UbuntuTrusty.IsOpenSUSE()); ASSERT_FALSE(UbuntuTrusty.IsDebian()); - vfs::InMemoryFileSystem UbuntuYakketyFileSystem; + llvm::vfs::InMemoryFileSystem UbuntuYakketyFileSystem; UbuntuYakketyFileSystem.addFile("/etc/debian_version", 0, llvm::MemoryBuffer::getMemBuffer("stretch/sid\n")); UbuntuYakketyFileSystem.addFile("/etc/lsb-release", 0, @@ -83,7 +83,7 @@ } TEST(DistroTest, DetectRedhat) { - vfs::InMemoryFileSystem Fedora25FileSystem; + llvm::vfs::InMemoryFileSystem Fedora25FileSystem; Fedora25FileSystem.addFile("/etc/system-release-cpe", 0, llvm::MemoryBuffer::getMemBuffer("cpe:/o:fedoraproject:fedora:25\n")); // Both files are symlinks to fedora-release. @@ -115,7 +115,7 @@ ASSERT_FALSE(Fedora25.IsOpenSUSE()); ASSERT_FALSE(Fedora25.IsDebian()); - vfs::InMemoryFileSystem CentOS7FileSystem; + llvm::vfs::InMemoryFileSystem CentOS7FileSystem; CentOS7FileSystem.addFile("/etc/system-release-cpe", 0, llvm::MemoryBuffer::getMemBuffer("cpe:/o:centos:centos:7\n")); // Both files are symlinks to centos-release. @@ -153,7 +153,7 @@ } TEST(DistroTest, DetectOpenSUSE) { - vfs::InMemoryFileSystem OpenSUSELeap421FileSystem; + llvm::vfs::InMemoryFileSystem OpenSUSELeap421FileSystem; OpenSUSELeap421FileSystem.addFile("/etc/SuSE-release", 0, llvm::MemoryBuffer::getMemBuffer("openSUSE 42.1 (x86_64)\n" "VERSION = 42.1\n" @@ -178,7 +178,7 @@ ASSERT_TRUE(OpenSUSELeap421.IsOpenSUSE()); ASSERT_FALSE(OpenSUSELeap421.IsDebian()); - vfs::InMemoryFileSystem OpenSUSE132FileSystem; + llvm::vfs::InMemoryFileSystem OpenSUSE132FileSystem; OpenSUSE132FileSystem.addFile("/etc/SuSE-release", 0, llvm::MemoryBuffer::getMemBuffer("openSUSE 13.2 (x86_64)\n" "VERSION = 13.2\n" @@ -203,7 +203,7 @@ ASSERT_TRUE(OpenSUSE132.IsOpenSUSE()); ASSERT_FALSE(OpenSUSE132.IsDebian()); - vfs::InMemoryFileSystem SLES10FileSystem; + llvm::vfs::InMemoryFileSystem SLES10FileSystem; SLES10FileSystem.addFile("/etc/SuSE-release", 0, llvm::MemoryBuffer::getMemBuffer("SUSE Linux Enterprise Server 10 (x86_64)\n" "VERSION = 10\n" @@ -221,7 +221,7 @@ } TEST(DistroTest, DetectDebian) { - vfs::InMemoryFileSystem DebianJessieFileSystem; + llvm::vfs::InMemoryFileSystem DebianJessieFileSystem; DebianJessieFileSystem.addFile("/etc/debian_version", 0, llvm::MemoryBuffer::getMemBuffer("8.6\n")); DebianJessieFileSystem.addFile("/etc/os-release", 0, @@ -241,7 +241,7 @@ ASSERT_FALSE(DebianJessie.IsOpenSUSE()); ASSERT_TRUE(DebianJessie.IsDebian()); - vfs::InMemoryFileSystem DebianStretchSidFileSystem; + llvm::vfs::InMemoryFileSystem DebianStretchSidFileSystem; DebianStretchSidFileSystem.addFile("/etc/debian_version", 0, llvm::MemoryBuffer::getMemBuffer("stretch/sid\n")); DebianStretchSidFileSystem.addFile("/etc/os-release", 0, @@ -261,7 +261,7 @@ } TEST(DistroTest, DetectExherbo) { - vfs::InMemoryFileSystem ExherboFileSystem; + llvm::vfs::InMemoryFileSystem ExherboFileSystem; ExherboFileSystem.addFile("/etc/exherbo-release", 0, // (ASCII art) llvm::MemoryBuffer::getMemBuffer("")); ExherboFileSystem.addFile("/etc/os-release", 0, @@ -282,7 +282,7 @@ } TEST(DistroTest, DetectArchLinux) { - vfs::InMemoryFileSystem ArchLinuxFileSystem; + llvm::vfs::InMemoryFileSystem ArchLinuxFileSystem; ArchLinuxFileSystem.addFile("/etc/arch-release", 0, // (empty) llvm::MemoryBuffer::getMemBuffer("")); ArchLinuxFileSystem.addFile("/etc/os-release", 0, Index: cfe/trunk/unittests/Driver/ToolChainTest.cpp =================================================================== --- cfe/trunk/unittests/Driver/ToolChainTest.cpp +++ cfe/trunk/unittests/Driver/ToolChainTest.cpp @@ -15,11 +15,11 @@ #include "clang/Basic/DiagnosticIDs.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Basic/LLVM.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" +#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" using namespace clang; @@ -33,8 +33,8 @@ IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); struct TestDiagnosticConsumer : public DiagnosticConsumer {}; DiagnosticsEngine Diags(DiagID, &*DiagOpts, new TestDiagnosticConsumer); - IntrusiveRefCntPtr InMemoryFileSystem( - new vfs::InMemoryFileSystem); + IntrusiveRefCntPtr InMemoryFileSystem( + new llvm::vfs::InMemoryFileSystem); Driver TheDriver("/bin/clang", "arm-linux-gnueabihf", Diags, InMemoryFileSystem); @@ -87,8 +87,8 @@ IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); struct TestDiagnosticConsumer : public DiagnosticConsumer {}; DiagnosticsEngine Diags(DiagID, &*DiagOpts, new TestDiagnosticConsumer); - IntrusiveRefCntPtr InMemoryFileSystem( - new vfs::InMemoryFileSystem); + IntrusiveRefCntPtr InMemoryFileSystem( + new llvm::vfs::InMemoryFileSystem); Driver TheDriver("/home/test/bin/clang", "arm-linux-gnueabi", Diags, InMemoryFileSystem); @@ -127,8 +127,8 @@ IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); struct TestDiagnosticConsumer : public DiagnosticConsumer {}; DiagnosticsEngine Diags(DiagID, &*DiagOpts, new TestDiagnosticConsumer); - IntrusiveRefCntPtr InMemoryFileSystem( - new vfs::InMemoryFileSystem); + IntrusiveRefCntPtr InMemoryFileSystem( + new llvm::vfs::InMemoryFileSystem); Driver CCDriver("/home/test/bin/clang", "arm-linux-gnueabi", Diags, InMemoryFileSystem); Index: cfe/trunk/unittests/Format/FormatTest.cpp =================================================================== --- cfe/trunk/unittests/Format/FormatTest.cpp +++ cfe/trunk/unittests/Format/FormatTest.cpp @@ -12375,14 +12375,14 @@ } TEST(FormatStyle, GetStyleWithEmptyFileName) { - vfs::InMemoryFileSystem FS; + llvm::vfs::InMemoryFileSystem FS; auto Style1 = getStyle("file", "", "Google", "", &FS); ASSERT_TRUE((bool)Style1); ASSERT_EQ(*Style1, getGoogleStyle()); } TEST(FormatStyle, GetStyleOfFile) { - vfs::InMemoryFileSystem FS; + llvm::vfs::InMemoryFileSystem FS; // Test 1: format file in the same directory. ASSERT_TRUE( FS.addFile("/a/.clang-format", 0, Index: cfe/trunk/unittests/Index/IndexTests.cpp =================================================================== --- cfe/trunk/unittests/Index/IndexTests.cpp +++ cfe/trunk/unittests/Index/IndexTests.cpp @@ -9,7 +9,6 @@ #include "clang/AST/ASTConsumer.h" #include "clang/AST/Decl.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendAction.h" #include "clang/Index/IndexDataConsumer.h" @@ -18,6 +17,7 @@ #include "clang/Lex/Preprocessor.h" #include "clang/Tooling/Tooling.h" #include "llvm/ADT/StringRef.h" +#include "llvm/Support/VirtualFileSystem.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include Index: cfe/trunk/unittests/Lex/HeaderSearchTest.cpp =================================================================== --- cfe/trunk/unittests/Lex/HeaderSearchTest.cpp +++ cfe/trunk/unittests/Lex/HeaderSearchTest.cpp @@ -27,7 +27,7 @@ class HeaderSearchTest : public ::testing::Test { protected: HeaderSearchTest() - : VFS(new vfs::InMemoryFileSystem), FileMgr(FileMgrOpts, VFS), + : VFS(new llvm::vfs::InMemoryFileSystem), FileMgr(FileMgrOpts, VFS), DiagID(new DiagnosticIDs()), Diags(DiagID, new DiagnosticOptions, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions), @@ -46,7 +46,7 @@ Search.AddSearchPath(DL, /*isAngled=*/false); } - IntrusiveRefCntPtr VFS; + IntrusiveRefCntPtr VFS; FileSystemOptions FileMgrOpts; FileManager FileMgr; IntrusiveRefCntPtr DiagID; Index: cfe/trunk/unittests/Lex/PPCallbacksTest.cpp =================================================================== --- cfe/trunk/unittests/Lex/PPCallbacksTest.cpp +++ cfe/trunk/unittests/Lex/PPCallbacksTest.cpp @@ -95,7 +95,7 @@ class PPCallbacksTest : public ::testing::Test { protected: PPCallbacksTest() - : InMemoryFileSystem(new vfs::InMemoryFileSystem), + : InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem), FileMgr(FileSystemOptions(), InMemoryFileSystem), DiagID(new DiagnosticIDs()), DiagOpts(new DiagnosticOptions()), Diags(DiagID, DiagOpts.get(), new IgnoringDiagConsumer()), @@ -104,7 +104,7 @@ Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts); } - IntrusiveRefCntPtr InMemoryFileSystem; + IntrusiveRefCntPtr InMemoryFileSystem; FileManager FileMgr; IntrusiveRefCntPtr DiagID; IntrusiveRefCntPtr DiagOpts; @@ -116,17 +116,17 @@ // Register a header path as a known file and add its location // to search path. - void AddFakeHeader(HeaderSearch& HeaderInfo, const char* HeaderPath, - bool IsSystemHeader) { - // Tell FileMgr about header. - InMemoryFileSystem->addFile(HeaderPath, 0, - llvm::MemoryBuffer::getMemBuffer("\n")); - - // Add header's parent path to search path. - StringRef SearchPath = llvm::sys::path::parent_path(HeaderPath); - const DirectoryEntry *DE = FileMgr.getDirectory(SearchPath); - DirectoryLookup DL(DE, SrcMgr::C_User, false); - HeaderInfo.AddSearchPath(DL, IsSystemHeader); + void AddFakeHeader(HeaderSearch &HeaderInfo, const char *HeaderPath, + bool IsSystemHeader) { + // Tell FileMgr about header. + InMemoryFileSystem->addFile(HeaderPath, 0, + llvm::MemoryBuffer::getMemBuffer("\n")); + + // Add header's parent path to search path. + StringRef SearchPath = llvm::sys::path::parent_path(HeaderPath); + const DirectoryEntry *DE = FileMgr.getDirectory(SearchPath); + DirectoryLookup DL(DE, SrcMgr::C_User, false); + HeaderInfo.AddSearchPath(DL, IsSystemHeader); } // Get the raw source string of the range. @@ -139,8 +139,9 @@ // Run lexer over SourceText and collect FilenameRange from // the InclusionDirective callback. - CharSourceRange InclusionDirectiveFilenameRange(const char* SourceText, - const char* HeaderPath, bool SystemHeader) { + CharSourceRange InclusionDirectiveFilenameRange(const char *SourceText, + const char *HeaderPath, + bool SystemHeader) { std::unique_ptr Buf = llvm::MemoryBuffer::getMemBuffer(SourceText); SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(Buf))); @@ -198,8 +199,8 @@ return Callbacks; } - PragmaOpenCLExtensionCallbacks::CallbackParameters - PragmaOpenCLExtensionCall(const char* SourceText) { + PragmaOpenCLExtensionCallbacks::CallbackParameters + PragmaOpenCLExtensionCall(const char *SourceText) { LangOptions OpenCLLangOpts; OpenCLLangOpts.OpenCL = 1; @@ -221,9 +222,8 @@ // parser actually sets correct pragma handlers for preprocessor // according to LangOptions, so we init Parser to register opencl // pragma handlers - ASTContext Context(OpenCLLangOpts, SourceMgr, - PP.getIdentifierTable(), PP.getSelectorTable(), - PP.getBuiltinInfo()); + ASTContext Context(OpenCLLangOpts, SourceMgr, PP.getIdentifierTable(), + PP.getSelectorTable(), PP.getBuiltinInfo()); Context.InitBuiltinTypes(*Target); ASTConsumer Consumer; @@ -245,7 +245,7 @@ Callbacks->Name, Callbacks->State }; - return RetVal; + return RetVal; } }; Index: cfe/trunk/unittests/Rename/ClangRenameTest.h =================================================================== --- cfe/trunk/unittests/Rename/ClangRenameTest.h +++ cfe/trunk/unittests/Rename/ClangRenameTest.h @@ -14,7 +14,6 @@ #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemOptions.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Format/Format.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/PCHContainerOperations.h" @@ -26,6 +25,7 @@ #include "llvm/ADT/StringRef.h" #include "llvm/Support/Format.h" #include "llvm/Support/MemoryBuffer.h" +#include "llvm/Support/VirtualFileSystem.h" #include "gtest/gtest.h" #include #include Index: cfe/trunk/unittests/Tooling/RefactoringTest.cpp =================================================================== --- cfe/trunk/unittests/Tooling/RefactoringTest.cpp +++ cfe/trunk/unittests/Tooling/RefactoringTest.cpp @@ -7,6 +7,7 @@ // //===----------------------------------------------------------------------===// +#include "clang/Tooling/Refactoring.h" #include "ReplacementTest.h" #include "RewriterTestContext.h" #include "clang/AST/ASTConsumer.h" @@ -19,16 +20,15 @@ #include "clang/Basic/FileManager.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/SourceManager.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Format/Format.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendAction.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Rewrite/Core/Rewriter.h" -#include "clang/Tooling/Refactoring.h" #include "clang/Tooling/Refactoring/AtomicChange.h" #include "clang/Tooling/Tooling.h" #include "llvm/ADT/SmallString.h" +#include "llvm/Support/VirtualFileSystem.h" #include "gtest/gtest.h" namespace clang { @@ -1032,8 +1032,8 @@ TEST(DeduplicateByFileTest, PathsWithDots) { std::map FileToReplaces; - llvm::IntrusiveRefCntPtr VFS( - new vfs::InMemoryFileSystem()); + llvm::IntrusiveRefCntPtr VFS( + new llvm::vfs::InMemoryFileSystem()); FileManager FileMgr(FileSystemOptions(), VFS); #if !defined(_WIN32) StringRef Path1 = "a/b/.././c.h"; @@ -1053,8 +1053,8 @@ TEST(DeduplicateByFileTest, PathWithDotSlash) { std::map FileToReplaces; - llvm::IntrusiveRefCntPtr VFS( - new vfs::InMemoryFileSystem()); + llvm::IntrusiveRefCntPtr VFS( + new llvm::vfs::InMemoryFileSystem()); FileManager FileMgr(FileSystemOptions(), VFS); #if !defined(_WIN32) StringRef Path1 = "./a/b/c.h"; @@ -1074,8 +1074,8 @@ TEST(DeduplicateByFileTest, NonExistingFilePath) { std::map FileToReplaces; - llvm::IntrusiveRefCntPtr VFS( - new vfs::InMemoryFileSystem()); + llvm::IntrusiveRefCntPtr VFS( + new llvm::vfs::InMemoryFileSystem()); FileManager FileMgr(FileSystemOptions(), VFS); #if !defined(_WIN32) StringRef Path1 = "./a/b/c.h"; Index: cfe/trunk/unittests/Tooling/RewriterTestContext.h =================================================================== --- cfe/trunk/unittests/Tooling/RewriterTestContext.h +++ cfe/trunk/unittests/Tooling/RewriterTestContext.h @@ -39,15 +39,15 @@ Diagnostics(IntrusiveRefCntPtr(new DiagnosticIDs), &*DiagOpts), DiagnosticPrinter(llvm::outs(), &*DiagOpts), - InMemoryFileSystem(new vfs::InMemoryFileSystem), + InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem), OverlayFileSystem( - new vfs::OverlayFileSystem(vfs::getRealFileSystem())), + new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())), Files(FileSystemOptions(), OverlayFileSystem), Sources(Diagnostics, Files), Rewrite(Sources, Options) { - Diagnostics.setClient(&DiagnosticPrinter, false); - // FIXME: To make these tests truly in-memory, we need to overlay the - // builtin headers. - OverlayFileSystem->pushOverlay(InMemoryFileSystem); + Diagnostics.setClient(&DiagnosticPrinter, false); + // FIXME: To make these tests truly in-memory, we need to overlay the + // builtin headers. + OverlayFileSystem->pushOverlay(InMemoryFileSystem); } ~RewriterTestContext() {} @@ -114,8 +114,8 @@ IntrusiveRefCntPtr DiagOpts; DiagnosticsEngine Diagnostics; TextDiagnosticPrinter DiagnosticPrinter; - IntrusiveRefCntPtr InMemoryFileSystem; - IntrusiveRefCntPtr OverlayFileSystem; + IntrusiveRefCntPtr InMemoryFileSystem; + IntrusiveRefCntPtr OverlayFileSystem; FileManager Files; SourceManager Sources; LangOptions Options; Index: cfe/trunk/unittests/Tooling/ToolingTest.cpp =================================================================== --- cfe/trunk/unittests/Tooling/ToolingTest.cpp +++ cfe/trunk/unittests/Tooling/ToolingTest.cpp @@ -149,10 +149,10 @@ } TEST(ToolInvocation, TestMapVirtualFile) { - llvm::IntrusiveRefCntPtr OverlayFileSystem( - new vfs::OverlayFileSystem(vfs::getRealFileSystem())); - llvm::IntrusiveRefCntPtr InMemoryFileSystem( - new vfs::InMemoryFileSystem); + llvm::IntrusiveRefCntPtr OverlayFileSystem( + new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())); + llvm::IntrusiveRefCntPtr InMemoryFileSystem( + new llvm::vfs::InMemoryFileSystem); OverlayFileSystem->pushOverlay(InMemoryFileSystem); llvm::IntrusiveRefCntPtr Files( new FileManager(FileSystemOptions(), OverlayFileSystem)); @@ -175,10 +175,10 @@ // mapped module.map is found on the include path. In the future, expand this // test to run a full modules enabled compilation, so we make sure we can // rerun modules compilations with a virtual file system. - llvm::IntrusiveRefCntPtr OverlayFileSystem( - new vfs::OverlayFileSystem(vfs::getRealFileSystem())); - llvm::IntrusiveRefCntPtr InMemoryFileSystem( - new vfs::InMemoryFileSystem); + llvm::IntrusiveRefCntPtr OverlayFileSystem( + new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())); + llvm::IntrusiveRefCntPtr InMemoryFileSystem( + new llvm::vfs::InMemoryFileSystem); OverlayFileSystem->pushOverlay(InMemoryFileSystem); llvm::IntrusiveRefCntPtr Files( new FileManager(FileSystemOptions(), OverlayFileSystem)); @@ -403,10 +403,10 @@ TEST(ClangToolTest, BaseVirtualFileSystemUsage) { FixedCompilationDatabase Compilations("/", std::vector()); - llvm::IntrusiveRefCntPtr OverlayFileSystem( - new vfs::OverlayFileSystem(vfs::getRealFileSystem())); - llvm::IntrusiveRefCntPtr InMemoryFileSystem( - new vfs::InMemoryFileSystem); + llvm::IntrusiveRefCntPtr OverlayFileSystem( + new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())); + llvm::IntrusiveRefCntPtr InMemoryFileSystem( + new llvm::vfs::InMemoryFileSystem); OverlayFileSystem->pushOverlay(InMemoryFileSystem); InMemoryFileSystem->addFile( Index: clang-tools-extra/trunk/clang-tidy/ClangTidy.h =================================================================== --- clang-tools-extra/trunk/clang-tidy/ClangTidy.h +++ clang-tools-extra/trunk/clang-tidy/ClangTidy.h @@ -233,7 +233,7 @@ void runClangTidy(clang::tidy::ClangTidyContext &Context, const tooling::CompilationDatabase &Compilations, ArrayRef InputFiles, - llvm::IntrusiveRefCntPtr BaseFS, + llvm::IntrusiveRefCntPtr BaseFS, bool EnableCheckProfile = false, llvm::StringRef StoreCheckProfile = StringRef()); @@ -245,7 +245,7 @@ /// clang-format configuration file is found, the given \P FormatStyle is used. void handleErrors(ClangTidyContext &Context, bool Fix, unsigned &WarningsAsErrorsCount, - llvm::IntrusiveRefCntPtr BaseFS); + llvm::IntrusiveRefCntPtr BaseFS); /// \brief Serializes replacements into YAML and writes them to the specified /// output stream. Index: clang-tools-extra/trunk/clang-tidy/ClangTidy.cpp =================================================================== --- clang-tools-extra/trunk/clang-tidy/ClangTidy.cpp +++ clang-tools-extra/trunk/clang-tidy/ClangTidy.cpp @@ -96,7 +96,7 @@ class ErrorReporter { public: ErrorReporter(ClangTidyContext &Context, bool ApplyFixes, - llvm::IntrusiveRefCntPtr BaseFS) + llvm::IntrusiveRefCntPtr BaseFS) : Files(FileSystemOptions(), BaseFS), DiagOpts(new DiagnosticOptions()), DiagPrinter(new TextDiagnosticPrinter(llvm::outs(), &*DiagOpts)), Diags(IntrusiveRefCntPtr(new DiagnosticIDs), &*DiagOpts, @@ -503,7 +503,7 @@ void runClangTidy(clang::tidy::ClangTidyContext &Context, const CompilationDatabase &Compilations, ArrayRef InputFiles, - llvm::IntrusiveRefCntPtr BaseFS, + llvm::IntrusiveRefCntPtr BaseFS, bool EnableCheckProfile, llvm::StringRef StoreCheckProfile) { ClangTool Tool(Compilations, InputFiles, std::make_shared(), BaseFS); @@ -590,9 +590,9 @@ void handleErrors(ClangTidyContext &Context, bool Fix, unsigned &WarningsAsErrorsCount, - llvm::IntrusiveRefCntPtr BaseFS) { + llvm::IntrusiveRefCntPtr BaseFS) { ErrorReporter Reporter(Context, Fix, BaseFS); - vfs::FileSystem &FileSystem = + llvm::vfs::FileSystem &FileSystem = *Reporter.getSourceManager().getFileManager().getVirtualFileSystem(); auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory(); if (!InitialWorkingDir) Index: clang-tools-extra/trunk/clang-tidy/ClangTidyOptions.h =================================================================== --- clang-tools-extra/trunk/clang-tidy/ClangTidyOptions.h +++ clang-tools-extra/trunk/clang-tidy/ClangTidyOptions.h @@ -10,12 +10,12 @@ #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYOPTIONS_H #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYOPTIONS_H +#include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" -#include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/Support/ErrorOr.h" -#include "clang/Basic/VirtualFileSystem.h" +#include "llvm/Support/VirtualFileSystem.h" #include #include #include @@ -218,10 +218,11 @@ /// /// If any of the \param OverrideOptions fields are set, they will override /// whatever options are read from the configuration file. - FileOptionsProvider(const ClangTidyGlobalOptions &GlobalOptions, - const ClangTidyOptions &DefaultOptions, - const ClangTidyOptions &OverrideOptions, - llvm::IntrusiveRefCntPtr FS = nullptr); + FileOptionsProvider( + const ClangTidyGlobalOptions &GlobalOptions, + const ClangTidyOptions &DefaultOptions, + const ClangTidyOptions &OverrideOptions, + llvm::IntrusiveRefCntPtr FS = nullptr); /// \brief Initializes the \c FileOptionsProvider instance with a custom set /// of configuration file handlers. @@ -255,7 +256,7 @@ llvm::StringMap CachedOptions; ClangTidyOptions OverrideOptions; ConfigFileHandlers ConfigHandlers; - llvm::IntrusiveRefCntPtr FS; + llvm::IntrusiveRefCntPtr FS; }; /// \brief Parses LineFilter from JSON and stores it to the \p Options. Index: clang-tools-extra/trunk/clang-tidy/ClangTidyOptions.cpp =================================================================== --- clang-tools-extra/trunk/clang-tidy/ClangTidyOptions.cpp +++ clang-tools-extra/trunk/clang-tidy/ClangTidyOptions.cpp @@ -204,11 +204,11 @@ const ClangTidyGlobalOptions &GlobalOptions, const ClangTidyOptions &DefaultOptions, const ClangTidyOptions &OverrideOptions, - llvm::IntrusiveRefCntPtr VFS) + llvm::IntrusiveRefCntPtr VFS) : DefaultOptionsProvider(GlobalOptions, DefaultOptions), OverrideOptions(OverrideOptions), FS(std::move(VFS)) { if (!FS) - FS = vfs::getRealFileSystem(); + FS = llvm::vfs::getRealFileSystem(); ConfigHandlers.emplace_back(".clang-tidy", parseConfiguration); } Index: clang-tools-extra/trunk/clangd/ClangdUnit.h =================================================================== --- clang-tools-extra/trunk/clangd/ClangdUnit.h +++ clang-tools-extra/trunk/clangd/ClangdUnit.h @@ -28,14 +28,14 @@ namespace llvm { class raw_ostream; -} - -namespace clang { -class PCHContainerOperations; namespace vfs { class FileSystem; } +} // namespace llvm + +namespace clang { +class PCHContainerOperations; namespace tooling { struct CompileCommand; @@ -63,7 +63,7 @@ /// Information required to run clang, e.g. to parse AST or do code completion. struct ParseInputs { tooling::CompileCommand CompileCommand; - IntrusiveRefCntPtr FS; + IntrusiveRefCntPtr FS; std::string Contents; }; @@ -77,7 +77,7 @@ std::shared_ptr Preamble, std::unique_ptr Buffer, std::shared_ptr PCHs, - IntrusiveRefCntPtr VFS); + IntrusiveRefCntPtr VFS); ParsedAST(ParsedAST &&Other); ParsedAST &operator=(ParsedAST &&Other); Index: clang-tools-extra/trunk/clangd/ClangdUnit.cpp =================================================================== --- clang-tools-extra/trunk/clangd/ClangdUnit.cpp +++ clang-tools-extra/trunk/clangd/ClangdUnit.cpp @@ -126,7 +126,7 @@ std::shared_ptr Preamble, std::unique_ptr Buffer, std::shared_ptr PCHs, - IntrusiveRefCntPtr VFS) { + IntrusiveRefCntPtr VFS) { assert(CI); // Command-line parsing sets DisableFree to true by default, but we don't want // to leak memory in clangd. Index: clang-tools-extra/trunk/clangd/CodeComplete.h =================================================================== --- clang-tools-extra/trunk/clangd/CodeComplete.h +++ clang-tools-extra/trunk/clangd/CodeComplete.h @@ -224,7 +224,7 @@ const tooling::CompileCommand &Command, const PreambleData *Preamble, StringRef Contents, Position Pos, - IntrusiveRefCntPtr VFS, + IntrusiveRefCntPtr VFS, std::shared_ptr PCHs, CodeCompleteOptions Opts, SpeculativeFuzzyFind *SpecFuzzyFind = nullptr); @@ -234,7 +234,7 @@ const tooling::CompileCommand &Command, const PreambleData *Preamble, StringRef Contents, Position Pos, - IntrusiveRefCntPtr VFS, + IntrusiveRefCntPtr VFS, std::shared_ptr PCHs, const SymbolIndex *Index); Index: clang-tools-extra/trunk/clangd/CodeComplete.cpp =================================================================== --- clang-tools-extra/trunk/clangd/CodeComplete.cpp +++ clang-tools-extra/trunk/clangd/CodeComplete.cpp @@ -986,7 +986,7 @@ const PreambleData *Preamble; StringRef Contents; Position Pos; - IntrusiveRefCntPtr VFS; + IntrusiveRefCntPtr VFS; std::shared_ptr PCHs; }; @@ -1007,7 +1007,7 @@ // working dirs. } - IntrusiveRefCntPtr VFS = Input.VFS; + IntrusiveRefCntPtr VFS = Input.VFS; if (Input.Preamble && Input.Preamble->StatCache) VFS = Input.Preamble->StatCache->getConsumingFS(std::move(VFS)); IgnoreDiagnostics DummyDiagsConsumer; @@ -1567,7 +1567,7 @@ CodeCompleteResult codeComplete(PathRef FileName, const tooling::CompileCommand &Command, const PreambleData *Preamble, StringRef Contents, Position Pos, - IntrusiveRefCntPtr VFS, + IntrusiveRefCntPtr VFS, std::shared_ptr PCHs, CodeCompleteOptions Opts, SpeculativeFuzzyFind *SpecFuzzyFind) { return CodeCompleteFlow(FileName, @@ -1580,7 +1580,7 @@ const tooling::CompileCommand &Command, const PreambleData *Preamble, StringRef Contents, Position Pos, - IntrusiveRefCntPtr VFS, + IntrusiveRefCntPtr VFS, std::shared_ptr PCHs, const SymbolIndex *Index) { SignatureHelp Result; Index: clang-tools-extra/trunk/clangd/Compiler.h =================================================================== --- clang-tools-extra/trunk/clangd/Compiler.h +++ clang-tools-extra/trunk/clangd/Compiler.h @@ -37,8 +37,8 @@ /// - Preamble is overriden to use PCH passed to this function. It means the /// changes to the preamble headers or files included in the preamble are /// not visible to this compiler instance. -/// - vfs::FileSystem is used for all underlying file accesses. The actual -/// vfs used by the compiler may be an overlay over the passed vfs. +/// - llvm::vfs::FileSystem is used for all underlying file accesses. The +/// actual vfs used by the compiler may be an overlay over the passed vfs. /// Returns null on errors. When non-null value is returned, it is expected to /// be consumed by FrontendAction::BeginSourceFile to properly destroy \p /// MainFile. @@ -46,7 +46,7 @@ std::unique_ptr, const PrecompiledPreamble *, std::unique_ptr MainFile, std::shared_ptr, - IntrusiveRefCntPtr, DiagnosticConsumer &); + IntrusiveRefCntPtr, DiagnosticConsumer &); } // namespace clangd } // namespace clang Index: clang-tools-extra/trunk/clangd/Compiler.cpp =================================================================== --- clang-tools-extra/trunk/clangd/Compiler.cpp +++ clang-tools-extra/trunk/clangd/Compiler.cpp @@ -44,7 +44,7 @@ const PrecompiledPreamble *Preamble, std::unique_ptr Buffer, std::shared_ptr PCHs, - IntrusiveRefCntPtr VFS, + IntrusiveRefCntPtr VFS, DiagnosticConsumer &DiagsClient) { assert(VFS && "VFS is null"); assert(!CI->getPreprocessorOpts().RetainRemappedFileBuffers && Index: clang-tools-extra/trunk/clangd/FS.h =================================================================== --- clang-tools-extra/trunk/clangd/FS.h +++ clang-tools-extra/trunk/clangd/FS.h @@ -10,8 +10,9 @@ #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_FS_H #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_FS_H -#include "clang/Basic/VirtualFileSystem.h" +#include "clang/Basic/LLVM.h" #include "llvm/ADT/Optional.h" +#include "llvm/Support/VirtualFileSystem.h" namespace clang { namespace clangd { @@ -39,10 +40,10 @@ /// corresponds to. The stat for the main file will not be cached. PreambleFileStatusCache(llvm::StringRef MainFilePath); - void update(const vfs::FileSystem &FS, vfs::Status S); + void update(const llvm::vfs::FileSystem &FS, llvm::vfs::Status S); /// \p Path is a path stored in preamble. - llvm::Optional lookup(llvm::StringRef Path) const; + llvm::Optional lookup(llvm::StringRef Path) const; /// Returns a VFS that collects file status. /// Only cache stats for files that exist because @@ -51,18 +52,18 @@ /// 2) we use the file name in the Status as the cache key. /// /// Note that the returned VFS should not outlive the cache. - IntrusiveRefCntPtr - getProducingFS(IntrusiveRefCntPtr FS); + IntrusiveRefCntPtr + getProducingFS(IntrusiveRefCntPtr FS); /// Returns a VFS that uses the cache collected. /// /// Note that the returned VFS should not outlive the cache. - IntrusiveRefCntPtr - getConsumingFS(IntrusiveRefCntPtr FS) const; + IntrusiveRefCntPtr + getConsumingFS(IntrusiveRefCntPtr FS) const; private: std::string MainFilePath; - llvm::StringMap StatCache; + llvm::StringMap StatCache; }; } // namespace clangd Index: clang-tools-extra/trunk/clangd/FS.cpp =================================================================== --- clang-tools-extra/trunk/clangd/FS.cpp +++ clang-tools-extra/trunk/clangd/FS.cpp @@ -8,7 +8,7 @@ //===----------------------------------------------------------------------===// #include "FS.h" -#include "clang/Basic/VirtualFileSystem.h" +#include "clang/Basic/LLVM.h" #include "llvm/ADT/None.h" #include "llvm/Support/Path.h" @@ -20,7 +20,8 @@ assert(llvm::sys::path::is_absolute(MainFilePath)); } -void PreambleFileStatusCache::update(const vfs::FileSystem &FS, vfs::Status S) { +void PreambleFileStatusCache::update(const llvm::vfs::FileSystem &FS, + llvm::vfs::Status S) { SmallString<32> PathStore(S.getName()); if (FS.makeAbsolute(PathStore)) return; @@ -31,7 +32,7 @@ StatCache.insert({PathStore, std::move(S)}); } -llvm::Optional +llvm::Optional PreambleFileStatusCache::lookup(llvm::StringRef File) const { auto I = StatCache.find(File); if (I != StatCache.end()) @@ -39,17 +40,18 @@ return llvm::None; } -IntrusiveRefCntPtr PreambleFileStatusCache::getProducingFS( - IntrusiveRefCntPtr FS) { +IntrusiveRefCntPtr +PreambleFileStatusCache::getProducingFS( + IntrusiveRefCntPtr FS) { // This invalidates old status in cache if files are re-`open()`ed or // re-`stat()`ed in case file status has changed during preamble build. - class CollectFS : public vfs::ProxyFileSystem { + class CollectFS : public llvm::vfs::ProxyFileSystem { public: - CollectFS(IntrusiveRefCntPtr FS, + CollectFS(IntrusiveRefCntPtr FS, PreambleFileStatusCache &StatCache) : ProxyFileSystem(std::move(FS)), StatCache(StatCache) {} - llvm::ErrorOr> + llvm::ErrorOr> openFileForRead(const Twine &Path) override { auto File = getUnderlyingFS().openFileForRead(Path); if (!File || !*File) @@ -64,7 +66,7 @@ return File; } - llvm::ErrorOr status(const Twine &Path) override { + llvm::ErrorOr status(const Twine &Path) override { auto S = getUnderlyingFS().status(Path); if (S) StatCache.update(getUnderlyingFS(), *S); @@ -77,15 +79,16 @@ return IntrusiveRefCntPtr(new CollectFS(std::move(FS), *this)); } -IntrusiveRefCntPtr PreambleFileStatusCache::getConsumingFS( - IntrusiveRefCntPtr FS) const { - class CacheVFS : public vfs::ProxyFileSystem { +IntrusiveRefCntPtr +PreambleFileStatusCache::getConsumingFS( + IntrusiveRefCntPtr FS) const { + class CacheVFS : public llvm::vfs::ProxyFileSystem { public: - CacheVFS(IntrusiveRefCntPtr FS, + CacheVFS(IntrusiveRefCntPtr FS, const PreambleFileStatusCache &StatCache) : ProxyFileSystem(std::move(FS)), StatCache(StatCache) {} - llvm::ErrorOr status(const Twine &Path) override { + llvm::ErrorOr status(const Twine &Path) override { if (auto S = StatCache.lookup(Path.str())) return *S; return getUnderlyingFS().status(Path); Index: clang-tools-extra/trunk/clangd/FSProvider.h =================================================================== --- clang-tools-extra/trunk/clangd/FSProvider.h +++ clang-tools-extra/trunk/clangd/FSProvider.h @@ -10,8 +10,8 @@ #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_FSPROVIDER_H #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_FSPROVIDER_H -#include "clang/Basic/VirtualFileSystem.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" +#include "llvm/Support/VirtualFileSystem.h" namespace clang { namespace clangd { @@ -25,14 +25,14 @@ /// Context::current() will be the context passed to the clang entrypoint, /// such as addDocument(), and will also be propagated to result callbacks. /// Embedders may use this to isolate filesystem accesses. - virtual IntrusiveRefCntPtr getFileSystem() const = 0; + virtual IntrusiveRefCntPtr getFileSystem() const = 0; }; class RealFileSystemProvider : public FileSystemProvider { public: // FIXME: returns the single real FS instance, which is not threadsafe. - IntrusiveRefCntPtr getFileSystem() const override { - return vfs::getRealFileSystem(); + IntrusiveRefCntPtr getFileSystem() const override { + return llvm::vfs::getRealFileSystem(); } }; Index: clang-tools-extra/trunk/clangd/Headers.h =================================================================== --- clang-tools-extra/trunk/clangd/Headers.h +++ clang-tools-extra/trunk/clangd/Headers.h @@ -13,7 +13,6 @@ #include "Path.h" #include "Protocol.h" #include "SourceCode.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Format/Format.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/PPCallbacks.h" @@ -21,6 +20,7 @@ #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSet.h" #include "llvm/Support/Error.h" +#include "llvm/Support/VirtualFileSystem.h" namespace clang { namespace clangd { Index: clang-tools-extra/trunk/unittests/change-namespace/ChangeNamespaceTests.cpp =================================================================== --- clang-tools-extra/trunk/unittests/change-namespace/ChangeNamespaceTests.cpp +++ clang-tools-extra/trunk/unittests/change-namespace/ChangeNamespaceTests.cpp @@ -12,7 +12,6 @@ #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemOptions.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Format/Format.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/PCHContainerOperations.h" @@ -21,6 +20,7 @@ #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/MemoryBuffer.h" +#include "llvm/Support/VirtualFileSystem.h" #include "gtest/gtest.h" #include #include Index: clang-tools-extra/trunk/unittests/clang-tidy/ClangTidyTest.h =================================================================== --- clang-tools-extra/trunk/unittests/clang-tidy/ClangTidyTest.h +++ clang-tools-extra/trunk/unittests/clang-tidy/ClangTidyTest.h @@ -99,8 +99,8 @@ Args.push_back(Filename.str()); ast_matchers::MatchFinder Finder; - llvm::IntrusiveRefCntPtr InMemoryFileSystem( - new vfs::InMemoryFileSystem); + llvm::IntrusiveRefCntPtr InMemoryFileSystem( + new llvm::vfs::InMemoryFileSystem); llvm::IntrusiveRefCntPtr Files( new FileManager(FileSystemOptions(), InMemoryFileSystem)); Index: clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp =================================================================== --- clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp +++ clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp @@ -264,7 +264,7 @@ TEST_F(ClangdVFSTest, PropagatesContexts) { static Key Secret; struct FSProvider : public FileSystemProvider { - IntrusiveRefCntPtr getFileSystem() const override { + IntrusiveRefCntPtr getFileSystem() const override { Got = Context::current().getExisting(Secret); return buildTestFS({}); } @@ -973,19 +973,19 @@ ListenStatsFSProvider(llvm::StringMap &CountStats) : CountStats(CountStats) {} - IntrusiveRefCntPtr getFileSystem() const override { - class ListenStatVFS : public vfs::ProxyFileSystem { + IntrusiveRefCntPtr getFileSystem() const override { + class ListenStatVFS : public llvm::vfs::ProxyFileSystem { public: - ListenStatVFS(IntrusiveRefCntPtr FS, + ListenStatVFS(IntrusiveRefCntPtr FS, llvm::StringMap &CountStats) : ProxyFileSystem(std::move(FS)), CountStats(CountStats) {} - llvm::ErrorOr> + llvm::ErrorOr> openFileForRead(const Twine &Path) override { ++CountStats[llvm::sys::path::filename(Path.str())]; return ProxyFileSystem::openFileForRead(Path); } - llvm::ErrorOr status(const Twine &Path) override { + llvm::ErrorOr status(const Twine &Path) override { ++CountStats[llvm::sys::path::filename(Path.str())]; return ProxyFileSystem::status(Path); } Index: clang-tools-extra/trunk/unittests/clangd/FSTests.cpp =================================================================== --- clang-tools-extra/trunk/unittests/clangd/FSTests.cpp +++ clang-tools-extra/trunk/unittests/clangd/FSTests.cpp @@ -35,9 +35,10 @@ // Main file is not cached. EXPECT_FALSE(StatCache.lookup(testPath("main")).hasValue()); - vfs::Status S("fake", llvm::sys::fs::UniqueID(0, 0), - std::chrono::system_clock::now(), 0, 0, 1024, - llvm::sys::fs::file_type::regular_file, llvm::sys::fs::all_all); + llvm::vfs::Status S("fake", llvm::sys::fs::UniqueID(0, 0), + std::chrono::system_clock::now(), 0, 0, 1024, + llvm::sys::fs::file_type::regular_file, + llvm::sys::fs::all_all); StatCache.update(*FS, S); auto ConsumeFS = StatCache.getConsumingFS(FS); auto Cached = ConsumeFS->status(testPath("fake")); Index: clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp =================================================================== --- clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp +++ clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp @@ -13,7 +13,6 @@ #include "index/SymbolCollector.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemOptions.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Index/IndexingAction.h" #include "clang/Tooling/Tooling.h" @@ -21,6 +20,7 @@ #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/MemoryBuffer.h" +#include "llvm/Support/VirtualFileSystem.h" #include "gmock/gmock.h" #include "gtest/gtest.h" @@ -219,7 +219,7 @@ class SymbolCollectorTest : public ::testing::Test { public: SymbolCollectorTest() - : InMemoryFileSystem(new vfs::InMemoryFileSystem), + : InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem), TestHeaderName(testPath("symbol.h")), TestFileName(testPath("symbol.cc")) { TestHeaderURI = URI::createFile(TestHeaderName).toString(); @@ -258,7 +258,7 @@ } protected: - llvm::IntrusiveRefCntPtr InMemoryFileSystem; + llvm::IntrusiveRefCntPtr InMemoryFileSystem; std::string TestHeaderName; std::string TestHeaderURI; std::string TestFileName; Index: clang-tools-extra/trunk/unittests/clangd/TestFS.h =================================================================== --- clang-tools-extra/trunk/unittests/clangd/TestFS.h +++ clang-tools-extra/trunk/unittests/clangd/TestFS.h @@ -13,23 +13,23 @@ #ifndef LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_TESTFS_H #define LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_TESTFS_H #include "ClangdServer.h" -#include "clang/Basic/VirtualFileSystem.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/Support/Path.h" +#include "llvm/Support/VirtualFileSystem.h" namespace clang { namespace clangd { // Builds a VFS that provides access to the provided files, plus temporary // directories. -llvm::IntrusiveRefCntPtr +llvm::IntrusiveRefCntPtr buildTestFS(llvm::StringMap const &Files, llvm::StringMap const &Timestamps = {}); // A VFS provider that returns TestFSes containing a provided set of files. class MockFSProvider : public FileSystemProvider { public: - IntrusiveRefCntPtr getFileSystem() const override { + IntrusiveRefCntPtr getFileSystem() const override { return buildTestFS(Files); } Index: clang-tools-extra/trunk/unittests/include-fixer/IncludeFixerTest.cpp =================================================================== --- clang-tools-extra/trunk/unittests/include-fixer/IncludeFixerTest.cpp +++ clang-tools-extra/trunk/unittests/include-fixer/IncludeFixerTest.cpp @@ -24,8 +24,8 @@ static bool runOnCode(tooling::ToolAction *ToolAction, StringRef Code, StringRef FileName, const std::vector &ExtraArgs) { - llvm::IntrusiveRefCntPtr InMemoryFileSystem( - new vfs::InMemoryFileSystem); + llvm::IntrusiveRefCntPtr InMemoryFileSystem( + new llvm::vfs::InMemoryFileSystem); llvm::IntrusiveRefCntPtr Files( new FileManager(FileSystemOptions(), InMemoryFileSystem)); // FIXME: Investigate why -fms-compatibility breaks tests. Index: clang-tools-extra/trunk/unittests/include-fixer/find-all-symbols/FindAllSymbolsTests.cpp =================================================================== --- clang-tools-extra/trunk/unittests/include-fixer/find-all-symbols/FindAllSymbolsTests.cpp +++ clang-tools-extra/trunk/unittests/include-fixer/find-all-symbols/FindAllSymbolsTests.cpp @@ -14,7 +14,6 @@ #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemOptions.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/PCHContainerOperations.h" #include "clang/Tooling/Tooling.h" @@ -22,6 +21,7 @@ #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/MemoryBuffer.h" +#include "llvm/Support/VirtualFileSystem.h" #include "gtest/gtest.h" #include #include @@ -63,8 +63,8 @@ int used(const SymbolInfo &Symbol) { return Reporter.used(Symbol); } bool runFindAllSymbols(StringRef HeaderCode, StringRef MainCode) { - llvm::IntrusiveRefCntPtr InMemoryFileSystem( - new vfs::InMemoryFileSystem); + llvm::IntrusiveRefCntPtr InMemoryFileSystem( + new llvm::vfs::InMemoryFileSystem); llvm::IntrusiveRefCntPtr Files( new FileManager(FileSystemOptions(), InMemoryFileSystem)); Index: llvm/trunk/include/llvm/Support/VirtualFileSystem.h =================================================================== --- llvm/trunk/include/llvm/Support/VirtualFileSystem.h +++ llvm/trunk/include/llvm/Support/VirtualFileSystem.h @@ -0,0 +1,522 @@ +//===- VirtualFileSystem.h - Virtual File System Layer ----------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +/// \file +/// Defines the virtual file system interface vfs::FileSystem. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_VIRTUALFILESYSTEM_H +#define LLVM_SUPPORT_VIRTUALFILESYSTEM_H + +#include "llvm/ADT/IntrusiveRefCntPtr.h" +#include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/Twine.h" +#include "llvm/Support/Chrono.h" +#include "llvm/Support/ErrorOr.h" +#include "llvm/Support/FileSystem.h" +#include "llvm/Support/SourceMgr.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace llvm { + +class MemoryBuffer; + +namespace vfs { + +/// The result of a \p status operation. +class Status { + std::string Name; + llvm::sys::fs::UniqueID UID; + llvm::sys::TimePoint<> MTime; + uint32_t User; + uint32_t Group; + uint64_t Size; + llvm::sys::fs::file_type Type = llvm::sys::fs::file_type::status_error; + llvm::sys::fs::perms Perms; + +public: + // FIXME: remove when files support multiple names + bool IsVFSMapped = false; + + Status() = default; + Status(const llvm::sys::fs::file_status &Status); + Status(StringRef Name, llvm::sys::fs::UniqueID UID, + llvm::sys::TimePoint<> MTime, uint32_t User, uint32_t Group, + uint64_t Size, llvm::sys::fs::file_type Type, + llvm::sys::fs::perms Perms); + + /// Get a copy of a Status with a different name. + static Status copyWithNewName(const Status &In, StringRef NewName); + static Status copyWithNewName(const llvm::sys::fs::file_status &In, + StringRef NewName); + + /// Returns the name that should be used for this file or directory. + StringRef getName() const { return Name; } + + /// @name Status interface from llvm::sys::fs + /// @{ + llvm::sys::fs::file_type getType() const { return Type; } + llvm::sys::fs::perms getPermissions() const { return Perms; } + llvm::sys::TimePoint<> getLastModificationTime() const { return MTime; } + llvm::sys::fs::UniqueID getUniqueID() const { return UID; } + uint32_t getUser() const { return User; } + uint32_t getGroup() const { return Group; } + uint64_t getSize() const { return Size; } + /// @} + /// @name Status queries + /// These are static queries in llvm::sys::fs. + /// @{ + bool equivalent(const Status &Other) const; + bool isDirectory() const; + bool isRegularFile() const; + bool isOther() const; + bool isSymlink() const; + bool isStatusKnown() const; + bool exists() const; + /// @} +}; + +/// Represents an open file. +class File { +public: + /// Destroy the file after closing it (if open). + /// Sub-classes should generally call close() inside their destructors. We + /// cannot do that from the base class, since close is virtual. + virtual ~File(); + + /// Get the status of the file. + virtual llvm::ErrorOr status() = 0; + + /// Get the name of the file + virtual llvm::ErrorOr getName() { + if (auto Status = status()) + return Status->getName().str(); + else + return Status.getError(); + } + + /// Get the contents of the file as a \p MemoryBuffer. + virtual llvm::ErrorOr> + getBuffer(const Twine &Name, int64_t FileSize = -1, + bool RequiresNullTerminator = true, bool IsVolatile = false) = 0; + + /// Closes the file. + virtual std::error_code close() = 0; +}; + +/// A member of a directory, yielded by a directory_iterator. +/// Only information available on most platforms is included. +class directory_entry { + std::string Path; + llvm::sys::fs::file_type Type; + +public: + directory_entry() = default; + directory_entry(std::string Path, llvm::sys::fs::file_type Type) + : Path(std::move(Path)), Type(Type) {} + + llvm::StringRef path() const { return Path; } + llvm::sys::fs::file_type type() const { return Type; } +}; + +namespace detail { + +/// An interface for virtual file systems to provide an iterator over the +/// (non-recursive) contents of a directory. +struct DirIterImpl { + virtual ~DirIterImpl(); + + /// Sets \c CurrentEntry to the next entry in the directory on success, + /// to directory_entry() at end, or returns a system-defined \c error_code. + virtual std::error_code increment() = 0; + + directory_entry CurrentEntry; +}; + +} // namespace detail + +/// An input iterator over the entries in a virtual path, similar to +/// llvm::sys::fs::directory_iterator. +class directory_iterator { + std::shared_ptr Impl; // Input iterator semantics on copy + +public: + directory_iterator(std::shared_ptr I) + : Impl(std::move(I)) { + assert(Impl.get() != nullptr && "requires non-null implementation"); + if (Impl->CurrentEntry.path().empty()) + Impl.reset(); // Normalize the end iterator to Impl == nullptr. + } + + /// Construct an 'end' iterator. + directory_iterator() = default; + + /// Equivalent to operator++, with an error code. + directory_iterator &increment(std::error_code &EC) { + assert(Impl && "attempting to increment past end"); + EC = Impl->increment(); + if (Impl->CurrentEntry.path().empty()) + Impl.reset(); // Normalize the end iterator to Impl == nullptr. + return *this; + } + + const directory_entry &operator*() const { return Impl->CurrentEntry; } + const directory_entry *operator->() const { return &Impl->CurrentEntry; } + + bool operator==(const directory_iterator &RHS) const { + if (Impl && RHS.Impl) + return Impl->CurrentEntry.path() == RHS.Impl->CurrentEntry.path(); + return !Impl && !RHS.Impl; + } + bool operator!=(const directory_iterator &RHS) const { + return !(*this == RHS); + } +}; + +class FileSystem; + +/// An input iterator over the recursive contents of a virtual path, +/// similar to llvm::sys::fs::recursive_directory_iterator. +class recursive_directory_iterator { + using IterState = + std::stack>; + + FileSystem *FS; + std::shared_ptr State; // Input iterator semantics on copy. + +public: + recursive_directory_iterator(FileSystem &FS, const Twine &Path, + std::error_code &EC); + + /// Construct an 'end' iterator. + recursive_directory_iterator() = default; + + /// Equivalent to operator++, with an error code. + recursive_directory_iterator &increment(std::error_code &EC); + + const directory_entry &operator*() const { return *State->top(); } + const directory_entry *operator->() const { return &*State->top(); } + + bool operator==(const recursive_directory_iterator &Other) const { + return State == Other.State; // identity + } + bool operator!=(const recursive_directory_iterator &RHS) const { + return !(*this == RHS); + } + + /// Gets the current level. Starting path is at level 0. + int level() const { + assert(!State->empty() && "Cannot get level without any iteration state"); + return State->size() - 1; + } +}; + +/// The virtual file system interface. +class FileSystem : public llvm::ThreadSafeRefCountedBase { +public: + virtual ~FileSystem(); + + /// Get the status of the entry at \p Path, if one exists. + virtual llvm::ErrorOr status(const Twine &Path) = 0; + + /// Get a \p File object for the file at \p Path, if one exists. + virtual llvm::ErrorOr> + openFileForRead(const Twine &Path) = 0; + + /// This is a convenience method that opens a file, gets its content and then + /// closes the file. + llvm::ErrorOr> + getBufferForFile(const Twine &Name, int64_t FileSize = -1, + bool RequiresNullTerminator = true, bool IsVolatile = false); + + /// Get a directory_iterator for \p Dir. + /// \note The 'end' iterator is directory_iterator(). + virtual directory_iterator dir_begin(const Twine &Dir, + std::error_code &EC) = 0; + + /// Set the working directory. This will affect all following operations on + /// this file system and may propagate down for nested file systems. + virtual std::error_code setCurrentWorkingDirectory(const Twine &Path) = 0; + + /// Get the working directory of this file system. + virtual llvm::ErrorOr getCurrentWorkingDirectory() const = 0; + + /// Gets real path of \p Path e.g. collapse all . and .. patterns, resolve + /// symlinks. For real file system, this uses `llvm::sys::fs::real_path`. + /// This returns errc::operation_not_permitted if not implemented by subclass. + virtual std::error_code getRealPath(const Twine &Path, + SmallVectorImpl &Output) const; + + /// Check whether a file exists. Provided for convenience. + bool exists(const Twine &Path); + + /// Make \a Path an absolute path. + /// + /// Makes \a Path absolute using the current directory if it is not already. + /// An empty \a Path will result in the current directory. + /// + /// /absolute/path => /absolute/path + /// relative/../path => /relative/../path + /// + /// \param Path A path that is modified to be an absolute path. + /// \returns success if \a path has been made absolute, otherwise a + /// platform-specific error_code. + std::error_code makeAbsolute(SmallVectorImpl &Path) const; +}; + +/// Gets an \p vfs::FileSystem for the 'real' file system, as seen by +/// the operating system. +IntrusiveRefCntPtr getRealFileSystem(); + +/// A file system that allows overlaying one \p AbstractFileSystem on top +/// of another. +/// +/// Consists of a stack of >=1 \p FileSystem objects, which are treated as being +/// one merged file system. When there is a directory that exists in more than +/// one file system, the \p OverlayFileSystem contains a directory containing +/// the union of their contents. The attributes (permissions, etc.) of the +/// top-most (most recently added) directory are used. When there is a file +/// that exists in more than one file system, the file in the top-most file +/// system overrides the other(s). +class OverlayFileSystem : public FileSystem { + using FileSystemList = SmallVector, 1>; + + /// The stack of file systems, implemented as a list in order of + /// their addition. + FileSystemList FSList; + +public: + OverlayFileSystem(IntrusiveRefCntPtr Base); + + /// Pushes a file system on top of the stack. + void pushOverlay(IntrusiveRefCntPtr FS); + + llvm::ErrorOr status(const Twine &Path) override; + llvm::ErrorOr> + openFileForRead(const Twine &Path) override; + directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override; + llvm::ErrorOr getCurrentWorkingDirectory() const override; + std::error_code setCurrentWorkingDirectory(const Twine &Path) override; + std::error_code getRealPath(const Twine &Path, + SmallVectorImpl &Output) const override; + + using iterator = FileSystemList::reverse_iterator; + using const_iterator = FileSystemList::const_reverse_iterator; + + /// Get an iterator pointing to the most recently added file system. + iterator overlays_begin() { return FSList.rbegin(); } + const_iterator overlays_begin() const { return FSList.rbegin(); } + + /// Get an iterator pointing one-past the least recently added file + /// system. + iterator overlays_end() { return FSList.rend(); } + const_iterator overlays_end() const { return FSList.rend(); } +}; + +/// By default, this delegates all calls to the underlying file system. This +/// is useful when derived file systems want to override some calls and still +/// proxy other calls. +class ProxyFileSystem : public FileSystem { +public: + explicit ProxyFileSystem(IntrusiveRefCntPtr FS) + : FS(std::move(FS)) {} + + llvm::ErrorOr status(const Twine &Path) override { + return FS->status(Path); + } + llvm::ErrorOr> + openFileForRead(const Twine &Path) override { + return FS->openFileForRead(Path); + } + directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override { + return FS->dir_begin(Dir, EC); + } + llvm::ErrorOr getCurrentWorkingDirectory() const override { + return FS->getCurrentWorkingDirectory(); + } + std::error_code setCurrentWorkingDirectory(const Twine &Path) override { + return FS->setCurrentWorkingDirectory(Path); + } + std::error_code getRealPath(const Twine &Path, + SmallVectorImpl &Output) const override { + return FS->getRealPath(Path, Output); + } + +protected: + FileSystem &getUnderlyingFS() { return *FS; } + +private: + IntrusiveRefCntPtr FS; +}; + +namespace detail { + +class InMemoryDirectory; +class InMemoryFile; + +} // namespace detail + +/// An in-memory file system. +class InMemoryFileSystem : public FileSystem { + std::unique_ptr Root; + std::string WorkingDirectory; + bool UseNormalizedPaths = true; + + /// If HardLinkTarget is non-null, a hardlink is created to the To path which + /// must be a file. If it is null then it adds the file as the public addFile. + bool addFile(const Twine &Path, time_t ModificationTime, + std::unique_ptr Buffer, + Optional User, Optional Group, + Optional Type, + Optional Perms, + const detail::InMemoryFile *HardLinkTarget); + +public: + explicit InMemoryFileSystem(bool UseNormalizedPaths = true); + ~InMemoryFileSystem() override; + + /// Add a file containing a buffer or a directory to the VFS with a + /// path. The VFS owns the buffer. If present, User, Group, Type + /// and Perms apply to the newly-created file or directory. + /// \return true if the file or directory was successfully added, + /// false if the file or directory already exists in the file system with + /// different contents. + bool addFile(const Twine &Path, time_t ModificationTime, + std::unique_ptr Buffer, + Optional User = None, Optional Group = None, + Optional Type = None, + Optional Perms = None); + + /// Add a hard link to a file. + /// Here hard links are not intended to be fully equivalent to the classical + /// filesystem. Both the hard link and the file share the same buffer and + /// status (and thus have the same UniqueID). Because of this there is no way + /// to distinguish between the link and the file after the link has been + /// added. + /// + /// The To path must be an existing file or a hardlink. The From file must not + /// have been added before. The To Path must not be a directory. The From Node + /// is added as a hard link which points to the resolved file of To Node. + /// \return true if the above condition is satisfied and hardlink was + /// successfully created, false otherwise. + bool addHardLink(const Twine &From, const Twine &To); + + /// Add a buffer to the VFS with a path. The VFS does not own the buffer. + /// If present, User, Group, Type and Perms apply to the newly-created file + /// or directory. + /// \return true if the file or directory was successfully added, + /// false if the file or directory already exists in the file system with + /// different contents. + bool addFileNoOwn(const Twine &Path, time_t ModificationTime, + llvm::MemoryBuffer *Buffer, Optional User = None, + Optional Group = None, + Optional Type = None, + Optional Perms = None); + + std::string toString() const; + + /// Return true if this file system normalizes . and .. in paths. + bool useNormalizedPaths() const { return UseNormalizedPaths; } + + llvm::ErrorOr status(const Twine &Path) override; + llvm::ErrorOr> + openFileForRead(const Twine &Path) override; + directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override; + + llvm::ErrorOr getCurrentWorkingDirectory() const override { + return WorkingDirectory; + } + /// Canonicalizes \p Path by combining with the current working + /// directory and normalizing the path (e.g. remove dots). If the current + /// working directory is not set, this returns errc::operation_not_permitted. + /// + /// This doesn't resolve symlinks as they are not supported in in-memory file + /// system. + std::error_code getRealPath(const Twine &Path, + SmallVectorImpl &Output) const override; + + std::error_code setCurrentWorkingDirectory(const Twine &Path) override; +}; + +/// Get a globally unique ID for a virtual file or directory. +llvm::sys::fs::UniqueID getNextVirtualUniqueID(); + +/// Gets a \p FileSystem for a virtual file system described in YAML +/// format. +IntrusiveRefCntPtr +getVFSFromYAML(std::unique_ptr Buffer, + llvm::SourceMgr::DiagHandlerTy DiagHandler, + StringRef YAMLFilePath, void *DiagContext = nullptr, + IntrusiveRefCntPtr ExternalFS = getRealFileSystem()); + +struct YAMLVFSEntry { + template + YAMLVFSEntry(T1 &&VPath, T2 &&RPath) + : VPath(std::forward(VPath)), RPath(std::forward(RPath)) {} + std::string VPath; + std::string RPath; +}; + +/// Collect all pairs of entries from the +/// \p YAMLFilePath. This is used by the module dependency collector to forward +/// the entries into the reproducer output VFS YAML file. +void collectVFSFromYAML( + std::unique_ptr Buffer, + llvm::SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath, + SmallVectorImpl &CollectedEntries, + void *DiagContext = nullptr, + IntrusiveRefCntPtr ExternalFS = getRealFileSystem()); + +class YAMLVFSWriter { + std::vector Mappings; + Optional IsCaseSensitive; + Optional IsOverlayRelative; + Optional UseExternalNames; + Optional IgnoreNonExistentContents; + std::string OverlayDir; + +public: + YAMLVFSWriter() = default; + + void addFileMapping(StringRef VirtualPath, StringRef RealPath); + + void setCaseSensitivity(bool CaseSensitive) { + IsCaseSensitive = CaseSensitive; + } + + void setUseExternalNames(bool UseExtNames) { UseExternalNames = UseExtNames; } + + void setIgnoreNonExistentContents(bool IgnoreContents) { + IgnoreNonExistentContents = IgnoreContents; + } + + void setOverlayDir(StringRef OverlayDirectory) { + IsOverlayRelative = true; + OverlayDir.assign(OverlayDirectory.str()); + } + + void write(llvm::raw_ostream &OS); +}; + +} // namespace vfs +} // namespace llvm + +#endif // LLVM_SUPPORT_VIRTUALFILESYSTEM_H Index: llvm/trunk/lib/Support/CMakeLists.txt =================================================================== --- llvm/trunk/lib/Support/CMakeLists.txt +++ llvm/trunk/lib/Support/CMakeLists.txt @@ -135,6 +135,7 @@ Unicode.cpp UnicodeCaseFold.cpp VersionTuple.cpp + VirtualFileSystem.cpp WithColor.cpp YAMLParser.cpp YAMLTraits.cpp Index: llvm/trunk/lib/Support/VirtualFileSystem.cpp =================================================================== --- llvm/trunk/lib/Support/VirtualFileSystem.cpp +++ llvm/trunk/lib/Support/VirtualFileSystem.cpp @@ -0,0 +1,2121 @@ +//===- VirtualFileSystem.cpp - Virtual File System Layer ------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file implements the VirtualFileSystem interface. +// +//===----------------------------------------------------------------------===// + +#include "llvm/Support/VirtualFileSystem.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/IntrusiveRefCntPtr.h" +#include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallString.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/StringSet.h" +#include "llvm/ADT/Twine.h" +#include "llvm/ADT/iterator_range.h" +#include "llvm/Config/llvm-config.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/Chrono.h" +#include "llvm/Support/Compiler.h" +#include "llvm/Support/Debug.h" +#include "llvm/Support/Errc.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/ErrorOr.h" +#include "llvm/Support/FileSystem.h" +#include "llvm/Support/MemoryBuffer.h" +#include "llvm/Support/Path.h" +#include "llvm/Support/Process.h" +#include "llvm/Support/SMLoc.h" +#include "llvm/Support/SourceMgr.h" +#include "llvm/Support/YAMLParser.h" +#include "llvm/Support/raw_ostream.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace llvm; +using namespace llvm::vfs; + +using llvm::sys::fs::file_status; +using llvm::sys::fs::file_type; +using llvm::sys::fs::perms; +using llvm::sys::fs::UniqueID; + +Status::Status(const file_status &Status) + : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()), + User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()), + Type(Status.type()), Perms(Status.permissions()) {} + +Status::Status(StringRef Name, UniqueID UID, sys::TimePoint<> MTime, + uint32_t User, uint32_t Group, uint64_t Size, file_type Type, + perms Perms) + : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size), + Type(Type), Perms(Perms) {} + +Status Status::copyWithNewName(const Status &In, StringRef NewName) { + return Status(NewName, In.getUniqueID(), In.getLastModificationTime(), + In.getUser(), In.getGroup(), In.getSize(), In.getType(), + In.getPermissions()); +} + +Status Status::copyWithNewName(const file_status &In, StringRef NewName) { + return Status(NewName, In.getUniqueID(), In.getLastModificationTime(), + In.getUser(), In.getGroup(), In.getSize(), In.type(), + In.permissions()); +} + +bool Status::equivalent(const Status &Other) const { + assert(isStatusKnown() && Other.isStatusKnown()); + return getUniqueID() == Other.getUniqueID(); +} + +bool Status::isDirectory() const { return Type == file_type::directory_file; } + +bool Status::isRegularFile() const { return Type == file_type::regular_file; } + +bool Status::isOther() const { + return exists() && !isRegularFile() && !isDirectory() && !isSymlink(); +} + +bool Status::isSymlink() const { return Type == file_type::symlink_file; } + +bool Status::isStatusKnown() const { return Type != file_type::status_error; } + +bool Status::exists() const { + return isStatusKnown() && Type != file_type::file_not_found; +} + +File::~File() = default; + +FileSystem::~FileSystem() = default; + +ErrorOr> +FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize, + bool RequiresNullTerminator, bool IsVolatile) { + auto F = openFileForRead(Name); + if (!F) + return F.getError(); + + return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile); +} + +std::error_code FileSystem::makeAbsolute(SmallVectorImpl &Path) const { + if (llvm::sys::path::is_absolute(Path)) + return {}; + + auto WorkingDir = getCurrentWorkingDirectory(); + if (!WorkingDir) + return WorkingDir.getError(); + + return llvm::sys::fs::make_absolute(WorkingDir.get(), Path); +} + +std::error_code FileSystem::getRealPath(const Twine &Path, + SmallVectorImpl &Output) const { + return errc::operation_not_permitted; +} + +bool FileSystem::exists(const Twine &Path) { + auto Status = status(Path); + return Status && Status->exists(); +} + +#ifndef NDEBUG +static bool isTraversalComponent(StringRef Component) { + return Component.equals("..") || Component.equals("."); +} + +static bool pathHasTraversal(StringRef Path) { + using namespace llvm::sys; + + for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path))) + if (isTraversalComponent(Comp)) + return true; + return false; +} +#endif + +//===-----------------------------------------------------------------------===/ +// RealFileSystem implementation +//===-----------------------------------------------------------------------===/ + +namespace { + +/// Wrapper around a raw file descriptor. +class RealFile : public File { + friend class RealFileSystem; + + int FD; + Status S; + std::string RealName; + + RealFile(int FD, StringRef NewName, StringRef NewRealPathName) + : FD(FD), S(NewName, {}, {}, {}, {}, {}, + llvm::sys::fs::file_type::status_error, {}), + RealName(NewRealPathName.str()) { + assert(FD >= 0 && "Invalid or inactive file descriptor"); + } + +public: + ~RealFile() override; + + ErrorOr status() override; + ErrorOr getName() override; + ErrorOr> getBuffer(const Twine &Name, + int64_t FileSize, + bool RequiresNullTerminator, + bool IsVolatile) override; + std::error_code close() override; +}; + +} // namespace + +RealFile::~RealFile() { close(); } + +ErrorOr RealFile::status() { + assert(FD != -1 && "cannot stat closed file"); + if (!S.isStatusKnown()) { + file_status RealStatus; + if (std::error_code EC = sys::fs::status(FD, RealStatus)) + return EC; + S = Status::copyWithNewName(RealStatus, S.getName()); + } + return S; +} + +ErrorOr RealFile::getName() { + return RealName.empty() ? S.getName().str() : RealName; +} + +ErrorOr> +RealFile::getBuffer(const Twine &Name, int64_t FileSize, + bool RequiresNullTerminator, bool IsVolatile) { + assert(FD != -1 && "cannot get buffer for closed file"); + return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator, + IsVolatile); +} + +std::error_code RealFile::close() { + std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD); + FD = -1; + return EC; +} + +namespace { + +/// The file system according to your operating system. +class RealFileSystem : public FileSystem { +public: + ErrorOr status(const Twine &Path) override; + ErrorOr> openFileForRead(const Twine &Path) override; + directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override; + + llvm::ErrorOr getCurrentWorkingDirectory() const override; + std::error_code setCurrentWorkingDirectory(const Twine &Path) override; + std::error_code getRealPath(const Twine &Path, + SmallVectorImpl &Output) const override; + +private: + mutable std::mutex CWDMutex; + mutable std::string CWDCache; +}; + +} // namespace + +ErrorOr RealFileSystem::status(const Twine &Path) { + sys::fs::file_status RealStatus; + if (std::error_code EC = sys::fs::status(Path, RealStatus)) + return EC; + return Status::copyWithNewName(RealStatus, Path.str()); +} + +ErrorOr> +RealFileSystem::openFileForRead(const Twine &Name) { + int FD; + SmallString<256> RealName; + if (std::error_code EC = + sys::fs::openFileForRead(Name, FD, sys::fs::OF_None, &RealName)) + return EC; + return std::unique_ptr(new RealFile(FD, Name.str(), RealName.str())); +} + +llvm::ErrorOr RealFileSystem::getCurrentWorkingDirectory() const { + std::lock_guard Lock(CWDMutex); + if (!CWDCache.empty()) + return CWDCache; + SmallString<256> Dir; + if (std::error_code EC = llvm::sys::fs::current_path(Dir)) + return EC; + CWDCache = Dir.str(); + return CWDCache; +} + +std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) { + // FIXME: chdir is thread hostile; on the other hand, creating the same + // behavior as chdir is complex: chdir resolves the path once, thus + // guaranteeing that all subsequent relative path operations work + // on the same path the original chdir resulted in. This makes a + // difference for example on network filesystems, where symlinks might be + // switched during runtime of the tool. Fixing this depends on having a + // file system abstraction that allows openat() style interactions. + if (auto EC = llvm::sys::fs::set_current_path(Path)) + return EC; + + // Invalidate cache. + std::lock_guard Lock(CWDMutex); + CWDCache.clear(); + return std::error_code(); +} + +std::error_code +RealFileSystem::getRealPath(const Twine &Path, + SmallVectorImpl &Output) const { + return llvm::sys::fs::real_path(Path, Output); +} + +IntrusiveRefCntPtr vfs::getRealFileSystem() { + static IntrusiveRefCntPtr FS = new RealFileSystem(); + return FS; +} + +namespace { + +class RealFSDirIter : public llvm::vfs::detail::DirIterImpl { + llvm::sys::fs::directory_iterator Iter; + +public: + RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) { + if (Iter != llvm::sys::fs::directory_iterator()) + CurrentEntry = directory_entry(Iter->path(), Iter->type()); + } + + std::error_code increment() override { + std::error_code EC; + Iter.increment(EC); + CurrentEntry = (Iter == llvm::sys::fs::directory_iterator()) + ? directory_entry() + : directory_entry(Iter->path(), Iter->type()); + return EC; + } +}; + +} // namespace + +directory_iterator RealFileSystem::dir_begin(const Twine &Dir, + std::error_code &EC) { + return directory_iterator(std::make_shared(Dir, EC)); +} + +//===-----------------------------------------------------------------------===/ +// OverlayFileSystem implementation +//===-----------------------------------------------------------------------===/ + +OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr BaseFS) { + FSList.push_back(std::move(BaseFS)); +} + +void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr FS) { + FSList.push_back(FS); + // Synchronize added file systems by duplicating the working directory from + // the first one in the list. + FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get()); +} + +ErrorOr OverlayFileSystem::status(const Twine &Path) { + // FIXME: handle symlinks that cross file systems + for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) { + ErrorOr Status = (*I)->status(Path); + if (Status || Status.getError() != llvm::errc::no_such_file_or_directory) + return Status; + } + return make_error_code(llvm::errc::no_such_file_or_directory); +} + +ErrorOr> +OverlayFileSystem::openFileForRead(const llvm::Twine &Path) { + // FIXME: handle symlinks that cross file systems + for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) { + auto Result = (*I)->openFileForRead(Path); + if (Result || Result.getError() != llvm::errc::no_such_file_or_directory) + return Result; + } + return make_error_code(llvm::errc::no_such_file_or_directory); +} + +llvm::ErrorOr +OverlayFileSystem::getCurrentWorkingDirectory() const { + // All file systems are synchronized, just take the first working directory. + return FSList.front()->getCurrentWorkingDirectory(); +} + +std::error_code +OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) { + for (auto &FS : FSList) + if (std::error_code EC = FS->setCurrentWorkingDirectory(Path)) + return EC; + return {}; +} + +std::error_code +OverlayFileSystem::getRealPath(const Twine &Path, + SmallVectorImpl &Output) const { + for (auto &FS : FSList) + if (FS->exists(Path)) + return FS->getRealPath(Path, Output); + return errc::no_such_file_or_directory; +} + +llvm::vfs::detail::DirIterImpl::~DirIterImpl() = default; + +namespace { + +class OverlayFSDirIterImpl : public llvm::vfs::detail::DirIterImpl { + OverlayFileSystem &Overlays; + std::string Path; + OverlayFileSystem::iterator CurrentFS; + directory_iterator CurrentDirIter; + llvm::StringSet<> SeenNames; + + std::error_code incrementFS() { + assert(CurrentFS != Overlays.overlays_end() && "incrementing past end"); + ++CurrentFS; + for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) { + std::error_code EC; + CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC); + if (EC && EC != errc::no_such_file_or_directory) + return EC; + if (CurrentDirIter != directory_iterator()) + break; // found + } + return {}; + } + + std::error_code incrementDirIter(bool IsFirstTime) { + assert((IsFirstTime || CurrentDirIter != directory_iterator()) && + "incrementing past end"); + std::error_code EC; + if (!IsFirstTime) + CurrentDirIter.increment(EC); + if (!EC && CurrentDirIter == directory_iterator()) + EC = incrementFS(); + return EC; + } + + std::error_code incrementImpl(bool IsFirstTime) { + while (true) { + std::error_code EC = incrementDirIter(IsFirstTime); + if (EC || CurrentDirIter == directory_iterator()) { + CurrentEntry = directory_entry(); + return EC; + } + CurrentEntry = *CurrentDirIter; + StringRef Name = llvm::sys::path::filename(CurrentEntry.path()); + if (SeenNames.insert(Name).second) + return EC; // name not seen before + } + llvm_unreachable("returned above"); + } + +public: + OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS, + std::error_code &EC) + : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) { + CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC); + EC = incrementImpl(true); + } + + std::error_code increment() override { return incrementImpl(false); } +}; + +} // namespace + +directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir, + std::error_code &EC) { + return directory_iterator( + std::make_shared(Dir, *this, EC)); +} + +namespace llvm { +namespace vfs { + +namespace detail { + +enum InMemoryNodeKind { IME_File, IME_Directory, IME_HardLink }; + +/// The in memory file system is a tree of Nodes. Every node can either be a +/// file , hardlink or a directory. +class InMemoryNode { + InMemoryNodeKind Kind; + std::string FileName; + +public: + InMemoryNode(llvm::StringRef FileName, InMemoryNodeKind Kind) + : Kind(Kind), FileName(llvm::sys::path::filename(FileName)) {} + virtual ~InMemoryNode() = default; + + /// Get the filename of this node (the name without the directory part). + StringRef getFileName() const { return FileName; } + InMemoryNodeKind getKind() const { return Kind; } + virtual std::string toString(unsigned Indent) const = 0; +}; + +class InMemoryFile : public InMemoryNode { + Status Stat; + std::unique_ptr Buffer; + +public: + InMemoryFile(Status Stat, std::unique_ptr Buffer) + : InMemoryNode(Stat.getName(), IME_File), Stat(std::move(Stat)), + Buffer(std::move(Buffer)) {} + + /// Return the \p Status for this node. \p RequestedName should be the name + /// through which the caller referred to this node. It will override + /// \p Status::Name in the return value, to mimic the behavior of \p RealFile. + Status getStatus(StringRef RequestedName) const { + return Status::copyWithNewName(Stat, RequestedName); + } + llvm::MemoryBuffer *getBuffer() const { return Buffer.get(); } + + std::string toString(unsigned Indent) const override { + return (std::string(Indent, ' ') + Stat.getName() + "\n").str(); + } + + static bool classof(const InMemoryNode *N) { + return N->getKind() == IME_File; + } +}; + +namespace { + +class InMemoryHardLink : public InMemoryNode { + const InMemoryFile &ResolvedFile; + +public: + InMemoryHardLink(StringRef Path, const InMemoryFile &ResolvedFile) + : InMemoryNode(Path, IME_HardLink), ResolvedFile(ResolvedFile) {} + const InMemoryFile &getResolvedFile() const { return ResolvedFile; } + + std::string toString(unsigned Indent) const override { + return std::string(Indent, ' ') + "HardLink to -> " + + ResolvedFile.toString(0); + } + + static bool classof(const InMemoryNode *N) { + return N->getKind() == IME_HardLink; + } +}; + +/// Adapt a InMemoryFile for VFS' File interface. The goal is to make +/// \p InMemoryFileAdaptor mimic as much as possible the behavior of +/// \p RealFile. +class InMemoryFileAdaptor : public File { + const InMemoryFile &Node; + /// The name to use when returning a Status for this file. + std::string RequestedName; + +public: + explicit InMemoryFileAdaptor(const InMemoryFile &Node, + std::string RequestedName) + : Node(Node), RequestedName(std::move(RequestedName)) {} + + llvm::ErrorOr status() override { + return Node.getStatus(RequestedName); + } + + llvm::ErrorOr> + getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator, + bool IsVolatile) override { + llvm::MemoryBuffer *Buf = Node.getBuffer(); + return llvm::MemoryBuffer::getMemBuffer( + Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator); + } + + std::error_code close() override { return {}; } +}; +} // namespace + +class InMemoryDirectory : public InMemoryNode { + Status Stat; + llvm::StringMap> Entries; + +public: + InMemoryDirectory(Status Stat) + : InMemoryNode(Stat.getName(), IME_Directory), Stat(std::move(Stat)) {} + + /// Return the \p Status for this node. \p RequestedName should be the name + /// through which the caller referred to this node. It will override + /// \p Status::Name in the return value, to mimic the behavior of \p RealFile. + Status getStatus(StringRef RequestedName) const { + return Status::copyWithNewName(Stat, RequestedName); + } + InMemoryNode *getChild(StringRef Name) { + auto I = Entries.find(Name); + if (I != Entries.end()) + return I->second.get(); + return nullptr; + } + + InMemoryNode *addChild(StringRef Name, std::unique_ptr Child) { + return Entries.insert(make_pair(Name, std::move(Child))) + .first->second.get(); + } + + using const_iterator = decltype(Entries)::const_iterator; + + const_iterator begin() const { return Entries.begin(); } + const_iterator end() const { return Entries.end(); } + + std::string toString(unsigned Indent) const override { + std::string Result = + (std::string(Indent, ' ') + Stat.getName() + "\n").str(); + for (const auto &Entry : Entries) + Result += Entry.second->toString(Indent + 2); + return Result; + } + + static bool classof(const InMemoryNode *N) { + return N->getKind() == IME_Directory; + } +}; + +namespace { +Status getNodeStatus(const InMemoryNode *Node, StringRef RequestedName) { + if (auto Dir = dyn_cast(Node)) + return Dir->getStatus(RequestedName); + if (auto File = dyn_cast(Node)) + return File->getStatus(RequestedName); + if (auto Link = dyn_cast(Node)) + return Link->getResolvedFile().getStatus(RequestedName); + llvm_unreachable("Unknown node type"); +} +} // namespace +} // namespace detail + +InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths) + : Root(new detail::InMemoryDirectory( + Status("", getNextVirtualUniqueID(), llvm::sys::TimePoint<>(), 0, 0, + 0, llvm::sys::fs::file_type::directory_file, + llvm::sys::fs::perms::all_all))), + UseNormalizedPaths(UseNormalizedPaths) {} + +InMemoryFileSystem::~InMemoryFileSystem() = default; + +std::string InMemoryFileSystem::toString() const { + return Root->toString(/*Indent=*/0); +} + +bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime, + std::unique_ptr Buffer, + Optional User, + Optional Group, + Optional Type, + Optional Perms, + const detail::InMemoryFile *HardLinkTarget) { + SmallString<128> Path; + P.toVector(Path); + + // Fix up relative paths. This just prepends the current working directory. + std::error_code EC = makeAbsolute(Path); + assert(!EC); + (void)EC; + + if (useNormalizedPaths()) + llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true); + + if (Path.empty()) + return false; + + detail::InMemoryDirectory *Dir = Root.get(); + auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path); + const auto ResolvedUser = User.getValueOr(0); + const auto ResolvedGroup = Group.getValueOr(0); + const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file); + const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all); + assert(!(HardLinkTarget && Buffer) && "HardLink cannot have a buffer"); + // Any intermediate directories we create should be accessible by + // the owner, even if Perms says otherwise for the final path. + const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all; + while (true) { + StringRef Name = *I; + detail::InMemoryNode *Node = Dir->getChild(Name); + ++I; + if (!Node) { + if (I == E) { + // End of the path. + std::unique_ptr Child; + if (HardLinkTarget) + Child.reset(new detail::InMemoryHardLink(P.str(), *HardLinkTarget)); + else { + // Create a new file or directory. + Status Stat(P.str(), getNextVirtualUniqueID(), + llvm::sys::toTimePoint(ModificationTime), ResolvedUser, + ResolvedGroup, Buffer->getBufferSize(), ResolvedType, + ResolvedPerms); + if (ResolvedType == sys::fs::file_type::directory_file) { + Child.reset(new detail::InMemoryDirectory(std::move(Stat))); + } else { + Child.reset( + new detail::InMemoryFile(std::move(Stat), std::move(Buffer))); + } + } + Dir->addChild(Name, std::move(Child)); + return true; + } + + // Create a new directory. Use the path up to here. + Status Stat( + StringRef(Path.str().begin(), Name.end() - Path.str().begin()), + getNextVirtualUniqueID(), llvm::sys::toTimePoint(ModificationTime), + ResolvedUser, ResolvedGroup, 0, sys::fs::file_type::directory_file, + NewDirectoryPerms); + Dir = cast(Dir->addChild( + Name, llvm::make_unique(std::move(Stat)))); + continue; + } + + if (auto *NewDir = dyn_cast(Node)) { + Dir = NewDir; + } else { + assert((isa(Node) || + isa(Node)) && + "Must be either file, hardlink or directory!"); + + // Trying to insert a directory in place of a file. + if (I != E) + return false; + + // Return false only if the new file is different from the existing one. + if (auto Link = dyn_cast(Node)) { + return Link->getResolvedFile().getBuffer()->getBuffer() == + Buffer->getBuffer(); + } + return cast(Node)->getBuffer()->getBuffer() == + Buffer->getBuffer(); + } + } +} + +bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime, + std::unique_ptr Buffer, + Optional User, + Optional Group, + Optional Type, + Optional Perms) { + return addFile(P, ModificationTime, std::move(Buffer), User, Group, Type, + Perms, /*HardLinkTarget=*/nullptr); +} + +bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime, + llvm::MemoryBuffer *Buffer, + Optional User, + Optional Group, + Optional Type, + Optional Perms) { + return addFile(P, ModificationTime, + llvm::MemoryBuffer::getMemBuffer( + Buffer->getBuffer(), Buffer->getBufferIdentifier()), + std::move(User), std::move(Group), std::move(Type), + std::move(Perms)); +} + +static ErrorOr +lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir, + const Twine &P) { + SmallString<128> Path; + P.toVector(Path); + + // Fix up relative paths. This just prepends the current working directory. + std::error_code EC = FS.makeAbsolute(Path); + assert(!EC); + (void)EC; + + if (FS.useNormalizedPaths()) + llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true); + + if (Path.empty()) + return Dir; + + auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path); + while (true) { + detail::InMemoryNode *Node = Dir->getChild(*I); + ++I; + if (!Node) + return errc::no_such_file_or_directory; + + // Return the file if it's at the end of the path. + if (auto File = dyn_cast(Node)) { + if (I == E) + return File; + return errc::no_such_file_or_directory; + } + + // If Node is HardLink then return the resolved file. + if (auto File = dyn_cast(Node)) { + if (I == E) + return &File->getResolvedFile(); + return errc::no_such_file_or_directory; + } + // Traverse directories. + Dir = cast(Node); + if (I == E) + return Dir; + } +} + +bool InMemoryFileSystem::addHardLink(const Twine &FromPath, + const Twine &ToPath) { + auto FromNode = lookupInMemoryNode(*this, Root.get(), FromPath); + auto ToNode = lookupInMemoryNode(*this, Root.get(), ToPath); + // FromPath must not have been added before. ToPath must have been added + // before. Resolved ToPath must be a File. + if (!ToNode || FromNode || !isa(*ToNode)) + return false; + return this->addFile(FromPath, 0, nullptr, None, None, None, None, + cast(*ToNode)); +} + +llvm::ErrorOr InMemoryFileSystem::status(const Twine &Path) { + auto Node = lookupInMemoryNode(*this, Root.get(), Path); + if (Node) + return detail::getNodeStatus(*Node, Path.str()); + return Node.getError(); +} + +llvm::ErrorOr> +InMemoryFileSystem::openFileForRead(const Twine &Path) { + auto Node = lookupInMemoryNode(*this, Root.get(), Path); + if (!Node) + return Node.getError(); + + // When we have a file provide a heap-allocated wrapper for the memory buffer + // to match the ownership semantics for File. + if (auto *F = dyn_cast(*Node)) + return std::unique_ptr( + new detail::InMemoryFileAdaptor(*F, Path.str())); + + // FIXME: errc::not_a_file? + return make_error_code(llvm::errc::invalid_argument); +} + +namespace { + +/// Adaptor from InMemoryDir::iterator to directory_iterator. +class InMemoryDirIterator : public llvm::vfs::detail::DirIterImpl { + detail::InMemoryDirectory::const_iterator I; + detail::InMemoryDirectory::const_iterator E; + std::string RequestedDirName; + + void setCurrentEntry() { + if (I != E) { + SmallString<256> Path(RequestedDirName); + llvm::sys::path::append(Path, I->second->getFileName()); + sys::fs::file_type Type; + switch (I->second->getKind()) { + case detail::IME_File: + case detail::IME_HardLink: + Type = sys::fs::file_type::regular_file; + break; + case detail::IME_Directory: + Type = sys::fs::file_type::directory_file; + break; + } + CurrentEntry = directory_entry(Path.str(), Type); + } else { + // When we're at the end, make CurrentEntry invalid and DirIterImpl will + // do the rest. + CurrentEntry = directory_entry(); + } + } + +public: + InMemoryDirIterator() = default; + + explicit InMemoryDirIterator(const detail::InMemoryDirectory &Dir, + std::string RequestedDirName) + : I(Dir.begin()), E(Dir.end()), + RequestedDirName(std::move(RequestedDirName)) { + setCurrentEntry(); + } + + std::error_code increment() override { + ++I; + setCurrentEntry(); + return {}; + } +}; + +} // namespace + +directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir, + std::error_code &EC) { + auto Node = lookupInMemoryNode(*this, Root.get(), Dir); + if (!Node) { + EC = Node.getError(); + return directory_iterator(std::make_shared()); + } + + if (auto *DirNode = dyn_cast(*Node)) + return directory_iterator( + std::make_shared(*DirNode, Dir.str())); + + EC = make_error_code(llvm::errc::not_a_directory); + return directory_iterator(std::make_shared()); +} + +std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) { + SmallString<128> Path; + P.toVector(Path); + + // Fix up relative paths. This just prepends the current working directory. + std::error_code EC = makeAbsolute(Path); + assert(!EC); + (void)EC; + + if (useNormalizedPaths()) + llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true); + + if (!Path.empty()) + WorkingDirectory = Path.str(); + return {}; +} + +std::error_code +InMemoryFileSystem::getRealPath(const Twine &Path, + SmallVectorImpl &Output) const { + auto CWD = getCurrentWorkingDirectory(); + if (!CWD || CWD->empty()) + return errc::operation_not_permitted; + Path.toVector(Output); + if (auto EC = makeAbsolute(Output)) + return EC; + llvm::sys::path::remove_dots(Output, /*remove_dot_dot=*/true); + return {}; +} + +} // namespace vfs +} // namespace llvm + +//===-----------------------------------------------------------------------===/ +// RedirectingFileSystem implementation +//===-----------------------------------------------------------------------===/ + +namespace { + +enum EntryKind { EK_Directory, EK_File }; + +/// A single file or directory in the VFS. +class Entry { + EntryKind Kind; + std::string Name; + +public: + Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {} + virtual ~Entry() = default; + + StringRef getName() const { return Name; } + EntryKind getKind() const { return Kind; } +}; + +class RedirectingDirectoryEntry : public Entry { + std::vector> Contents; + Status S; + +public: + RedirectingDirectoryEntry(StringRef Name, + std::vector> Contents, + Status S) + : Entry(EK_Directory, Name), Contents(std::move(Contents)), + S(std::move(S)) {} + RedirectingDirectoryEntry(StringRef Name, Status S) + : Entry(EK_Directory, Name), S(std::move(S)) {} + + Status getStatus() { return S; } + + void addContent(std::unique_ptr Content) { + Contents.push_back(std::move(Content)); + } + + Entry *getLastContent() const { return Contents.back().get(); } + + using iterator = decltype(Contents)::iterator; + + iterator contents_begin() { return Contents.begin(); } + iterator contents_end() { return Contents.end(); } + + static bool classof(const Entry *E) { return E->getKind() == EK_Directory; } +}; + +class RedirectingFileEntry : public Entry { +public: + enum NameKind { NK_NotSet, NK_External, NK_Virtual }; + +private: + std::string ExternalContentsPath; + NameKind UseName; + +public: + RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath, + NameKind UseName) + : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath), + UseName(UseName) {} + + StringRef getExternalContentsPath() const { return ExternalContentsPath; } + + /// whether to use the external path as the name for this file. + bool useExternalName(bool GlobalUseExternalName) const { + return UseName == NK_NotSet ? GlobalUseExternalName + : (UseName == NK_External); + } + + NameKind getUseName() const { return UseName; } + + static bool classof(const Entry *E) { return E->getKind() == EK_File; } +}; + +class VFSFromYamlDirIterImpl : public llvm::vfs::detail::DirIterImpl { + std::string Dir; + RedirectingDirectoryEntry::iterator Current, End; + + std::error_code incrementImpl(); + +public: + VFSFromYamlDirIterImpl(const Twine &Path, + RedirectingDirectoryEntry::iterator Begin, + RedirectingDirectoryEntry::iterator End, + std::error_code &EC); + + std::error_code increment() override; +}; + +/// A virtual file system parsed from a YAML file. +/// +/// Currently, this class allows creating virtual directories and mapping +/// virtual file paths to existing external files, available in \c ExternalFS. +/// +/// The basic structure of the parsed file is: +/// \verbatim +/// { +/// 'version': , +/// +/// 'roots': [ +/// +/// ] +/// } +/// \endverbatim +/// +/// All configuration options are optional. +/// 'case-sensitive': +/// 'use-external-names': +/// 'overlay-relative': +/// 'ignore-non-existent-contents': +/// +/// Virtual directories are represented as +/// \verbatim +/// { +/// 'type': 'directory', +/// 'name': , +/// 'contents': [ ] +/// } +/// \endverbatim +/// +/// The default attributes for virtual directories are: +/// \verbatim +/// MTime = now() when created +/// Perms = 0777 +/// User = Group = 0 +/// Size = 0 +/// UniqueID = unspecified unique value +/// \endverbatim +/// +/// Re-mapped files are represented as +/// \verbatim +/// { +/// 'type': 'file', +/// 'name': , +/// 'use-external-name': # Optional +/// 'external-contents': +/// } +/// \endverbatim +/// +/// and inherit their attributes from the external contents. +/// +/// In both cases, the 'name' field may contain multiple path components (e.g. +/// /path/to/file). However, any directory that contains more than one child +/// must be uniquely represented by a directory entry. +class RedirectingFileSystem : public vfs::FileSystem { + friend class RedirectingFileSystemParser; + + /// The root(s) of the virtual file system. + std::vector> Roots; + + /// The file system to use for external references. + IntrusiveRefCntPtr ExternalFS; + + /// If IsRelativeOverlay is set, this represents the directory + /// path that should be prefixed to each 'external-contents' entry + /// when reading from YAML files. + std::string ExternalContentsPrefixDir; + + /// @name Configuration + /// @{ + + /// Whether to perform case-sensitive comparisons. + /// + /// Currently, case-insensitive matching only works correctly with ASCII. + bool CaseSensitive = true; + + /// IsRelativeOverlay marks whether a ExternalContentsPrefixDir path must + /// be prefixed in every 'external-contents' when reading from YAML files. + bool IsRelativeOverlay = false; + + /// Whether to use to use the value of 'external-contents' for the + /// names of files. This global value is overridable on a per-file basis. + bool UseExternalNames = true; + + /// Whether an invalid path obtained via 'external-contents' should + /// cause iteration on the VFS to stop. If 'true', the VFS should ignore + /// the entry and continue with the next. Allows YAML files to be shared + /// across multiple compiler invocations regardless of prior existent + /// paths in 'external-contents'. This global value is overridable on a + /// per-file basis. + bool IgnoreNonExistentContents = true; + /// @} + + /// Virtual file paths and external files could be canonicalized without "..", + /// "." and "./" in their paths. FIXME: some unittests currently fail on + /// win32 when using remove_dots and remove_leading_dotslash on paths. + bool UseCanonicalizedPaths = +#ifdef _WIN32 + false; +#else + true; +#endif + +private: + RedirectingFileSystem(IntrusiveRefCntPtr ExternalFS) + : ExternalFS(std::move(ExternalFS)) {} + + /// Looks up the path [Start, End) in \p From, possibly + /// recursing into the contents of \p From if it is a directory. + ErrorOr lookupPath(sys::path::const_iterator Start, + sys::path::const_iterator End, Entry *From); + + /// Get the status of a given an \c Entry. + ErrorOr status(const Twine &Path, Entry *E); + +public: + /// Looks up \p Path in \c Roots. + ErrorOr lookupPath(const Twine &Path); + + /// Parses \p Buffer, which is expected to be in YAML format and + /// returns a virtual file system representing its contents. + static RedirectingFileSystem * + create(std::unique_ptr Buffer, + SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath, + void *DiagContext, IntrusiveRefCntPtr ExternalFS); + + ErrorOr status(const Twine &Path) override; + ErrorOr> openFileForRead(const Twine &Path) override; + + llvm::ErrorOr getCurrentWorkingDirectory() const override { + return ExternalFS->getCurrentWorkingDirectory(); + } + + std::error_code setCurrentWorkingDirectory(const Twine &Path) override { + return ExternalFS->setCurrentWorkingDirectory(Path); + } + + directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override { + ErrorOr E = lookupPath(Dir); + if (!E) { + EC = E.getError(); + return {}; + } + ErrorOr S = status(Dir, *E); + if (!S) { + EC = S.getError(); + return {}; + } + if (!S->isDirectory()) { + EC = std::error_code(static_cast(errc::not_a_directory), + std::system_category()); + return {}; + } + + auto *D = cast(*E); + return directory_iterator(std::make_shared( + Dir, D->contents_begin(), D->contents_end(), EC)); + } + + void setExternalContentsPrefixDir(StringRef PrefixDir) { + ExternalContentsPrefixDir = PrefixDir.str(); + } + + StringRef getExternalContentsPrefixDir() const { + return ExternalContentsPrefixDir; + } + + bool ignoreNonExistentContents() const { return IgnoreNonExistentContents; } + +#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) + LLVM_DUMP_METHOD void dump() const { + for (const auto &Root : Roots) + dumpEntry(Root.get()); + } + + LLVM_DUMP_METHOD void dumpEntry(Entry *E, int NumSpaces = 0) const { + StringRef Name = E->getName(); + for (int i = 0, e = NumSpaces; i < e; ++i) + dbgs() << " "; + dbgs() << "'" << Name.str().c_str() << "'" + << "\n"; + + if (E->getKind() == EK_Directory) { + auto *DE = dyn_cast(E); + assert(DE && "Should be a directory"); + + for (std::unique_ptr &SubEntry : + llvm::make_range(DE->contents_begin(), DE->contents_end())) + dumpEntry(SubEntry.get(), NumSpaces + 2); + } + } +#endif +}; + +/// A helper class to hold the common YAML parsing state. +class RedirectingFileSystemParser { + yaml::Stream &Stream; + + void error(yaml::Node *N, const Twine &Msg) { Stream.printError(N, Msg); } + + // false on error + bool parseScalarString(yaml::Node *N, StringRef &Result, + SmallVectorImpl &Storage) { + const auto *S = dyn_cast(N); + + if (!S) { + error(N, "expected string"); + return false; + } + Result = S->getValue(Storage); + return true; + } + + // false on error + bool parseScalarBool(yaml::Node *N, bool &Result) { + SmallString<5> Storage; + StringRef Value; + if (!parseScalarString(N, Value, Storage)) + return false; + + if (Value.equals_lower("true") || Value.equals_lower("on") || + Value.equals_lower("yes") || Value == "1") { + Result = true; + return true; + } else if (Value.equals_lower("false") || Value.equals_lower("off") || + Value.equals_lower("no") || Value == "0") { + Result = false; + return true; + } + + error(N, "expected boolean value"); + return false; + } + + struct KeyStatus { + bool Required; + bool Seen = false; + + KeyStatus(bool Required = false) : Required(Required) {} + }; + + using KeyStatusPair = std::pair; + + // false on error + bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key, + DenseMap &Keys) { + if (!Keys.count(Key)) { + error(KeyNode, "unknown key"); + return false; + } + KeyStatus &S = Keys[Key]; + if (S.Seen) { + error(KeyNode, Twine("duplicate key '") + Key + "'"); + return false; + } + S.Seen = true; + return true; + } + + // false on error + bool checkMissingKeys(yaml::Node *Obj, DenseMap &Keys) { + for (const auto &I : Keys) { + if (I.second.Required && !I.second.Seen) { + error(Obj, Twine("missing key '") + I.first + "'"); + return false; + } + } + return true; + } + + Entry *lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name, + Entry *ParentEntry = nullptr) { + if (!ParentEntry) { // Look for a existent root + for (const auto &Root : FS->Roots) { + if (Name.equals(Root->getName())) { + ParentEntry = Root.get(); + return ParentEntry; + } + } + } else { // Advance to the next component + auto *DE = dyn_cast(ParentEntry); + for (std::unique_ptr &Content : + llvm::make_range(DE->contents_begin(), DE->contents_end())) { + auto *DirContent = dyn_cast(Content.get()); + if (DirContent && Name.equals(Content->getName())) + return DirContent; + } + } + + // ... or create a new one + std::unique_ptr E = llvm::make_unique( + Name, + Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(), + 0, 0, 0, file_type::directory_file, sys::fs::all_all)); + + if (!ParentEntry) { // Add a new root to the overlay + FS->Roots.push_back(std::move(E)); + ParentEntry = FS->Roots.back().get(); + return ParentEntry; + } + + auto *DE = dyn_cast(ParentEntry); + DE->addContent(std::move(E)); + return DE->getLastContent(); + } + + void uniqueOverlayTree(RedirectingFileSystem *FS, Entry *SrcE, + Entry *NewParentE = nullptr) { + StringRef Name = SrcE->getName(); + switch (SrcE->getKind()) { + case EK_Directory: { + auto *DE = dyn_cast(SrcE); + assert(DE && "Must be a directory"); + // Empty directories could be present in the YAML as a way to + // describe a file for a current directory after some of its subdir + // is parsed. This only leads to redundant walks, ignore it. + if (!Name.empty()) + NewParentE = lookupOrCreateEntry(FS, Name, NewParentE); + for (std::unique_ptr &SubEntry : + llvm::make_range(DE->contents_begin(), DE->contents_end())) + uniqueOverlayTree(FS, SubEntry.get(), NewParentE); + break; + } + case EK_File: { + auto *FE = dyn_cast(SrcE); + assert(FE && "Must be a file"); + assert(NewParentE && "Parent entry must exist"); + auto *DE = dyn_cast(NewParentE); + DE->addContent(llvm::make_unique( + Name, FE->getExternalContentsPath(), FE->getUseName())); + break; + } + } + } + + std::unique_ptr parseEntry(yaml::Node *N, RedirectingFileSystem *FS, + bool IsRootEntry) { + auto *M = dyn_cast(N); + if (!M) { + error(N, "expected mapping node for file or directory entry"); + return nullptr; + } + + KeyStatusPair Fields[] = { + KeyStatusPair("name", true), + KeyStatusPair("type", true), + KeyStatusPair("contents", false), + KeyStatusPair("external-contents", false), + KeyStatusPair("use-external-name", false), + }; + + DenseMap Keys(std::begin(Fields), std::end(Fields)); + + bool HasContents = false; // external or otherwise + std::vector> EntryArrayContents; + std::string ExternalContentsPath; + std::string Name; + yaml::Node *NameValueNode; + auto UseExternalName = RedirectingFileEntry::NK_NotSet; + EntryKind Kind; + + for (auto &I : *M) { + StringRef Key; + // Reuse the buffer for key and value, since we don't look at key after + // parsing value. + SmallString<256> Buffer; + if (!parseScalarString(I.getKey(), Key, Buffer)) + return nullptr; + + if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys)) + return nullptr; + + StringRef Value; + if (Key == "name") { + if (!parseScalarString(I.getValue(), Value, Buffer)) + return nullptr; + + NameValueNode = I.getValue(); + if (FS->UseCanonicalizedPaths) { + SmallString<256> Path(Value); + // Guarantee that old YAML files containing paths with ".." and "." + // are properly canonicalized before read into the VFS. + Path = sys::path::remove_leading_dotslash(Path); + sys::path::remove_dots(Path, /*remove_dot_dot=*/true); + Name = Path.str(); + } else { + Name = Value; + } + } else if (Key == "type") { + if (!parseScalarString(I.getValue(), Value, Buffer)) + return nullptr; + if (Value == "file") + Kind = EK_File; + else if (Value == "directory") + Kind = EK_Directory; + else { + error(I.getValue(), "unknown value for 'type'"); + return nullptr; + } + } else if (Key == "contents") { + if (HasContents) { + error(I.getKey(), + "entry already has 'contents' or 'external-contents'"); + return nullptr; + } + HasContents = true; + auto *Contents = dyn_cast(I.getValue()); + if (!Contents) { + // FIXME: this is only for directories, what about files? + error(I.getValue(), "expected array"); + return nullptr; + } + + for (auto &I : *Contents) { + if (std::unique_ptr E = + parseEntry(&I, FS, /*IsRootEntry*/ false)) + EntryArrayContents.push_back(std::move(E)); + else + return nullptr; + } + } else if (Key == "external-contents") { + if (HasContents) { + error(I.getKey(), + "entry already has 'contents' or 'external-contents'"); + return nullptr; + } + HasContents = true; + if (!parseScalarString(I.getValue(), Value, Buffer)) + return nullptr; + + SmallString<256> FullPath; + if (FS->IsRelativeOverlay) { + FullPath = FS->getExternalContentsPrefixDir(); + assert(!FullPath.empty() && + "External contents prefix directory must exist"); + llvm::sys::path::append(FullPath, Value); + } else { + FullPath = Value; + } + + if (FS->UseCanonicalizedPaths) { + // Guarantee that old YAML files containing paths with ".." and "." + // are properly canonicalized before read into the VFS. + FullPath = sys::path::remove_leading_dotslash(FullPath); + sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true); + } + ExternalContentsPath = FullPath.str(); + } else if (Key == "use-external-name") { + bool Val; + if (!parseScalarBool(I.getValue(), Val)) + return nullptr; + UseExternalName = Val ? RedirectingFileEntry::NK_External + : RedirectingFileEntry::NK_Virtual; + } else { + llvm_unreachable("key missing from Keys"); + } + } + + if (Stream.failed()) + return nullptr; + + // check for missing keys + if (!HasContents) { + error(N, "missing key 'contents' or 'external-contents'"); + return nullptr; + } + if (!checkMissingKeys(N, Keys)) + return nullptr; + + // check invalid configuration + if (Kind == EK_Directory && + UseExternalName != RedirectingFileEntry::NK_NotSet) { + error(N, "'use-external-name' is not supported for directories"); + return nullptr; + } + + if (IsRootEntry && !sys::path::is_absolute(Name)) { + assert(NameValueNode && "Name presence should be checked earlier"); + error(NameValueNode, + "entry with relative path at the root level is not discoverable"); + return nullptr; + } + + // Remove trailing slash(es), being careful not to remove the root path + StringRef Trimmed(Name); + size_t RootPathLen = sys::path::root_path(Trimmed).size(); + while (Trimmed.size() > RootPathLen && + sys::path::is_separator(Trimmed.back())) + Trimmed = Trimmed.slice(0, Trimmed.size() - 1); + // Get the last component + StringRef LastComponent = sys::path::filename(Trimmed); + + std::unique_ptr Result; + switch (Kind) { + case EK_File: + Result = llvm::make_unique( + LastComponent, std::move(ExternalContentsPath), UseExternalName); + break; + case EK_Directory: + Result = llvm::make_unique( + LastComponent, std::move(EntryArrayContents), + Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(), + 0, 0, 0, file_type::directory_file, sys::fs::all_all)); + break; + } + + StringRef Parent = sys::path::parent_path(Trimmed); + if (Parent.empty()) + return Result; + + // if 'name' contains multiple components, create implicit directory entries + for (sys::path::reverse_iterator I = sys::path::rbegin(Parent), + E = sys::path::rend(Parent); + I != E; ++I) { + std::vector> Entries; + Entries.push_back(std::move(Result)); + Result = llvm::make_unique( + *I, std::move(Entries), + Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(), + 0, 0, 0, file_type::directory_file, sys::fs::all_all)); + } + return Result; + } + +public: + RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {} + + // false on error + bool parse(yaml::Node *Root, RedirectingFileSystem *FS) { + auto *Top = dyn_cast(Root); + if (!Top) { + error(Root, "expected mapping node"); + return false; + } + + KeyStatusPair Fields[] = { + KeyStatusPair("version", true), + KeyStatusPair("case-sensitive", false), + KeyStatusPair("use-external-names", false), + KeyStatusPair("overlay-relative", false), + KeyStatusPair("ignore-non-existent-contents", false), + KeyStatusPair("roots", true), + }; + + DenseMap Keys(std::begin(Fields), std::end(Fields)); + std::vector> RootEntries; + + // Parse configuration and 'roots' + for (auto &I : *Top) { + SmallString<10> KeyBuffer; + StringRef Key; + if (!parseScalarString(I.getKey(), Key, KeyBuffer)) + return false; + + if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys)) + return false; + + if (Key == "roots") { + auto *Roots = dyn_cast(I.getValue()); + if (!Roots) { + error(I.getValue(), "expected array"); + return false; + } + + for (auto &I : *Roots) { + if (std::unique_ptr E = + parseEntry(&I, FS, /*IsRootEntry*/ true)) + RootEntries.push_back(std::move(E)); + else + return false; + } + } else if (Key == "version") { + StringRef VersionString; + SmallString<4> Storage; + if (!parseScalarString(I.getValue(), VersionString, Storage)) + return false; + int Version; + if (VersionString.getAsInteger(10, Version)) { + error(I.getValue(), "expected integer"); + return false; + } + if (Version < 0) { + error(I.getValue(), "invalid version number"); + return false; + } + if (Version != 0) { + error(I.getValue(), "version mismatch, expected 0"); + return false; + } + } else if (Key == "case-sensitive") { + if (!parseScalarBool(I.getValue(), FS->CaseSensitive)) + return false; + } else if (Key == "overlay-relative") { + if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay)) + return false; + } else if (Key == "use-external-names") { + if (!parseScalarBool(I.getValue(), FS->UseExternalNames)) + return false; + } else if (Key == "ignore-non-existent-contents") { + if (!parseScalarBool(I.getValue(), FS->IgnoreNonExistentContents)) + return false; + } else { + llvm_unreachable("key missing from Keys"); + } + } + + if (Stream.failed()) + return false; + + if (!checkMissingKeys(Top, Keys)) + return false; + + // Now that we sucessefully parsed the YAML file, canonicalize the internal + // representation to a proper directory tree so that we can search faster + // inside the VFS. + for (auto &E : RootEntries) + uniqueOverlayTree(FS, E.get()); + + return true; + } +}; + +} // namespace + +RedirectingFileSystem * +RedirectingFileSystem::create(std::unique_ptr Buffer, + SourceMgr::DiagHandlerTy DiagHandler, + StringRef YAMLFilePath, void *DiagContext, + IntrusiveRefCntPtr ExternalFS) { + SourceMgr SM; + yaml::Stream Stream(Buffer->getMemBufferRef(), SM); + + SM.setDiagHandler(DiagHandler, DiagContext); + yaml::document_iterator DI = Stream.begin(); + yaml::Node *Root = DI->getRoot(); + if (DI == Stream.end() || !Root) { + SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node"); + return nullptr; + } + + RedirectingFileSystemParser P(Stream); + + std::unique_ptr FS( + new RedirectingFileSystem(std::move(ExternalFS))); + + if (!YAMLFilePath.empty()) { + // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed + // to each 'external-contents' path. + // + // Example: + // -ivfsoverlay dummy.cache/vfs/vfs.yaml + // yields: + // FS->ExternalContentsPrefixDir => //dummy.cache/vfs + // + SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath); + std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir); + assert(!EC && "Overlay dir final path must be absolute"); + (void)EC; + FS->setExternalContentsPrefixDir(OverlayAbsDir); + } + + if (!P.parse(Root, FS.get())) + return nullptr; + + return FS.release(); +} + +ErrorOr RedirectingFileSystem::lookupPath(const Twine &Path_) { + SmallString<256> Path; + Path_.toVector(Path); + + // Handle relative paths + if (std::error_code EC = makeAbsolute(Path)) + return EC; + + // Canonicalize path by removing ".", "..", "./", etc components. This is + // a VFS request, do bot bother about symlinks in the path components + // but canonicalize in order to perform the correct entry search. + if (UseCanonicalizedPaths) { + Path = sys::path::remove_leading_dotslash(Path); + sys::path::remove_dots(Path, /*remove_dot_dot=*/true); + } + + if (Path.empty()) + return make_error_code(llvm::errc::invalid_argument); + + sys::path::const_iterator Start = sys::path::begin(Path); + sys::path::const_iterator End = sys::path::end(Path); + for (const auto &Root : Roots) { + ErrorOr Result = lookupPath(Start, End, Root.get()); + if (Result || Result.getError() != llvm::errc::no_such_file_or_directory) + return Result; + } + return make_error_code(llvm::errc::no_such_file_or_directory); +} + +ErrorOr +RedirectingFileSystem::lookupPath(sys::path::const_iterator Start, + sys::path::const_iterator End, Entry *From) { +#ifndef _WIN32 + assert(!isTraversalComponent(*Start) && + !isTraversalComponent(From->getName()) && + "Paths should not contain traversal components"); +#else + // FIXME: this is here to support windows, remove it once canonicalized + // paths become globally default. + if (Start->equals(".")) + ++Start; +#endif + + StringRef FromName = From->getName(); + + // Forward the search to the next component in case this is an empty one. + if (!FromName.empty()) { + if (CaseSensitive ? !Start->equals(FromName) + : !Start->equals_lower(FromName)) + // failure to match + return make_error_code(llvm::errc::no_such_file_or_directory); + + ++Start; + + if (Start == End) { + // Match! + return From; + } + } + + auto *DE = dyn_cast(From); + if (!DE) + return make_error_code(llvm::errc::not_a_directory); + + for (const std::unique_ptr &DirEntry : + llvm::make_range(DE->contents_begin(), DE->contents_end())) { + ErrorOr Result = lookupPath(Start, End, DirEntry.get()); + if (Result || Result.getError() != llvm::errc::no_such_file_or_directory) + return Result; + } + return make_error_code(llvm::errc::no_such_file_or_directory); +} + +static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames, + Status ExternalStatus) { + Status S = ExternalStatus; + if (!UseExternalNames) + S = Status::copyWithNewName(S, Path.str()); + S.IsVFSMapped = true; + return S; +} + +ErrorOr RedirectingFileSystem::status(const Twine &Path, Entry *E) { + assert(E != nullptr); + if (auto *F = dyn_cast(E)) { + ErrorOr S = ExternalFS->status(F->getExternalContentsPath()); + assert(!S || S->getName() == F->getExternalContentsPath()); + if (S) + return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames), + *S); + return S; + } else { // directory + auto *DE = cast(E); + return Status::copyWithNewName(DE->getStatus(), Path.str()); + } +} + +ErrorOr RedirectingFileSystem::status(const Twine &Path) { + ErrorOr Result = lookupPath(Path); + if (!Result) + return Result.getError(); + return status(Path, *Result); +} + +namespace { + +/// Provide a file wrapper with an overriden status. +class FileWithFixedStatus : public File { + std::unique_ptr InnerFile; + Status S; + +public: + FileWithFixedStatus(std::unique_ptr InnerFile, Status S) + : InnerFile(std::move(InnerFile)), S(std::move(S)) {} + + ErrorOr status() override { return S; } + ErrorOr> + + getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator, + bool IsVolatile) override { + return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator, + IsVolatile); + } + + std::error_code close() override { return InnerFile->close(); } +}; + +} // namespace + +ErrorOr> +RedirectingFileSystem::openFileForRead(const Twine &Path) { + ErrorOr E = lookupPath(Path); + if (!E) + return E.getError(); + + auto *F = dyn_cast(*E); + if (!F) // FIXME: errc::not_a_file? + return make_error_code(llvm::errc::invalid_argument); + + auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath()); + if (!Result) + return Result; + + auto ExternalStatus = (*Result)->status(); + if (!ExternalStatus) + return ExternalStatus.getError(); + + // FIXME: Update the status with the name and VFSMapped. + Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames), + *ExternalStatus); + return std::unique_ptr( + llvm::make_unique(std::move(*Result), S)); +} + +IntrusiveRefCntPtr +vfs::getVFSFromYAML(std::unique_ptr Buffer, + SourceMgr::DiagHandlerTy DiagHandler, + StringRef YAMLFilePath, void *DiagContext, + IntrusiveRefCntPtr ExternalFS) { + return RedirectingFileSystem::create(std::move(Buffer), DiagHandler, + YAMLFilePath, DiagContext, + std::move(ExternalFS)); +} + +static void getVFSEntries(Entry *SrcE, SmallVectorImpl &Path, + SmallVectorImpl &Entries) { + auto Kind = SrcE->getKind(); + if (Kind == EK_Directory) { + auto *DE = dyn_cast(SrcE); + assert(DE && "Must be a directory"); + for (std::unique_ptr &SubEntry : + llvm::make_range(DE->contents_begin(), DE->contents_end())) { + Path.push_back(SubEntry->getName()); + getVFSEntries(SubEntry.get(), Path, Entries); + Path.pop_back(); + } + return; + } + + assert(Kind == EK_File && "Must be a EK_File"); + auto *FE = dyn_cast(SrcE); + assert(FE && "Must be a file"); + SmallString<128> VPath; + for (auto &Comp : Path) + llvm::sys::path::append(VPath, Comp); + Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath())); +} + +void vfs::collectVFSFromYAML(std::unique_ptr Buffer, + SourceMgr::DiagHandlerTy DiagHandler, + StringRef YAMLFilePath, + SmallVectorImpl &CollectedEntries, + void *DiagContext, + IntrusiveRefCntPtr ExternalFS) { + RedirectingFileSystem *VFS = RedirectingFileSystem::create( + std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext, + std::move(ExternalFS)); + ErrorOr RootE = VFS->lookupPath("/"); + if (!RootE) + return; + SmallVector Components; + Components.push_back("/"); + getVFSEntries(*RootE, Components, CollectedEntries); +} + +UniqueID vfs::getNextVirtualUniqueID() { + static std::atomic UID; + unsigned ID = ++UID; + // The following assumes that uint64_t max will never collide with a real + // dev_t value from the OS. + return UniqueID(std::numeric_limits::max(), ID); +} + +void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) { + assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute"); + assert(sys::path::is_absolute(RealPath) && "real path not absolute"); + assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported"); + Mappings.emplace_back(VirtualPath, RealPath); +} + +namespace { + +class JSONWriter { + llvm::raw_ostream &OS; + SmallVector DirStack; + + unsigned getDirIndent() { return 4 * DirStack.size(); } + unsigned getFileIndent() { return 4 * (DirStack.size() + 1); } + bool containedIn(StringRef Parent, StringRef Path); + StringRef containedPart(StringRef Parent, StringRef Path); + void startDirectory(StringRef Path); + void endDirectory(); + void writeEntry(StringRef VPath, StringRef RPath); + +public: + JSONWriter(llvm::raw_ostream &OS) : OS(OS) {} + + void write(ArrayRef Entries, Optional UseExternalNames, + Optional IsCaseSensitive, Optional IsOverlayRelative, + Optional IgnoreNonExistentContents, StringRef OverlayDir); +}; + +} // namespace + +bool JSONWriter::containedIn(StringRef Parent, StringRef Path) { + using namespace llvm::sys; + + // Compare each path component. + auto IParent = path::begin(Parent), EParent = path::end(Parent); + for (auto IChild = path::begin(Path), EChild = path::end(Path); + IParent != EParent && IChild != EChild; ++IParent, ++IChild) { + if (*IParent != *IChild) + return false; + } + // Have we exhausted the parent path? + return IParent == EParent; +} + +StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) { + assert(!Parent.empty()); + assert(containedIn(Parent, Path)); + return Path.slice(Parent.size() + 1, StringRef::npos); +} + +void JSONWriter::startDirectory(StringRef Path) { + StringRef Name = + DirStack.empty() ? Path : containedPart(DirStack.back(), Path); + DirStack.push_back(Path); + unsigned Indent = getDirIndent(); + OS.indent(Indent) << "{\n"; + OS.indent(Indent + 2) << "'type': 'directory',\n"; + OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n"; + OS.indent(Indent + 2) << "'contents': [\n"; +} + +void JSONWriter::endDirectory() { + unsigned Indent = getDirIndent(); + OS.indent(Indent + 2) << "]\n"; + OS.indent(Indent) << "}"; + + DirStack.pop_back(); +} + +void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) { + unsigned Indent = getFileIndent(); + OS.indent(Indent) << "{\n"; + OS.indent(Indent + 2) << "'type': 'file',\n"; + OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n"; + OS.indent(Indent + 2) << "'external-contents': \"" + << llvm::yaml::escape(RPath) << "\"\n"; + OS.indent(Indent) << "}"; +} + +void JSONWriter::write(ArrayRef Entries, + Optional UseExternalNames, + Optional IsCaseSensitive, + Optional IsOverlayRelative, + Optional IgnoreNonExistentContents, + StringRef OverlayDir) { + using namespace llvm::sys; + + OS << "{\n" + " 'version': 0,\n"; + if (IsCaseSensitive.hasValue()) + OS << " 'case-sensitive': '" + << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n"; + if (UseExternalNames.hasValue()) + OS << " 'use-external-names': '" + << (UseExternalNames.getValue() ? "true" : "false") << "',\n"; + bool UseOverlayRelative = false; + if (IsOverlayRelative.hasValue()) { + UseOverlayRelative = IsOverlayRelative.getValue(); + OS << " 'overlay-relative': '" << (UseOverlayRelative ? "true" : "false") + << "',\n"; + } + if (IgnoreNonExistentContents.hasValue()) + OS << " 'ignore-non-existent-contents': '" + << (IgnoreNonExistentContents.getValue() ? "true" : "false") << "',\n"; + OS << " 'roots': [\n"; + + if (!Entries.empty()) { + const YAMLVFSEntry &Entry = Entries.front(); + startDirectory(path::parent_path(Entry.VPath)); + + StringRef RPath = Entry.RPath; + if (UseOverlayRelative) { + unsigned OverlayDirLen = OverlayDir.size(); + assert(RPath.substr(0, OverlayDirLen) == OverlayDir && + "Overlay dir must be contained in RPath"); + RPath = RPath.slice(OverlayDirLen, RPath.size()); + } + + writeEntry(path::filename(Entry.VPath), RPath); + + for (const auto &Entry : Entries.slice(1)) { + StringRef Dir = path::parent_path(Entry.VPath); + if (Dir == DirStack.back()) + OS << ",\n"; + else { + while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) { + OS << "\n"; + endDirectory(); + } + OS << ",\n"; + startDirectory(Dir); + } + StringRef RPath = Entry.RPath; + if (UseOverlayRelative) { + unsigned OverlayDirLen = OverlayDir.size(); + assert(RPath.substr(0, OverlayDirLen) == OverlayDir && + "Overlay dir must be contained in RPath"); + RPath = RPath.slice(OverlayDirLen, RPath.size()); + } + writeEntry(path::filename(Entry.VPath), RPath); + } + + while (!DirStack.empty()) { + OS << "\n"; + endDirectory(); + } + OS << "\n"; + } + + OS << " ]\n" + << "}\n"; +} + +void YAMLVFSWriter::write(llvm::raw_ostream &OS) { + llvm::sort(Mappings, [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) { + return LHS.VPath < RHS.VPath; + }); + + JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive, + IsOverlayRelative, IgnoreNonExistentContents, + OverlayDir); +} + +VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl( + const Twine &_Path, RedirectingDirectoryEntry::iterator Begin, + RedirectingDirectoryEntry::iterator End, std::error_code &EC) + : Dir(_Path.str()), Current(Begin), End(End) { + EC = incrementImpl(); +} + +std::error_code VFSFromYamlDirIterImpl::increment() { + assert(Current != End && "cannot iterate past end"); + ++Current; + return incrementImpl(); +} + +std::error_code VFSFromYamlDirIterImpl::incrementImpl() { + while (Current != End) { + SmallString<128> PathStr(Dir); + llvm::sys::path::append(PathStr, (*Current)->getName()); + sys::fs::file_type Type; + switch ((*Current)->getKind()) { + case EK_Directory: + Type = sys::fs::file_type::directory_file; + break; + case EK_File: + Type = sys::fs::file_type::regular_file; + break; + } + CurrentEntry = directory_entry(PathStr.str(), Type); + break; + } + + if (Current == End) + CurrentEntry = directory_entry(); + return {}; +} + +vfs::recursive_directory_iterator::recursive_directory_iterator( + FileSystem &FS_, const Twine &Path, std::error_code &EC) + : FS(&FS_) { + directory_iterator I = FS->dir_begin(Path, EC); + if (I != directory_iterator()) { + State = std::make_shared(); + State->push(I); + } +} + +vfs::recursive_directory_iterator & +recursive_directory_iterator::increment(std::error_code &EC) { + assert(FS && State && !State->empty() && "incrementing past end"); + assert(!State->top()->path().empty() && "non-canonical end iterator"); + vfs::directory_iterator End; + if (State->top()->type() == sys::fs::file_type::directory_file) { + vfs::directory_iterator I = FS->dir_begin(State->top()->path(), EC); + if (I != End) { + State->push(I); + return *this; + } + } + + while (!State->empty() && State->top().increment(EC) == End) + State->pop(); + + if (State->empty()) + State.reset(); // end iterator + + return *this; +} Index: llvm/trunk/unittests/Support/CMakeLists.txt =================================================================== --- llvm/trunk/unittests/Support/CMakeLists.txt +++ llvm/trunk/unittests/Support/CMakeLists.txt @@ -68,6 +68,7 @@ TrigramIndexTest.cpp UnicodeTest.cpp VersionTupleTest.cpp + VirtualFileSystemTest.cpp YAMLIOTest.cpp YAMLParserTest.cpp formatted_raw_ostream_test.cpp Index: llvm/trunk/unittests/Support/VirtualFileSystemTest.cpp =================================================================== --- llvm/trunk/unittests/Support/VirtualFileSystemTest.cpp +++ llvm/trunk/unittests/Support/VirtualFileSystemTest.cpp @@ -0,0 +1,1601 @@ +//===- unittests/Support/VirtualFileSystem.cpp -------------- VFS tests ---===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "llvm/Support/VirtualFileSystem.h" +#include "llvm/ADT/Triple.h" +#include "llvm/Config/llvm-config.h" +#include "llvm/Support/Errc.h" +#include "llvm/Support/Host.h" +#include "llvm/Support/MemoryBuffer.h" +#include "llvm/Support/Path.h" +#include "llvm/Support/SourceMgr.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include +#include + +using namespace llvm; +using llvm::sys::fs::UniqueID; +using testing::ElementsAre; +using testing::Pair; +using testing::UnorderedElementsAre; + +namespace { +struct DummyFile : public vfs::File { + vfs::Status S; + explicit DummyFile(vfs::Status S) : S(S) {} + llvm::ErrorOr status() override { return S; } + llvm::ErrorOr> + getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator, + bool IsVolatile) override { + llvm_unreachable("unimplemented"); + } + std::error_code close() override { return std::error_code(); } +}; + +class DummyFileSystem : public vfs::FileSystem { + int FSID; // used to produce UniqueIDs + int FileID; // used to produce UniqueIDs + std::map FilesAndDirs; + + static int getNextFSID() { + static int Count = 0; + return Count++; + } + +public: + DummyFileSystem() : FSID(getNextFSID()), FileID(0) {} + + ErrorOr status(const Twine &Path) override { + std::map::iterator I = + FilesAndDirs.find(Path.str()); + if (I == FilesAndDirs.end()) + return make_error_code(llvm::errc::no_such_file_or_directory); + return I->second; + } + ErrorOr> + openFileForRead(const Twine &Path) override { + auto S = status(Path); + if (S) + return std::unique_ptr(new DummyFile{*S}); + return S.getError(); + } + llvm::ErrorOr getCurrentWorkingDirectory() const override { + return std::string(); + } + std::error_code setCurrentWorkingDirectory(const Twine &Path) override { + return std::error_code(); + } + // Map any symlink to "/symlink". + std::error_code getRealPath(const Twine &Path, + SmallVectorImpl &Output) const override { + auto I = FilesAndDirs.find(Path.str()); + if (I == FilesAndDirs.end()) + return make_error_code(llvm::errc::no_such_file_or_directory); + if (I->second.isSymlink()) { + Output.clear(); + Twine("/symlink").toVector(Output); + return std::error_code(); + } + Output.clear(); + Path.toVector(Output); + return std::error_code(); + } + + struct DirIterImpl : public llvm::vfs::detail::DirIterImpl { + std::map &FilesAndDirs; + std::map::iterator I; + std::string Path; + bool isInPath(StringRef S) { + if (Path.size() < S.size() && S.find(Path) == 0) { + auto LastSep = S.find_last_of('/'); + if (LastSep == Path.size() || LastSep == Path.size() - 1) + return true; + } + return false; + } + DirIterImpl(std::map &FilesAndDirs, + const Twine &_Path) + : FilesAndDirs(FilesAndDirs), I(FilesAndDirs.begin()), + Path(_Path.str()) { + for (; I != FilesAndDirs.end(); ++I) { + if (isInPath(I->first)) { + CurrentEntry = + vfs::directory_entry(I->second.getName(), I->second.getType()); + break; + } + } + } + std::error_code increment() override { + ++I; + for (; I != FilesAndDirs.end(); ++I) { + if (isInPath(I->first)) { + CurrentEntry = + vfs::directory_entry(I->second.getName(), I->second.getType()); + break; + } + } + if (I == FilesAndDirs.end()) + CurrentEntry = vfs::directory_entry(); + return std::error_code(); + } + }; + + vfs::directory_iterator dir_begin(const Twine &Dir, + std::error_code &EC) override { + return vfs::directory_iterator( + std::make_shared(FilesAndDirs, Dir)); + } + + void addEntry(StringRef Path, const vfs::Status &Status) { + FilesAndDirs[Path] = Status; + } + + void addRegularFile(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) { + vfs::Status S(Path, UniqueID(FSID, FileID++), + std::chrono::system_clock::now(), 0, 0, 1024, + sys::fs::file_type::regular_file, Perms); + addEntry(Path, S); + } + + void addDirectory(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) { + vfs::Status S(Path, UniqueID(FSID, FileID++), + std::chrono::system_clock::now(), 0, 0, 0, + sys::fs::file_type::directory_file, Perms); + addEntry(Path, S); + } + + void addSymlink(StringRef Path) { + vfs::Status S(Path, UniqueID(FSID, FileID++), + std::chrono::system_clock::now(), 0, 0, 0, + sys::fs::file_type::symlink_file, sys::fs::all_all); + addEntry(Path, S); + } +}; + +/// Replace back-slashes by front-slashes. +std::string getPosixPath(std::string S) { + SmallString<128> Result; + llvm::sys::path::native(S, Result, llvm::sys::path::Style::posix); + return Result.str(); +} +} // end anonymous namespace + +TEST(VirtualFileSystemTest, StatusQueries) { + IntrusiveRefCntPtr D(new DummyFileSystem()); + ErrorOr Status((std::error_code())); + + D->addRegularFile("/foo"); + Status = D->status("/foo"); + ASSERT_FALSE(Status.getError()); + EXPECT_TRUE(Status->isStatusKnown()); + EXPECT_FALSE(Status->isDirectory()); + EXPECT_TRUE(Status->isRegularFile()); + EXPECT_FALSE(Status->isSymlink()); + EXPECT_FALSE(Status->isOther()); + EXPECT_TRUE(Status->exists()); + + D->addDirectory("/bar"); + Status = D->status("/bar"); + ASSERT_FALSE(Status.getError()); + EXPECT_TRUE(Status->isStatusKnown()); + EXPECT_TRUE(Status->isDirectory()); + EXPECT_FALSE(Status->isRegularFile()); + EXPECT_FALSE(Status->isSymlink()); + EXPECT_FALSE(Status->isOther()); + EXPECT_TRUE(Status->exists()); + + D->addSymlink("/baz"); + Status = D->status("/baz"); + ASSERT_FALSE(Status.getError()); + EXPECT_TRUE(Status->isStatusKnown()); + EXPECT_FALSE(Status->isDirectory()); + EXPECT_FALSE(Status->isRegularFile()); + EXPECT_TRUE(Status->isSymlink()); + EXPECT_FALSE(Status->isOther()); + EXPECT_TRUE(Status->exists()); + + EXPECT_TRUE(Status->equivalent(*Status)); + ErrorOr Status2 = D->status("/foo"); + ASSERT_FALSE(Status2.getError()); + EXPECT_FALSE(Status->equivalent(*Status2)); +} + +TEST(VirtualFileSystemTest, BaseOnlyOverlay) { + IntrusiveRefCntPtr D(new DummyFileSystem()); + ErrorOr Status((std::error_code())); + EXPECT_FALSE(Status = D->status("/foo")); + + IntrusiveRefCntPtr O(new vfs::OverlayFileSystem(D)); + EXPECT_FALSE(Status = O->status("/foo")); + + D->addRegularFile("/foo"); + Status = D->status("/foo"); + EXPECT_FALSE(Status.getError()); + + ErrorOr Status2((std::error_code())); + Status2 = O->status("/foo"); + EXPECT_FALSE(Status2.getError()); + EXPECT_TRUE(Status->equivalent(*Status2)); +} + +TEST(VirtualFileSystemTest, GetRealPathInOverlay) { + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + Lower->addRegularFile("/foo"); + Lower->addSymlink("/lower_link"); + IntrusiveRefCntPtr Upper(new DummyFileSystem()); + + IntrusiveRefCntPtr O( + new vfs::OverlayFileSystem(Lower)); + O->pushOverlay(Upper); + + // Regular file. + SmallString<16> RealPath; + EXPECT_FALSE(O->getRealPath("/foo", RealPath)); + EXPECT_EQ(RealPath.str(), "/foo"); + + // Expect no error getting real path for symlink in lower overlay. + EXPECT_FALSE(O->getRealPath("/lower_link", RealPath)); + EXPECT_EQ(RealPath.str(), "/symlink"); + + // Try a non-existing link. + EXPECT_EQ(O->getRealPath("/upper_link", RealPath), + errc::no_such_file_or_directory); + + // Add a new symlink in upper. + Upper->addSymlink("/upper_link"); + EXPECT_FALSE(O->getRealPath("/upper_link", RealPath)); + EXPECT_EQ(RealPath.str(), "/symlink"); +} + +TEST(VirtualFileSystemTest, OverlayFiles) { + IntrusiveRefCntPtr Base(new DummyFileSystem()); + IntrusiveRefCntPtr Middle(new DummyFileSystem()); + IntrusiveRefCntPtr Top(new DummyFileSystem()); + IntrusiveRefCntPtr O( + new vfs::OverlayFileSystem(Base)); + O->pushOverlay(Middle); + O->pushOverlay(Top); + + ErrorOr Status1((std::error_code())), + Status2((std::error_code())), Status3((std::error_code())), + StatusB((std::error_code())), StatusM((std::error_code())), + StatusT((std::error_code())); + + Base->addRegularFile("/foo"); + StatusB = Base->status("/foo"); + ASSERT_FALSE(StatusB.getError()); + Status1 = O->status("/foo"); + ASSERT_FALSE(Status1.getError()); + Middle->addRegularFile("/foo"); + StatusM = Middle->status("/foo"); + ASSERT_FALSE(StatusM.getError()); + Status2 = O->status("/foo"); + ASSERT_FALSE(Status2.getError()); + Top->addRegularFile("/foo"); + StatusT = Top->status("/foo"); + ASSERT_FALSE(StatusT.getError()); + Status3 = O->status("/foo"); + ASSERT_FALSE(Status3.getError()); + + EXPECT_TRUE(Status1->equivalent(*StatusB)); + EXPECT_TRUE(Status2->equivalent(*StatusM)); + EXPECT_TRUE(Status3->equivalent(*StatusT)); + + EXPECT_FALSE(Status1->equivalent(*Status2)); + EXPECT_FALSE(Status2->equivalent(*Status3)); + EXPECT_FALSE(Status1->equivalent(*Status3)); +} + +TEST(VirtualFileSystemTest, OverlayDirsNonMerged) { + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + IntrusiveRefCntPtr Upper(new DummyFileSystem()); + IntrusiveRefCntPtr O( + new vfs::OverlayFileSystem(Lower)); + O->pushOverlay(Upper); + + Lower->addDirectory("/lower-only"); + Upper->addDirectory("/upper-only"); + + // non-merged paths should be the same + ErrorOr Status1 = Lower->status("/lower-only"); + ASSERT_FALSE(Status1.getError()); + ErrorOr Status2 = O->status("/lower-only"); + ASSERT_FALSE(Status2.getError()); + EXPECT_TRUE(Status1->equivalent(*Status2)); + + Status1 = Upper->status("/upper-only"); + ASSERT_FALSE(Status1.getError()); + Status2 = O->status("/upper-only"); + ASSERT_FALSE(Status2.getError()); + EXPECT_TRUE(Status1->equivalent(*Status2)); +} + +TEST(VirtualFileSystemTest, MergedDirPermissions) { + // merged directories get the permissions of the upper dir + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + IntrusiveRefCntPtr Upper(new DummyFileSystem()); + IntrusiveRefCntPtr O( + new vfs::OverlayFileSystem(Lower)); + O->pushOverlay(Upper); + + ErrorOr Status((std::error_code())); + Lower->addDirectory("/both", sys::fs::owner_read); + Upper->addDirectory("/both", sys::fs::owner_all | sys::fs::group_read); + Status = O->status("/both"); + ASSERT_FALSE(Status.getError()); + EXPECT_EQ(0740, Status->getPermissions()); + + // permissions (as usual) are not recursively applied + Lower->addRegularFile("/both/foo", sys::fs::owner_read); + Upper->addRegularFile("/both/bar", sys::fs::owner_write); + Status = O->status("/both/foo"); + ASSERT_FALSE(Status.getError()); + EXPECT_EQ(0400, Status->getPermissions()); + Status = O->status("/both/bar"); + ASSERT_FALSE(Status.getError()); + EXPECT_EQ(0200, Status->getPermissions()); +} + +namespace { +struct ScopedDir { + SmallString<128> Path; + ScopedDir(const Twine &Name, bool Unique = false) { + std::error_code EC; + if (Unique) { + EC = llvm::sys::fs::createUniqueDirectory(Name, Path); + } else { + Path = Name.str(); + EC = llvm::sys::fs::create_directory(Twine(Path)); + } + if (EC) + Path = ""; + EXPECT_FALSE(EC); + } + ~ScopedDir() { + if (Path != "") { + EXPECT_FALSE(llvm::sys::fs::remove(Path.str())); + } + } + operator StringRef() { return Path.str(); } +}; + +struct ScopedLink { + SmallString<128> Path; + ScopedLink(const Twine &To, const Twine &From) { + Path = From.str(); + std::error_code EC = sys::fs::create_link(To, From); + if (EC) + Path = ""; + EXPECT_FALSE(EC); + } + ~ScopedLink() { + if (Path != "") { + EXPECT_FALSE(llvm::sys::fs::remove(Path.str())); + } + } + operator StringRef() { return Path.str(); } +}; +} // end anonymous namespace + +TEST(VirtualFileSystemTest, BasicRealFSIteration) { + ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/ true); + IntrusiveRefCntPtr FS = vfs::getRealFileSystem(); + + std::error_code EC; + vfs::directory_iterator I = FS->dir_begin(Twine(TestDirectory), EC); + ASSERT_FALSE(EC); + EXPECT_EQ(vfs::directory_iterator(), I); // empty directory is empty + + ScopedDir _a(TestDirectory + "/a"); + ScopedDir _ab(TestDirectory + "/a/b"); + ScopedDir _c(TestDirectory + "/c"); + ScopedDir _cd(TestDirectory + "/c/d"); + + I = FS->dir_begin(Twine(TestDirectory), EC); + ASSERT_FALSE(EC); + ASSERT_NE(vfs::directory_iterator(), I); + // Check either a or c, since we can't rely on the iteration order. + EXPECT_TRUE(I->path().endswith("a") || I->path().endswith("c")); + I.increment(EC); + ASSERT_FALSE(EC); + ASSERT_NE(vfs::directory_iterator(), I); + EXPECT_TRUE(I->path().endswith("a") || I->path().endswith("c")); + I.increment(EC); + EXPECT_EQ(vfs::directory_iterator(), I); +} + +#ifdef LLVM_ON_UNIX +TEST(VirtualFileSystemTest, BrokenSymlinkRealFSIteration) { + ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/ true); + IntrusiveRefCntPtr FS = vfs::getRealFileSystem(); + + ScopedLink _a("no_such_file", TestDirectory + "/a"); + ScopedDir _b(TestDirectory + "/b"); + ScopedLink _c("no_such_file", TestDirectory + "/c"); + + // Should get no iteration error, but a stat error for the broken symlinks. + std::map StatResults; + std::error_code EC; + for (vfs::directory_iterator I = FS->dir_begin(Twine(TestDirectory), EC), E; + I != E; I.increment(EC)) { + EXPECT_FALSE(EC); + StatResults[sys::path::filename(I->path())] = + FS->status(I->path()).getError(); + } + EXPECT_THAT( + StatResults, + ElementsAre( + Pair("a", std::make_error_code(std::errc::no_such_file_or_directory)), + Pair("b", std::error_code()), + Pair("c", + std::make_error_code(std::errc::no_such_file_or_directory)))); +} +#endif + +TEST(VirtualFileSystemTest, BasicRealFSRecursiveIteration) { + ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/ true); + IntrusiveRefCntPtr FS = vfs::getRealFileSystem(); + + std::error_code EC; + auto I = vfs::recursive_directory_iterator(*FS, Twine(TestDirectory), EC); + ASSERT_FALSE(EC); + EXPECT_EQ(vfs::recursive_directory_iterator(), I); // empty directory is empty + + ScopedDir _a(TestDirectory + "/a"); + ScopedDir _ab(TestDirectory + "/a/b"); + ScopedDir _c(TestDirectory + "/c"); + ScopedDir _cd(TestDirectory + "/c/d"); + + I = vfs::recursive_directory_iterator(*FS, Twine(TestDirectory), EC); + ASSERT_FALSE(EC); + ASSERT_NE(vfs::recursive_directory_iterator(), I); + + std::vector Contents; + for (auto E = vfs::recursive_directory_iterator(); !EC && I != E; + I.increment(EC)) { + Contents.push_back(I->path()); + } + + // Check contents, which may be in any order + EXPECT_EQ(4U, Contents.size()); + int Counts[4] = {0, 0, 0, 0}; + for (const std::string &Name : Contents) { + ASSERT_FALSE(Name.empty()); + int Index = Name[Name.size() - 1] - 'a'; + ASSERT_TRUE(Index >= 0 && Index < 4); + Counts[Index]++; + } + EXPECT_EQ(1, Counts[0]); // a + EXPECT_EQ(1, Counts[1]); // b + EXPECT_EQ(1, Counts[2]); // c + EXPECT_EQ(1, Counts[3]); // d +} + +#ifdef LLVM_ON_UNIX +TEST(VirtualFileSystemTest, BrokenSymlinkRealFSRecursiveIteration) { + ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/ true); + IntrusiveRefCntPtr FS = vfs::getRealFileSystem(); + + ScopedLink _a("no_such_file", TestDirectory + "/a"); + ScopedDir _b(TestDirectory + "/b"); + ScopedLink _ba("no_such_file", TestDirectory + "/b/a"); + ScopedDir _bb(TestDirectory + "/b/b"); + ScopedLink _bc("no_such_file", TestDirectory + "/b/c"); + ScopedLink _c("no_such_file", TestDirectory + "/c"); + ScopedDir _d(TestDirectory + "/d"); + ScopedDir _dd(TestDirectory + "/d/d"); + ScopedDir _ddd(TestDirectory + "/d/d/d"); + ScopedLink _e("no_such_file", TestDirectory + "/e"); + + std::vector VisitedBrokenSymlinks; + std::vector VisitedNonBrokenSymlinks; + std::error_code EC; + for (vfs::recursive_directory_iterator I(*FS, Twine(TestDirectory), EC), E; + I != E; I.increment(EC)) { + EXPECT_FALSE(EC); + (FS->status(I->path()) ? VisitedNonBrokenSymlinks : VisitedBrokenSymlinks) + .push_back(I->path()); + } + + // Check visited file names. + EXPECT_THAT(VisitedBrokenSymlinks, + UnorderedElementsAre(StringRef(_a), StringRef(_ba), + StringRef(_bc), StringRef(_c), + StringRef(_e))); + EXPECT_THAT(VisitedNonBrokenSymlinks, + UnorderedElementsAre(StringRef(_b), StringRef(_bb), StringRef(_d), + StringRef(_dd), StringRef(_ddd))); +} +#endif + +template +static void checkContents(DirIter I, ArrayRef ExpectedOut) { + std::error_code EC; + SmallVector Expected(ExpectedOut.begin(), ExpectedOut.end()); + SmallVector InputToCheck; + + // Do not rely on iteration order to check for contents, sort both + // content vectors before comparison. + for (DirIter E; !EC && I != E; I.increment(EC)) + InputToCheck.push_back(I->path()); + + llvm::sort(InputToCheck); + llvm::sort(Expected); + EXPECT_EQ(InputToCheck.size(), Expected.size()); + + unsigned LastElt = std::min(InputToCheck.size(), Expected.size()); + for (unsigned Idx = 0; Idx != LastElt; ++Idx) + EXPECT_EQ(StringRef(InputToCheck[Idx]), Expected[Idx]); +} + +TEST(VirtualFileSystemTest, OverlayIteration) { + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + IntrusiveRefCntPtr Upper(new DummyFileSystem()); + IntrusiveRefCntPtr O( + new vfs::OverlayFileSystem(Lower)); + O->pushOverlay(Upper); + + std::error_code EC; + checkContents(O->dir_begin("/", EC), ArrayRef()); + + Lower->addRegularFile("/file1"); + checkContents(O->dir_begin("/", EC), ArrayRef("/file1")); + + Upper->addRegularFile("/file2"); + checkContents(O->dir_begin("/", EC), {"/file2", "/file1"}); + + Lower->addDirectory("/dir1"); + Lower->addRegularFile("/dir1/foo"); + Upper->addDirectory("/dir2"); + Upper->addRegularFile("/dir2/foo"); + checkContents(O->dir_begin("/dir2", EC), ArrayRef("/dir2/foo")); + checkContents(O->dir_begin("/", EC), {"/dir2", "/file2", "/dir1", "/file1"}); +} + +TEST(VirtualFileSystemTest, OverlayRecursiveIteration) { + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + IntrusiveRefCntPtr Middle(new DummyFileSystem()); + IntrusiveRefCntPtr Upper(new DummyFileSystem()); + IntrusiveRefCntPtr O( + new vfs::OverlayFileSystem(Lower)); + O->pushOverlay(Middle); + O->pushOverlay(Upper); + + std::error_code EC; + checkContents(vfs::recursive_directory_iterator(*O, "/", EC), + ArrayRef()); + + Lower->addRegularFile("/file1"); + checkContents(vfs::recursive_directory_iterator(*O, "/", EC), + ArrayRef("/file1")); + + Upper->addDirectory("/dir"); + Upper->addRegularFile("/dir/file2"); + checkContents(vfs::recursive_directory_iterator(*O, "/", EC), + {"/dir", "/dir/file2", "/file1"}); + + Lower->addDirectory("/dir1"); + Lower->addRegularFile("/dir1/foo"); + Lower->addDirectory("/dir1/a"); + Lower->addRegularFile("/dir1/a/b"); + Middle->addDirectory("/a"); + Middle->addDirectory("/a/b"); + Middle->addDirectory("/a/b/c"); + Middle->addRegularFile("/a/b/c/d"); + Middle->addRegularFile("/hiddenByUp"); + Upper->addDirectory("/dir2"); + Upper->addRegularFile("/dir2/foo"); + Upper->addRegularFile("/hiddenByUp"); + checkContents(vfs::recursive_directory_iterator(*O, "/dir2", EC), + ArrayRef("/dir2/foo")); + checkContents(vfs::recursive_directory_iterator(*O, "/", EC), + {"/dir", "/dir/file2", "/dir2", "/dir2/foo", "/hiddenByUp", + "/a", "/a/b", "/a/b/c", "/a/b/c/d", "/dir1", "/dir1/a", + "/dir1/a/b", "/dir1/foo", "/file1"}); +} + +TEST(VirtualFileSystemTest, ThreeLevelIteration) { + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + IntrusiveRefCntPtr Middle(new DummyFileSystem()); + IntrusiveRefCntPtr Upper(new DummyFileSystem()); + IntrusiveRefCntPtr O( + new vfs::OverlayFileSystem(Lower)); + O->pushOverlay(Middle); + O->pushOverlay(Upper); + + std::error_code EC; + checkContents(O->dir_begin("/", EC), ArrayRef()); + + Middle->addRegularFile("/file2"); + checkContents(O->dir_begin("/", EC), ArrayRef("/file2")); + + Lower->addRegularFile("/file1"); + Upper->addRegularFile("/file3"); + checkContents(O->dir_begin("/", EC), {"/file3", "/file2", "/file1"}); +} + +TEST(VirtualFileSystemTest, HiddenInIteration) { + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + IntrusiveRefCntPtr Middle(new DummyFileSystem()); + IntrusiveRefCntPtr Upper(new DummyFileSystem()); + IntrusiveRefCntPtr O( + new vfs::OverlayFileSystem(Lower)); + O->pushOverlay(Middle); + O->pushOverlay(Upper); + + std::error_code EC; + Lower->addRegularFile("/onlyInLow"); + Lower->addDirectory("/hiddenByMid"); + Lower->addDirectory("/hiddenByUp"); + Middle->addRegularFile("/onlyInMid"); + Middle->addRegularFile("/hiddenByMid"); + Middle->addDirectory("/hiddenByUp"); + Upper->addRegularFile("/onlyInUp"); + Upper->addRegularFile("/hiddenByUp"); + checkContents( + O->dir_begin("/", EC), + {"/hiddenByUp", "/onlyInUp", "/hiddenByMid", "/onlyInMid", "/onlyInLow"}); + + // Make sure we get the top-most entry + { + std::error_code EC; + vfs::directory_iterator I = O->dir_begin("/", EC), E; + for (; !EC && I != E; I.increment(EC)) + if (I->path() == "/hiddenByUp") + break; + ASSERT_NE(E, I); + EXPECT_EQ(sys::fs::file_type::regular_file, I->type()); + } + { + std::error_code EC; + vfs::directory_iterator I = O->dir_begin("/", EC), E; + for (; !EC && I != E; I.increment(EC)) + if (I->path() == "/hiddenByMid") + break; + ASSERT_NE(E, I); + EXPECT_EQ(sys::fs::file_type::regular_file, I->type()); + } +} + +class InMemoryFileSystemTest : public ::testing::Test { +protected: + llvm::vfs::InMemoryFileSystem FS; + llvm::vfs::InMemoryFileSystem NormalizedFS; + + InMemoryFileSystemTest() + : FS(/*UseNormalizedPaths=*/false), + NormalizedFS(/*UseNormalizedPaths=*/true) {} +}; + +MATCHER_P2(IsHardLinkTo, FS, Target, "") { + StringRef From = arg; + StringRef To = Target; + auto OpenedFrom = FS->openFileForRead(From); + auto OpenedTo = FS->openFileForRead(To); + return !OpenedFrom.getError() && !OpenedTo.getError() && + (*OpenedFrom)->status()->getUniqueID() == + (*OpenedTo)->status()->getUniqueID(); +} + +TEST_F(InMemoryFileSystemTest, IsEmpty) { + auto Stat = FS.status("/a"); + ASSERT_EQ(Stat.getError(), errc::no_such_file_or_directory) << FS.toString(); + Stat = FS.status("/"); + ASSERT_EQ(Stat.getError(), errc::no_such_file_or_directory) << FS.toString(); +} + +TEST_F(InMemoryFileSystemTest, WindowsPath) { + FS.addFile("c:/windows/system128/foo.cpp", 0, MemoryBuffer::getMemBuffer("")); + auto Stat = FS.status("c:"); +#if !defined(_WIN32) + ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString(); +#endif + Stat = FS.status("c:/windows/system128/foo.cpp"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString(); + FS.addFile("d:/windows/foo.cpp", 0, MemoryBuffer::getMemBuffer("")); + Stat = FS.status("d:/windows/foo.cpp"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString(); +} + +TEST_F(InMemoryFileSystemTest, OverlayFile) { + FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a")); + NormalizedFS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a")); + auto Stat = FS.status("/"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString(); + Stat = FS.status("/."); + ASSERT_FALSE(Stat); + Stat = NormalizedFS.status("/."); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString(); + Stat = FS.status("/a"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_EQ("/a", Stat->getName()); +} + +TEST_F(InMemoryFileSystemTest, OverlayFileNoOwn) { + auto Buf = MemoryBuffer::getMemBuffer("a"); + FS.addFileNoOwn("/a", 0, Buf.get()); + auto Stat = FS.status("/a"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_EQ("/a", Stat->getName()); +} + +TEST_F(InMemoryFileSystemTest, OpenFileForRead) { + FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a")); + FS.addFile("././c", 0, MemoryBuffer::getMemBuffer("c")); + FS.addFile("./d/../d", 0, MemoryBuffer::getMemBuffer("d")); + NormalizedFS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a")); + NormalizedFS.addFile("././c", 0, MemoryBuffer::getMemBuffer("c")); + NormalizedFS.addFile("./d/../d", 0, MemoryBuffer::getMemBuffer("d")); + auto File = FS.openFileForRead("/a"); + ASSERT_EQ("a", (*(*File)->getBuffer("ignored"))->getBuffer()); + File = FS.openFileForRead("/a"); // Open again. + ASSERT_EQ("a", (*(*File)->getBuffer("ignored"))->getBuffer()); + File = NormalizedFS.openFileForRead("/././a"); // Open again. + ASSERT_EQ("a", (*(*File)->getBuffer("ignored"))->getBuffer()); + File = FS.openFileForRead("/"); + ASSERT_EQ(File.getError(), errc::invalid_argument) << FS.toString(); + File = FS.openFileForRead("/b"); + ASSERT_EQ(File.getError(), errc::no_such_file_or_directory) << FS.toString(); + File = FS.openFileForRead("./c"); + ASSERT_FALSE(File); + File = FS.openFileForRead("e/../d"); + ASSERT_FALSE(File); + File = NormalizedFS.openFileForRead("./c"); + ASSERT_EQ("c", (*(*File)->getBuffer("ignored"))->getBuffer()); + File = NormalizedFS.openFileForRead("e/../d"); + ASSERT_EQ("d", (*(*File)->getBuffer("ignored"))->getBuffer()); +} + +TEST_F(InMemoryFileSystemTest, DuplicatedFile) { + ASSERT_TRUE(FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a"))); + ASSERT_FALSE(FS.addFile("/a/b", 0, MemoryBuffer::getMemBuffer("a"))); + ASSERT_TRUE(FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a"))); + ASSERT_FALSE(FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("b"))); +} + +TEST_F(InMemoryFileSystemTest, DirectoryIteration) { + FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("")); + FS.addFile("/b/c", 0, MemoryBuffer::getMemBuffer("")); + + std::error_code EC; + vfs::directory_iterator I = FS.dir_begin("/", EC); + ASSERT_FALSE(EC); + ASSERT_EQ("/a", I->path()); + I.increment(EC); + ASSERT_FALSE(EC); + ASSERT_EQ("/b", I->path()); + I.increment(EC); + ASSERT_FALSE(EC); + ASSERT_EQ(vfs::directory_iterator(), I); + + I = FS.dir_begin("/b", EC); + ASSERT_FALSE(EC); + // When on Windows, we end up with "/b\\c" as the name. Convert to Posix + // path for the sake of the comparison. + ASSERT_EQ("/b/c", getPosixPath(I->path())); + I.increment(EC); + ASSERT_FALSE(EC); + ASSERT_EQ(vfs::directory_iterator(), I); +} + +TEST_F(InMemoryFileSystemTest, WorkingDirectory) { + FS.setCurrentWorkingDirectory("/b"); + FS.addFile("c", 0, MemoryBuffer::getMemBuffer("")); + + auto Stat = FS.status("/b/c"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_EQ("/b/c", Stat->getName()); + ASSERT_EQ("/b", *FS.getCurrentWorkingDirectory()); + + Stat = FS.status("c"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + + NormalizedFS.setCurrentWorkingDirectory("/b/c"); + NormalizedFS.setCurrentWorkingDirectory("."); + ASSERT_EQ("/b/c", + getPosixPath(NormalizedFS.getCurrentWorkingDirectory().get())); + NormalizedFS.setCurrentWorkingDirectory(".."); + ASSERT_EQ("/b", + getPosixPath(NormalizedFS.getCurrentWorkingDirectory().get())); +} + +#if !defined(_WIN32) +TEST_F(InMemoryFileSystemTest, GetRealPath) { + SmallString<16> Path; + EXPECT_EQ(FS.getRealPath("b", Path), errc::operation_not_permitted); + + auto GetRealPath = [this](StringRef P) { + SmallString<16> Output; + auto EC = FS.getRealPath(P, Output); + EXPECT_FALSE(EC); + return Output.str().str(); + }; + + FS.setCurrentWorkingDirectory("a"); + EXPECT_EQ(GetRealPath("b"), "a/b"); + EXPECT_EQ(GetRealPath("../b"), "b"); + EXPECT_EQ(GetRealPath("b/./c"), "a/b/c"); + + FS.setCurrentWorkingDirectory("/a"); + EXPECT_EQ(GetRealPath("b"), "/a/b"); + EXPECT_EQ(GetRealPath("../b"), "/b"); + EXPECT_EQ(GetRealPath("b/./c"), "/a/b/c"); +} +#endif // _WIN32 + +TEST_F(InMemoryFileSystemTest, AddFileWithUser) { + FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), 0xFEEDFACE); + auto Stat = FS.status("/a"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_TRUE(Stat->isDirectory()); + ASSERT_EQ(0xFEEDFACE, Stat->getUser()); + Stat = FS.status("/a/b"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_TRUE(Stat->isDirectory()); + ASSERT_EQ(0xFEEDFACE, Stat->getUser()); + Stat = FS.status("/a/b/c"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_TRUE(Stat->isRegularFile()); + ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions()); + ASSERT_EQ(0xFEEDFACE, Stat->getUser()); +} + +TEST_F(InMemoryFileSystemTest, AddFileWithGroup) { + FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, 0xDABBAD00); + auto Stat = FS.status("/a"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_TRUE(Stat->isDirectory()); + ASSERT_EQ(0xDABBAD00, Stat->getGroup()); + Stat = FS.status("/a/b"); + ASSERT_TRUE(Stat->isDirectory()); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_EQ(0xDABBAD00, Stat->getGroup()); + Stat = FS.status("/a/b/c"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_TRUE(Stat->isRegularFile()); + ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions()); + ASSERT_EQ(0xDABBAD00, Stat->getGroup()); +} + +TEST_F(InMemoryFileSystemTest, AddFileWithFileType) { + FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, None, + sys::fs::file_type::socket_file); + auto Stat = FS.status("/a"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_TRUE(Stat->isDirectory()); + Stat = FS.status("/a/b"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_TRUE(Stat->isDirectory()); + Stat = FS.status("/a/b/c"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_EQ(sys::fs::file_type::socket_file, Stat->getType()); + ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions()); +} + +TEST_F(InMemoryFileSystemTest, AddFileWithPerms) { + FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, None, None, + sys::fs::perms::owner_read | sys::fs::perms::owner_write); + auto Stat = FS.status("/a"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_TRUE(Stat->isDirectory()); + ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write | + sys::fs::perms::owner_exe, + Stat->getPermissions()); + Stat = FS.status("/a/b"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_TRUE(Stat->isDirectory()); + ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write | + sys::fs::perms::owner_exe, + Stat->getPermissions()); + Stat = FS.status("/a/b/c"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_TRUE(Stat->isRegularFile()); + ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write, + Stat->getPermissions()); +} + +TEST_F(InMemoryFileSystemTest, AddDirectoryThenAddChild) { + FS.addFile("/a", 0, MemoryBuffer::getMemBuffer(""), /*User=*/None, + /*Group=*/None, sys::fs::file_type::directory_file); + FS.addFile("/a/b", 0, MemoryBuffer::getMemBuffer("abc"), /*User=*/None, + /*Group=*/None, sys::fs::file_type::regular_file); + auto Stat = FS.status("/a"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_TRUE(Stat->isDirectory()); + Stat = FS.status("/a/b"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString(); + ASSERT_TRUE(Stat->isRegularFile()); +} + +// Test that the name returned by status() is in the same form as the path that +// was requested (to match the behavior of RealFileSystem). +TEST_F(InMemoryFileSystemTest, StatusName) { + NormalizedFS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), + /*User=*/None, + /*Group=*/None, sys::fs::file_type::regular_file); + NormalizedFS.setCurrentWorkingDirectory("/a/b"); + + // Access using InMemoryFileSystem::status. + auto Stat = NormalizedFS.status("../b/c"); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" + << NormalizedFS.toString(); + ASSERT_TRUE(Stat->isRegularFile()); + ASSERT_EQ("../b/c", Stat->getName()); + + // Access using InMemoryFileAdaptor::status. + auto File = NormalizedFS.openFileForRead("../b/c"); + ASSERT_FALSE(File.getError()) << File.getError() << "\n" + << NormalizedFS.toString(); + Stat = (*File)->status(); + ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" + << NormalizedFS.toString(); + ASSERT_TRUE(Stat->isRegularFile()); + ASSERT_EQ("../b/c", Stat->getName()); + + // Access using a directory iterator. + std::error_code EC; + llvm::vfs::directory_iterator It = NormalizedFS.dir_begin("../b", EC); + // When on Windows, we end up with "../b\\c" as the name. Convert to Posix + // path for the sake of the comparison. + ASSERT_EQ("../b/c", getPosixPath(It->path())); +} + +TEST_F(InMemoryFileSystemTest, AddHardLinkToFile) { + StringRef FromLink = "/path/to/FROM/link"; + StringRef Target = "/path/to/TO/file"; + FS.addFile(Target, 0, MemoryBuffer::getMemBuffer("content of target")); + EXPECT_TRUE(FS.addHardLink(FromLink, Target)); + EXPECT_THAT(FromLink, IsHardLinkTo(&FS, Target)); + EXPECT_TRUE(FS.status(FromLink)->getSize() == FS.status(Target)->getSize()); + EXPECT_TRUE(FS.getBufferForFile(FromLink)->get()->getBuffer() == + FS.getBufferForFile(Target)->get()->getBuffer()); +} + +TEST_F(InMemoryFileSystemTest, AddHardLinkInChainPattern) { + StringRef Link0 = "/path/to/0/link"; + StringRef Link1 = "/path/to/1/link"; + StringRef Link2 = "/path/to/2/link"; + StringRef Target = "/path/to/target"; + FS.addFile(Target, 0, MemoryBuffer::getMemBuffer("content of target file")); + EXPECT_TRUE(FS.addHardLink(Link2, Target)); + EXPECT_TRUE(FS.addHardLink(Link1, Link2)); + EXPECT_TRUE(FS.addHardLink(Link0, Link1)); + EXPECT_THAT(Link0, IsHardLinkTo(&FS, Target)); + EXPECT_THAT(Link1, IsHardLinkTo(&FS, Target)); + EXPECT_THAT(Link2, IsHardLinkTo(&FS, Target)); +} + +TEST_F(InMemoryFileSystemTest, AddHardLinkToAFileThatWasNotAddedBefore) { + EXPECT_FALSE(FS.addHardLink("/path/to/link", "/path/to/target")); +} + +TEST_F(InMemoryFileSystemTest, AddHardLinkFromAFileThatWasAddedBefore) { + StringRef Link = "/path/to/link"; + StringRef Target = "/path/to/target"; + FS.addFile(Target, 0, MemoryBuffer::getMemBuffer("content of target")); + FS.addFile(Link, 0, MemoryBuffer::getMemBuffer("content of link")); + EXPECT_FALSE(FS.addHardLink(Link, Target)); +} + +TEST_F(InMemoryFileSystemTest, AddSameHardLinkMoreThanOnce) { + StringRef Link = "/path/to/link"; + StringRef Target = "/path/to/target"; + FS.addFile(Target, 0, MemoryBuffer::getMemBuffer("content of target")); + EXPECT_TRUE(FS.addHardLink(Link, Target)); + EXPECT_FALSE(FS.addHardLink(Link, Target)); +} + +TEST_F(InMemoryFileSystemTest, AddFileInPlaceOfAHardLinkWithSameContent) { + StringRef Link = "/path/to/link"; + StringRef Target = "/path/to/target"; + StringRef Content = "content of target"; + EXPECT_TRUE(FS.addFile(Target, 0, MemoryBuffer::getMemBuffer(Content))); + EXPECT_TRUE(FS.addHardLink(Link, Target)); + EXPECT_TRUE(FS.addFile(Link, 0, MemoryBuffer::getMemBuffer(Content))); +} + +TEST_F(InMemoryFileSystemTest, AddFileInPlaceOfAHardLinkWithDifferentContent) { + StringRef Link = "/path/to/link"; + StringRef Target = "/path/to/target"; + StringRef Content = "content of target"; + StringRef LinkContent = "different content of link"; + EXPECT_TRUE(FS.addFile(Target, 0, MemoryBuffer::getMemBuffer(Content))); + EXPECT_TRUE(FS.addHardLink(Link, Target)); + EXPECT_FALSE(FS.addFile(Link, 0, MemoryBuffer::getMemBuffer(LinkContent))); +} + +TEST_F(InMemoryFileSystemTest, AddHardLinkToADirectory) { + StringRef Dir = "path/to/dummy/dir"; + StringRef Link = "/path/to/link"; + StringRef File = "path/to/dummy/dir/target"; + StringRef Content = "content of target"; + EXPECT_TRUE(FS.addFile(File, 0, MemoryBuffer::getMemBuffer(Content))); + EXPECT_FALSE(FS.addHardLink(Link, Dir)); +} + +TEST_F(InMemoryFileSystemTest, AddHardLinkFromADirectory) { + StringRef Dir = "path/to/dummy/dir"; + StringRef Target = "path/to/dummy/dir/target"; + StringRef Content = "content of target"; + EXPECT_TRUE(FS.addFile(Target, 0, MemoryBuffer::getMemBuffer(Content))); + EXPECT_FALSE(FS.addHardLink(Dir, Target)); +} + +TEST_F(InMemoryFileSystemTest, AddHardLinkUnderAFile) { + StringRef CommonContent = "content string"; + FS.addFile("/a/b", 0, MemoryBuffer::getMemBuffer(CommonContent)); + FS.addFile("/c/d", 0, MemoryBuffer::getMemBuffer(CommonContent)); + EXPECT_FALSE(FS.addHardLink("/c/d/e", "/a/b")); +} + +TEST_F(InMemoryFileSystemTest, RecursiveIterationWithHardLink) { + std::error_code EC; + FS.addFile("/a/b", 0, MemoryBuffer::getMemBuffer("content string")); + EXPECT_TRUE(FS.addHardLink("/c/d", "/a/b")); + auto I = vfs::recursive_directory_iterator(FS, "/", EC); + ASSERT_FALSE(EC); + std::vector Nodes; + for (auto E = vfs::recursive_directory_iterator(); !EC && I != E; + I.increment(EC)) { + Nodes.push_back(getPosixPath(I->path())); + } + EXPECT_THAT(Nodes, testing::UnorderedElementsAre("/a", "/a/b", "/c", "/c/d")); +} + +// NOTE: in the tests below, we use '//root/' as our root directory, since it is +// a legal *absolute* path on Windows as well as *nix. +class VFSFromYAMLTest : public ::testing::Test { +public: + int NumDiagnostics; + + void SetUp() override { NumDiagnostics = 0; } + + static void CountingDiagHandler(const SMDiagnostic &, void *Context) { + VFSFromYAMLTest *Test = static_cast(Context); + ++Test->NumDiagnostics; + } + + IntrusiveRefCntPtr + getFromYAMLRawString(StringRef Content, + IntrusiveRefCntPtr ExternalFS) { + std::unique_ptr Buffer = MemoryBuffer::getMemBuffer(Content); + return getVFSFromYAML(std::move(Buffer), CountingDiagHandler, "", this, + ExternalFS); + } + + IntrusiveRefCntPtr getFromYAMLString( + StringRef Content, + IntrusiveRefCntPtr ExternalFS = new DummyFileSystem()) { + std::string VersionPlusContent("{\n 'version':0,\n"); + VersionPlusContent += Content.slice(Content.find('{') + 1, StringRef::npos); + return getFromYAMLRawString(VersionPlusContent, ExternalFS); + } + + // This is intended as a "XFAIL" for windows hosts. + bool supportsSameDirMultipleYAMLEntries() { + Triple Host(Triple::normalize(sys::getProcessTriple())); + return !Host.isOSWindows(); + } +}; + +TEST_F(VFSFromYAMLTest, BasicVFSFromYAML) { + IntrusiveRefCntPtr FS; + FS = getFromYAMLString(""); + EXPECT_EQ(nullptr, FS.get()); + FS = getFromYAMLString("[]"); + EXPECT_EQ(nullptr, FS.get()); + FS = getFromYAMLString("'string'"); + EXPECT_EQ(nullptr, FS.get()); + EXPECT_EQ(3, NumDiagnostics); +} + +TEST_F(VFSFromYAMLTest, MappedFiles) { + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + Lower->addRegularFile("//root/foo/bar/a"); + IntrusiveRefCntPtr FS = getFromYAMLString( + "{ 'roots': [\n" + "{\n" + " 'type': 'directory',\n" + " 'name': '//root/',\n" + " 'contents': [ {\n" + " 'type': 'file',\n" + " 'name': 'file1',\n" + " 'external-contents': '//root/foo/bar/a'\n" + " },\n" + " {\n" + " 'type': 'file',\n" + " 'name': 'file2',\n" + " 'external-contents': '//root/foo/b'\n" + " }\n" + " ]\n" + "}\n" + "]\n" + "}", + Lower); + ASSERT_TRUE(FS.get() != nullptr); + + IntrusiveRefCntPtr O( + new vfs::OverlayFileSystem(Lower)); + O->pushOverlay(FS); + + // file + ErrorOr S = O->status("//root/file1"); + ASSERT_FALSE(S.getError()); + EXPECT_EQ("//root/foo/bar/a", S->getName()); + EXPECT_TRUE(S->IsVFSMapped); + + ErrorOr SLower = O->status("//root/foo/bar/a"); + EXPECT_EQ("//root/foo/bar/a", SLower->getName()); + EXPECT_TRUE(S->equivalent(*SLower)); + EXPECT_FALSE(SLower->IsVFSMapped); + + // file after opening + auto OpenedF = O->openFileForRead("//root/file1"); + ASSERT_FALSE(OpenedF.getError()); + auto OpenedS = (*OpenedF)->status(); + ASSERT_FALSE(OpenedS.getError()); + EXPECT_EQ("//root/foo/bar/a", OpenedS->getName()); + EXPECT_TRUE(OpenedS->IsVFSMapped); + + // directory + S = O->status("//root/"); + ASSERT_FALSE(S.getError()); + EXPECT_TRUE(S->isDirectory()); + EXPECT_TRUE(S->equivalent(*O->status("//root/"))); // non-volatile UniqueID + + // broken mapping + EXPECT_EQ(O->status("//root/file2").getError(), + llvm::errc::no_such_file_or_directory); + EXPECT_EQ(0, NumDiagnostics); +} + +TEST_F(VFSFromYAMLTest, CaseInsensitive) { + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + Lower->addRegularFile("//root/foo/bar/a"); + IntrusiveRefCntPtr FS = getFromYAMLString( + "{ 'case-sensitive': 'false',\n" + " 'roots': [\n" + "{\n" + " 'type': 'directory',\n" + " 'name': '//root/',\n" + " 'contents': [ {\n" + " 'type': 'file',\n" + " 'name': 'XX',\n" + " 'external-contents': '//root/foo/bar/a'\n" + " }\n" + " ]\n" + "}]}", + Lower); + ASSERT_TRUE(FS.get() != nullptr); + + IntrusiveRefCntPtr O( + new vfs::OverlayFileSystem(Lower)); + O->pushOverlay(FS); + + ErrorOr S = O->status("//root/XX"); + ASSERT_FALSE(S.getError()); + + ErrorOr SS = O->status("//root/xx"); + ASSERT_FALSE(SS.getError()); + EXPECT_TRUE(S->equivalent(*SS)); + SS = O->status("//root/xX"); + EXPECT_TRUE(S->equivalent(*SS)); + SS = O->status("//root/Xx"); + EXPECT_TRUE(S->equivalent(*SS)); + EXPECT_EQ(0, NumDiagnostics); +} + +TEST_F(VFSFromYAMLTest, CaseSensitive) { + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + Lower->addRegularFile("//root/foo/bar/a"); + IntrusiveRefCntPtr FS = getFromYAMLString( + "{ 'case-sensitive': 'true',\n" + " 'roots': [\n" + "{\n" + " 'type': 'directory',\n" + " 'name': '//root/',\n" + " 'contents': [ {\n" + " 'type': 'file',\n" + " 'name': 'XX',\n" + " 'external-contents': '//root/foo/bar/a'\n" + " }\n" + " ]\n" + "}]}", + Lower); + ASSERT_TRUE(FS.get() != nullptr); + + IntrusiveRefCntPtr O( + new vfs::OverlayFileSystem(Lower)); + O->pushOverlay(FS); + + ErrorOr SS = O->status("//root/xx"); + EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory); + SS = O->status("//root/xX"); + EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory); + SS = O->status("//root/Xx"); + EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory); + EXPECT_EQ(0, NumDiagnostics); +} + +TEST_F(VFSFromYAMLTest, IllegalVFSFile) { + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + + // invalid YAML at top-level + IntrusiveRefCntPtr FS = getFromYAMLString("{]", Lower); + EXPECT_EQ(nullptr, FS.get()); + // invalid YAML in roots + FS = getFromYAMLString("{ 'roots':[}", Lower); + // invalid YAML in directory + FS = getFromYAMLString( + "{ 'roots':[ { 'name': 'foo', 'type': 'directory', 'contents': [}", + Lower); + EXPECT_EQ(nullptr, FS.get()); + + // invalid configuration + FS = getFromYAMLString("{ 'knobular': 'true', 'roots':[] }", Lower); + EXPECT_EQ(nullptr, FS.get()); + FS = getFromYAMLString("{ 'case-sensitive': 'maybe', 'roots':[] }", Lower); + EXPECT_EQ(nullptr, FS.get()); + + // invalid roots + FS = getFromYAMLString("{ 'roots':'' }", Lower); + EXPECT_EQ(nullptr, FS.get()); + FS = getFromYAMLString("{ 'roots':{} }", Lower); + EXPECT_EQ(nullptr, FS.get()); + + // invalid entries + FS = getFromYAMLString( + "{ 'roots':[ { 'type': 'other', 'name': 'me', 'contents': '' }", Lower); + EXPECT_EQ(nullptr, FS.get()); + FS = getFromYAMLString("{ 'roots':[ { 'type': 'file', 'name': [], " + "'external-contents': 'other' }", + Lower); + EXPECT_EQ(nullptr, FS.get()); + FS = getFromYAMLString( + "{ 'roots':[ { 'type': 'file', 'name': 'me', 'external-contents': [] }", + Lower); + EXPECT_EQ(nullptr, FS.get()); + FS = getFromYAMLString( + "{ 'roots':[ { 'type': 'file', 'name': 'me', 'external-contents': {} }", + Lower); + EXPECT_EQ(nullptr, FS.get()); + FS = getFromYAMLString( + "{ 'roots':[ { 'type': 'directory', 'name': 'me', 'contents': {} }", + Lower); + EXPECT_EQ(nullptr, FS.get()); + FS = getFromYAMLString( + "{ 'roots':[ { 'type': 'directory', 'name': 'me', 'contents': '' }", + Lower); + EXPECT_EQ(nullptr, FS.get()); + FS = getFromYAMLString( + "{ 'roots':[ { 'thingy': 'directory', 'name': 'me', 'contents': [] }", + Lower); + EXPECT_EQ(nullptr, FS.get()); + + // missing mandatory fields + FS = getFromYAMLString("{ 'roots':[ { 'type': 'file', 'name': 'me' }", Lower); + EXPECT_EQ(nullptr, FS.get()); + FS = getFromYAMLString( + "{ 'roots':[ { 'type': 'file', 'external-contents': 'other' }", Lower); + EXPECT_EQ(nullptr, FS.get()); + FS = getFromYAMLString("{ 'roots':[ { 'name': 'me', 'contents': [] }", Lower); + EXPECT_EQ(nullptr, FS.get()); + + // duplicate keys + FS = getFromYAMLString("{ 'roots':[], 'roots':[] }", Lower); + EXPECT_EQ(nullptr, FS.get()); + FS = getFromYAMLString( + "{ 'case-sensitive':'true', 'case-sensitive':'true', 'roots':[] }", + Lower); + EXPECT_EQ(nullptr, FS.get()); + FS = + getFromYAMLString("{ 'roots':[{'name':'me', 'name':'you', 'type':'file', " + "'external-contents':'blah' } ] }", + Lower); + EXPECT_EQ(nullptr, FS.get()); + + // missing version + FS = getFromYAMLRawString("{ 'roots':[] }", Lower); + EXPECT_EQ(nullptr, FS.get()); + + // bad version number + FS = getFromYAMLRawString("{ 'version':'foo', 'roots':[] }", Lower); + EXPECT_EQ(nullptr, FS.get()); + FS = getFromYAMLRawString("{ 'version':-1, 'roots':[] }", Lower); + EXPECT_EQ(nullptr, FS.get()); + FS = getFromYAMLRawString("{ 'version':100000, 'roots':[] }", Lower); + EXPECT_EQ(nullptr, FS.get()); + EXPECT_EQ(24, NumDiagnostics); +} + +TEST_F(VFSFromYAMLTest, UseExternalName) { + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + Lower->addRegularFile("//root/external/file"); + + IntrusiveRefCntPtr FS = + getFromYAMLString("{ 'roots': [\n" + " { 'type': 'file', 'name': '//root/A',\n" + " 'external-contents': '//root/external/file'\n" + " },\n" + " { 'type': 'file', 'name': '//root/B',\n" + " 'use-external-name': true,\n" + " 'external-contents': '//root/external/file'\n" + " },\n" + " { 'type': 'file', 'name': '//root/C',\n" + " 'use-external-name': false,\n" + " 'external-contents': '//root/external/file'\n" + " }\n" + "] }", + Lower); + ASSERT_TRUE(nullptr != FS.get()); + + // default true + EXPECT_EQ("//root/external/file", FS->status("//root/A")->getName()); + // explicit + EXPECT_EQ("//root/external/file", FS->status("//root/B")->getName()); + EXPECT_EQ("//root/C", FS->status("//root/C")->getName()); + + // global configuration + FS = getFromYAMLString("{ 'use-external-names': false,\n" + " 'roots': [\n" + " { 'type': 'file', 'name': '//root/A',\n" + " 'external-contents': '//root/external/file'\n" + " },\n" + " { 'type': 'file', 'name': '//root/B',\n" + " 'use-external-name': true,\n" + " 'external-contents': '//root/external/file'\n" + " },\n" + " { 'type': 'file', 'name': '//root/C',\n" + " 'use-external-name': false,\n" + " 'external-contents': '//root/external/file'\n" + " }\n" + "] }", + Lower); + ASSERT_TRUE(nullptr != FS.get()); + + // default + EXPECT_EQ("//root/A", FS->status("//root/A")->getName()); + // explicit + EXPECT_EQ("//root/external/file", FS->status("//root/B")->getName()); + EXPECT_EQ("//root/C", FS->status("//root/C")->getName()); +} + +TEST_F(VFSFromYAMLTest, MultiComponentPath) { + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + Lower->addRegularFile("//root/other"); + + // file in roots + IntrusiveRefCntPtr FS = + getFromYAMLString("{ 'roots': [\n" + " { 'type': 'file', 'name': '//root/path/to/file',\n" + " 'external-contents': '//root/other' }]\n" + "}", + Lower); + ASSERT_TRUE(nullptr != FS.get()); + EXPECT_FALSE(FS->status("//root/path/to/file").getError()); + EXPECT_FALSE(FS->status("//root/path/to").getError()); + EXPECT_FALSE(FS->status("//root/path").getError()); + EXPECT_FALSE(FS->status("//root/").getError()); + + // at the start + FS = getFromYAMLString( + "{ 'roots': [\n" + " { 'type': 'directory', 'name': '//root/path/to',\n" + " 'contents': [ { 'type': 'file', 'name': 'file',\n" + " 'external-contents': '//root/other' }]}]\n" + "}", + Lower); + ASSERT_TRUE(nullptr != FS.get()); + EXPECT_FALSE(FS->status("//root/path/to/file").getError()); + EXPECT_FALSE(FS->status("//root/path/to").getError()); + EXPECT_FALSE(FS->status("//root/path").getError()); + EXPECT_FALSE(FS->status("//root/").getError()); + + // at the end + FS = getFromYAMLString( + "{ 'roots': [\n" + " { 'type': 'directory', 'name': '//root/',\n" + " 'contents': [ { 'type': 'file', 'name': 'path/to/file',\n" + " 'external-contents': '//root/other' }]}]\n" + "}", + Lower); + ASSERT_TRUE(nullptr != FS.get()); + EXPECT_FALSE(FS->status("//root/path/to/file").getError()); + EXPECT_FALSE(FS->status("//root/path/to").getError()); + EXPECT_FALSE(FS->status("//root/path").getError()); + EXPECT_FALSE(FS->status("//root/").getError()); +} + +TEST_F(VFSFromYAMLTest, TrailingSlashes) { + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + Lower->addRegularFile("//root/other"); + + // file in roots + IntrusiveRefCntPtr FS = getFromYAMLString( + "{ 'roots': [\n" + " { 'type': 'directory', 'name': '//root/path/to////',\n" + " 'contents': [ { 'type': 'file', 'name': 'file',\n" + " 'external-contents': '//root/other' }]}]\n" + "}", + Lower); + ASSERT_TRUE(nullptr != FS.get()); + EXPECT_FALSE(FS->status("//root/path/to/file").getError()); + EXPECT_FALSE(FS->status("//root/path/to").getError()); + EXPECT_FALSE(FS->status("//root/path").getError()); + EXPECT_FALSE(FS->status("//root/").getError()); +} + +TEST_F(VFSFromYAMLTest, DirectoryIteration) { + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + Lower->addDirectory("//root/"); + Lower->addDirectory("//root/foo"); + Lower->addDirectory("//root/foo/bar"); + Lower->addRegularFile("//root/foo/bar/a"); + Lower->addRegularFile("//root/foo/bar/b"); + Lower->addRegularFile("//root/file3"); + IntrusiveRefCntPtr FS = getFromYAMLString( + "{ 'use-external-names': false,\n" + " 'roots': [\n" + "{\n" + " 'type': 'directory',\n" + " 'name': '//root/',\n" + " 'contents': [ {\n" + " 'type': 'file',\n" + " 'name': 'file1',\n" + " 'external-contents': '//root/foo/bar/a'\n" + " },\n" + " {\n" + " 'type': 'file',\n" + " 'name': 'file2',\n" + " 'external-contents': '//root/foo/bar/b'\n" + " }\n" + " ]\n" + "}\n" + "]\n" + "}", + Lower); + ASSERT_TRUE(FS.get() != nullptr); + + IntrusiveRefCntPtr O( + new vfs::OverlayFileSystem(Lower)); + O->pushOverlay(FS); + + std::error_code EC; + checkContents(O->dir_begin("//root/", EC), + {"//root/file1", "//root/file2", "//root/file3", "//root/foo"}); + + checkContents(O->dir_begin("//root/foo/bar", EC), + {"//root/foo/bar/a", "//root/foo/bar/b"}); +} + +TEST_F(VFSFromYAMLTest, DirectoryIterationSameDirMultipleEntries) { + // https://llvm.org/bugs/show_bug.cgi?id=27725 + if (!supportsSameDirMultipleYAMLEntries()) + return; + + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + Lower->addDirectory("//root/zab"); + Lower->addDirectory("//root/baz"); + Lower->addRegularFile("//root/zab/a"); + Lower->addRegularFile("//root/zab/b"); + IntrusiveRefCntPtr FS = getFromYAMLString( + "{ 'use-external-names': false,\n" + " 'roots': [\n" + "{\n" + " 'type': 'directory',\n" + " 'name': '//root/baz/',\n" + " 'contents': [ {\n" + " 'type': 'file',\n" + " 'name': 'x',\n" + " 'external-contents': '//root/zab/a'\n" + " }\n" + " ]\n" + "},\n" + "{\n" + " 'type': 'directory',\n" + " 'name': '//root/baz/',\n" + " 'contents': [ {\n" + " 'type': 'file',\n" + " 'name': 'y',\n" + " 'external-contents': '//root/zab/b'\n" + " }\n" + " ]\n" + "}\n" + "]\n" + "}", + Lower); + ASSERT_TRUE(FS.get() != nullptr); + + IntrusiveRefCntPtr O( + new vfs::OverlayFileSystem(Lower)); + O->pushOverlay(FS); + + std::error_code EC; + + checkContents(O->dir_begin("//root/baz/", EC), + {"//root/baz/x", "//root/baz/y"}); +} + +TEST_F(VFSFromYAMLTest, RecursiveDirectoryIterationLevel) { + + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + Lower->addDirectory("//root/a"); + Lower->addDirectory("//root/a/b"); + Lower->addDirectory("//root/a/b/c"); + Lower->addRegularFile("//root/a/b/c/file"); + IntrusiveRefCntPtr FS = getFromYAMLString( + "{ 'use-external-names': false,\n" + " 'roots': [\n" + "{\n" + " 'type': 'directory',\n" + " 'name': '//root/a/b/c/',\n" + " 'contents': [ {\n" + " 'type': 'file',\n" + " 'name': 'file',\n" + " 'external-contents': '//root/a/b/c/file'\n" + " }\n" + " ]\n" + "},\n" + "]\n" + "}", + Lower); + ASSERT_TRUE(FS.get() != nullptr); + + IntrusiveRefCntPtr O( + new vfs::OverlayFileSystem(Lower)); + O->pushOverlay(FS); + + std::error_code EC; + + // Test recursive_directory_iterator level() + vfs::recursive_directory_iterator I = vfs::recursive_directory_iterator( + *O, "//root", EC), + E; + ASSERT_FALSE(EC); + for (int l = 0; I != E; I.increment(EC), ++l) { + ASSERT_FALSE(EC); + EXPECT_EQ(I.level(), l); + } + EXPECT_EQ(I, E); +} + +TEST_F(VFSFromYAMLTest, RelativePaths) { + IntrusiveRefCntPtr Lower(new DummyFileSystem()); + // Filename at root level without a parent directory. + IntrusiveRefCntPtr FS = getFromYAMLString( + "{ 'roots': [\n" + " { 'type': 'file', 'name': 'file-not-in-directory.h',\n" + " 'external-contents': '//root/external/file'\n" + " }\n" + "] }", + Lower); + EXPECT_EQ(nullptr, FS.get()); + + // Relative file path. + FS = getFromYAMLString("{ 'roots': [\n" + " { 'type': 'file', 'name': 'relative/file/path.h',\n" + " 'external-contents': '//root/external/file'\n" + " }\n" + "] }", + Lower); + EXPECT_EQ(nullptr, FS.get()); + + // Relative directory path. + FS = getFromYAMLString( + "{ 'roots': [\n" + " { 'type': 'directory', 'name': 'relative/directory/path.h',\n" + " 'contents': []\n" + " }\n" + "] }", + Lower); + EXPECT_EQ(nullptr, FS.get()); + + EXPECT_EQ(3, NumDiagnostics); +}