LLVM 24.0.0git
VirtualFileSystem.h
Go to the documentation of this file.
1//===- VirtualFileSystem.h - Virtual File System Layer ----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Defines the virtual file system interface vfs::FileSystem.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_VIRTUALFILESYSTEM_H
15#define LLVM_SUPPORT_VIRTUALFILESYSTEM_H
16
17#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/Support/Chrono.h"
24#include "llvm/Support/Errc.h"
25#include "llvm/Support/Error.h"
29#include "llvm/Support/Path.h"
32#include <atomic>
33#include <cassert>
34#include <cstdint>
35#include <ctime>
36#include <memory>
37#include <optional>
38#include <string>
39#include <system_error>
40#include <utility>
41#include <vector>
42
43namespace llvm {
44
45class MemoryBuffer;
46class MemoryBufferRef;
47class Twine;
48
49namespace vfs {
50
51/// The result of a \p status operation.
52class Status {
53 std::string Name;
56 uint32_t User;
57 uint32_t Group;
58 uint64_t Size;
61
62public:
63 /// Whether this entity has an external path different from the virtual path,
64 /// and the external path is exposed by leaking it through the abstraction.
65 /// For example, a RedirectingFileSystem will set this for paths where
66 /// UseExternalName is true.
67 ///
68 /// FIXME: Currently the external path is exposed by replacing the virtual
69 /// path in this Status object. Instead, we should leave the path in the
70 /// Status intact (matching the requested virtual path) - see
71 /// FileManager::getFileRef for how we plan to fix this.
73
74 Status() = default;
77 llvm::sys::TimePoint<> MTime, uint32_t User, uint32_t Group,
80
81 /// Get a copy of a Status with a different size.
82 LLVM_ABI static Status copyWithNewSize(const Status &In, uint64_t NewSize);
83 /// Get a copy of a Status with a different name.
84 LLVM_ABI static Status copyWithNewName(const Status &In,
85 const Twine &NewName);
87 const Twine &NewName);
88
89 /// Returns the name that should be used for this file or directory.
90 StringRef getName() const { return Name; }
91
92 /// @name Status interface from llvm::sys::fs
93 /// @{
94 llvm::sys::fs::file_type getType() const { return Type; }
95 llvm::sys::fs::perms getPermissions() const { return Perms; }
97 llvm::sys::fs::UniqueID getUniqueID() const { return UID; }
98 uint32_t getUser() const { return User; }
99 uint32_t getGroup() const { return Group; }
100 uint64_t getSize() const { return Size; }
101 /// @}
102 /// @name Status queries
103 /// These are static queries in llvm::sys::fs.
104 /// @{
105 LLVM_ABI bool equivalent(const Status &Other) const;
106 LLVM_ABI bool isDirectory() const;
107 LLVM_ABI bool isRegularFile() const;
108 LLVM_ABI bool isOther() const;
109 LLVM_ABI bool isSymlink() const;
110 LLVM_ABI bool isStatusKnown() const;
111 LLVM_ABI bool exists() const;
112 /// @}
113
114 /// Returns true if any of the owner, group, or others execute permissions is
115 /// set. Unlike llvm::sys::fs::can_execute, this does not check whether the
116 /// current process is allowed to execute the file.
117 LLVM_ABI bool isExecutable() const;
118};
119
120/// Represents an open file.
122public:
123 /// Destroy the file after closing it (if open).
124 /// Sub-classes should generally call close() inside their destructors. We
125 /// cannot do that from the base class, since close is virtual.
126 virtual ~File();
127
128 /// Get the status of the file.
130
131 /// Get the name of the file
133 if (auto Status = status())
134 return Status->getName().str();
135 else
136 return Status.getError();
137 }
138
139 /// Get the contents of the file as a \p MemoryBuffer.
141 getBuffer(const Twine &Name, int64_t FileSize = -1,
142 bool RequiresNullTerminator = true, bool IsVolatile = false) = 0;
143
144 /// Closes the file.
145 virtual std::error_code close() = 0;
146
147 // Get the same file with a different path.
149 getWithPath(ErrorOr<std::unique_ptr<File>> Result, const Twine &P);
150
151protected:
152 // Set the file's underlying path.
153 virtual void setPath(const Twine &Path) {}
154};
155
156/// A member of a directory, yielded by a directory_iterator.
157/// Only information available on most platforms is included.
159 std::string Path;
161
162public:
163 directory_entry() = default;
165 : Path(std::move(Path)), Type(Type) {}
166
167 llvm::StringRef path() const { return Path; }
168 llvm::sys::fs::file_type type() const { return Type; }
169};
170
171namespace detail {
172
173/// An interface for virtual file systems to provide an iterator over the
174/// (non-recursive) contents of a directory.
176 virtual ~DirIterImpl();
177
178 /// Sets \c CurrentEntry to the next entry in the directory on success,
179 /// to directory_entry() at end, or returns a system-defined \c error_code.
180 virtual std::error_code increment() = 0;
181
183};
184
185} // namespace detail
186
187/// An input iterator over the entries in a virtual path, similar to
188/// llvm::sys::fs::directory_iterator.
190 std::shared_ptr<detail::DirIterImpl> Impl; // Input iterator semantics on copy
191
192public:
193 directory_iterator(std::shared_ptr<detail::DirIterImpl> I)
194 : Impl(std::move(I)) {
195 assert(Impl.get() != nullptr && "requires non-null implementation");
196 if (Impl->CurrentEntry.path().empty())
197 Impl.reset(); // Normalize the end iterator to Impl == nullptr.
198 }
199
200 /// Construct an 'end' iterator.
202
203 /// Equivalent to operator++, with an error code.
204 directory_iterator &increment(std::error_code &EC) {
205 assert(Impl && "attempting to increment past end");
206 EC = Impl->increment();
207 if (Impl->CurrentEntry.path().empty())
208 Impl.reset(); // Normalize the end iterator to Impl == nullptr.
209 return *this;
210 }
211
212 const directory_entry &operator*() const { return Impl->CurrentEntry; }
213 const directory_entry *operator->() const { return &Impl->CurrentEntry; }
214
215 bool operator==(const directory_iterator &RHS) const {
216 if (Impl && RHS.Impl)
217 return Impl->CurrentEntry.path() == RHS.Impl->CurrentEntry.path();
218 return !Impl && !RHS.Impl;
219 }
220 bool operator!=(const directory_iterator &RHS) const {
221 return !(*this == RHS);
222 }
223};
224
225namespace detail {
226
227/// Keeps state for the recursive_directory_iterator.
229 std::vector<directory_iterator> Stack;
230 bool HasNoPushRequest = false;
231};
232
233} // end namespace detail
234
235/// An input iterator over the recursive contents of a virtual path,
236/// similar to llvm::sys::fs::recursive_directory_iterator.
238 FileSystem *FS;
239 std::shared_ptr<detail::RecDirIterState>
240 State; // Input iterator semantics on copy.
241
242public:
244 std::error_code &EC);
245
246 /// Construct an 'end' iterator.
248
249 /// Equivalent to operator++, with an error code.
250 LLVM_ABI recursive_directory_iterator &increment(std::error_code &EC);
251
252 const directory_entry &operator*() const { return *State->Stack.back(); }
253 const directory_entry *operator->() const { return &*State->Stack.back(); }
254
256 return State == Other.State; // identity
257 }
259 return !(*this == RHS);
260 }
261
262 /// Gets the current level. Starting path is at level 0.
263 int level() const {
264 assert(!State->Stack.empty() &&
265 "Cannot get level without any iteration state");
266 return State->Stack.size() - 1;
267 }
268
269 void no_push() { State->HasNoPushRequest = true; }
270};
271
272/// The virtual file system interface.
274 public RTTIExtends<FileSystem, RTTIRoot> {
275public:
276 static const char ID;
277 ~FileSystem() override;
278
279 /// Get the status of the entry at \p Path, if one exists.
280 virtual llvm::ErrorOr<Status> status(const Twine &Path) = 0;
281
282 /// Get a \p File object for the text file at \p Path, if one exists.
284 openFileForRead(const Twine &Path) = 0;
285
286 /// Get a \p File object for the binary file at \p Path, if one exists.
287 /// Some non-ascii based file systems perform encoding conversions
288 /// when reading as a text file, and this function should be used if
289 /// a file's bytes should be read as-is. On most filesystems, this
290 /// is the same behaviour as openFileForRead.
293 return openFileForRead(Path);
294 }
295
296 /// This is a convenience method that opens a file, gets its content and then
297 /// closes the file.
298 /// The IsText parameter is used to distinguish whether the file should be
299 /// opened as a binary or text file.
301 getBufferForFile(const Twine &Name, int64_t FileSize = -1,
302 bool RequiresNullTerminator = true, bool IsVolatile = false,
303 bool IsText = true);
304
305 /// Get a directory_iterator for \p Dir.
306 /// \note The 'end' iterator is directory_iterator().
308 std::error_code &EC) = 0;
309
310 /// Set the working directory. This will affect all following operations on
311 /// this file system and may propagate down for nested file systems.
312 virtual std::error_code setCurrentWorkingDirectory(const Twine &Path) = 0;
313
314 /// Get the working directory of this file system.
316
317 /// Gets real path of \p Path e.g. collapse all . and .. patterns, resolve
318 /// symlinks. For real file system, this uses `llvm::sys::fs::real_path`.
319 /// This returns errc::operation_not_permitted if not implemented by subclass.
320 virtual std::error_code getRealPath(const Twine &Path,
321 SmallVectorImpl<char> &Output);
322
323 /// Collect the paths in the real file system that contribute to a potentially
324 /// virtual directory when iterated via \a dir_begin. This can be used for
325 /// directory watching.
326 ///
327 /// Only paths that are OS-level visible are returned, so in memory and other
328 /// such entirely virtual filesystems contribute no paths.
329 virtual void
332
333 /// Check whether \p Path exists. By default this uses \c status(), but
334 /// filesystems may provide a more efficient implementation if available.
335 virtual bool exists(const Twine &Path);
336
337 /// Is the file mounted on a local filesystem?
338 virtual std::error_code isLocal(const Twine &Path, bool &Result);
339
340 /// Make \a Path an absolute path.
341 ///
342 /// Makes \a Path absolute using the current directory if it is not already.
343 /// An empty \a Path will result in the current directory.
344 ///
345 /// /absolute/path => /absolute/path
346 /// relative/../path => <current-directory>/relative/../path
347 ///
348 /// \param Path A path that is modified to be an absolute path.
349 /// \returns success if \a path has been made absolute, otherwise a
350 /// platform-specific error_code.
351 virtual std::error_code makeAbsolute(SmallVectorImpl<char> &Path) const;
352
353 /// \returns true if \p A and \p B represent the same file, or an error or
354 /// false if they do not.
355 llvm::ErrorOr<bool> equivalent(const Twine &A, const Twine &B);
356
359 unsigned IndentLevel = 0) const {
360 printImpl(OS, Type, IndentLevel);
361 }
362
364 virtual void visitChildFileSystems(VisitCallbackTy Callback) {}
365 void visit(VisitCallbackTy Callback) {
366 Callback(*this);
367 visitChildFileSystems(Callback);
368 }
369
370#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
371 LLVM_DUMP_METHOD void dump() const;
372#endif
373
374protected:
376 unsigned IndentLevel) const {
377 printIndent(OS, IndentLevel);
378 OS << "FileSystem\n";
379 }
380
381 void printIndent(raw_ostream &OS, unsigned IndentLevel) const {
382 for (unsigned i = 0; i < IndentLevel; ++i)
383 OS << " ";
384 }
385};
386
387/// Gets an \p vfs::FileSystem for the 'real' file system, as seen by
388/// the operating system.
389/// The working directory is linked to the process's working directory.
390/// (This is usually thread-hostile).
391/// This may only be called outside the IO sandbox.
393
394/// Create an \p vfs::FileSystem for the 'real' file system, as seen by
395/// the operating system.
396/// It has its own working directory, independent of (but initially equal to)
397/// that of the process.
398/// This may only be called outside the IO sandbox.
399LLVM_ABI std::unique_ptr<FileSystem> createPhysicalFileSystem();
400
401/// Searches \p Dir and then each of its parent directories for a regular file
402/// named one of \p FileNames, trying the names in order in each directory. A
403/// relative \p Dir is only searched up to its first component.
404///
405/// \returns the path of the first file found, or std::nullopt if there is
406/// none.
407LLVM_ABI std::optional<std::string>
408findFileInParentDirectories(FileSystem &FS, StringRef Dir,
409 ArrayRef<StringRef> FileNames);
410
411/// A file system that allows overlaying one \p AbstractFileSystem on top
412/// of another.
413///
414/// Consists of a stack of >=1 \p FileSystem objects, which are treated as being
415/// one merged file system. When there is a directory that exists in more than
416/// one file system, the \p OverlayFileSystem contains a directory containing
417/// the union of their contents. The attributes (permissions, etc.) of the
418/// top-most (most recently added) directory are used. When there is a file
419/// that exists in more than one file system, the file in the top-most file
420/// system overrides the other(s).
422 : public RTTIExtends<OverlayFileSystem, FileSystem> {
423 using FileSystemList = SmallVector<IntrusiveRefCntPtr<FileSystem>, 1>;
424
425 /// The stack of file systems, implemented as a list in order of
426 /// their addition.
427 FileSystemList FSList;
428
429public:
430 static const char ID;
432
433 /// Pushes a file system on top of the stack.
435
436 llvm::ErrorOr<Status> status(const Twine &Path) override;
437 bool exists(const Twine &Path) override;
439 openFileForRead(const Twine &Path) override;
440 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
442 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
443 std::error_code isLocal(const Twine &Path, bool &Result) override;
444 std::error_code getRealPath(const Twine &Path,
445 SmallVectorImpl<char> &Output) override;
446 void
448 SmallVectorImpl<std::string> &Out) override;
449
456
457 /// Get an iterator pointing to the most recently added file system.
458 iterator overlays_begin() { return FSList.rbegin(); }
459 const_iterator overlays_begin() const { return FSList.rbegin(); }
460
461 /// Get an iterator pointing one-past the least recently added file system.
462 iterator overlays_end() { return FSList.rend(); }
463 const_iterator overlays_end() const { return FSList.rend(); }
464
465 /// Get an iterator pointing to the least recently added file system.
466 reverse_iterator overlays_rbegin() { return FSList.begin(); }
467 const_reverse_iterator overlays_rbegin() const { return FSList.begin(); }
468
469 /// Get an iterator pointing one-past the most recently added file system.
470 reverse_iterator overlays_rend() { return FSList.end(); }
471 const_reverse_iterator overlays_rend() const { return FSList.end(); }
472
473 range overlays_range() { return llvm::reverse(FSList); }
474 const_range overlays_range() const { return llvm::reverse(FSList); }
475
476protected:
477 void printImpl(raw_ostream &OS, PrintType Type,
478 unsigned IndentLevel) const override;
479 void visitChildFileSystems(VisitCallbackTy Callback) override;
480};
481
482/// By default, this delegates all calls to the underlying file system. This
483/// is useful when derived file systems want to override some calls and still
484/// proxy other calls.
486 : public RTTIExtends<ProxyFileSystem, FileSystem> {
487public:
488 static const char ID;
491
492 llvm::ErrorOr<Status> status(const Twine &Path) override {
493 return FS->status(Path);
494 }
495 bool exists(const Twine &Path) override { return FS->exists(Path); }
497 openFileForRead(const Twine &Path) override {
498 return FS->openFileForRead(Path);
499 }
500 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override {
501 return FS->dir_begin(Dir, EC);
502 }
504 return FS->getCurrentWorkingDirectory();
505 }
506 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
507 return FS->setCurrentWorkingDirectory(Path);
508 }
509 std::error_code getRealPath(const Twine &Path,
510 SmallVectorImpl<char> &Output) override {
511 return FS->getRealPath(Path, Output);
512 }
513 void
515 SmallVectorImpl<std::string> &Out) override {
516 return FS->getDirectoryContentRealSources(Dir, Out);
517 }
518 std::error_code isLocal(const Twine &Path, bool &Result) override {
519 return FS->isLocal(Path, Result);
520 }
521
522protected:
523 FileSystem &getUnderlyingFS() const { return *FS; }
524 void visitChildFileSystems(VisitCallbackTy Callback) override {
525 if (FS) {
526 Callback(*FS);
527 FS->visitChildFileSystems(Callback);
528 }
529 }
530
531private:
533
534 void anchor() override;
535};
536
537namespace detail {
538
539class InMemoryDirectory;
540class InMemoryNode;
541
555
558 Value;
559
560public:
563 : Value(std::make_pair(Name, Node)) {}
564 NamedNodeOrError(std::error_code EC) : Value(EC) {}
565 NamedNodeOrError(llvm::errc EC) : Value(EC) {}
566
567 StringRef getName() const { return (*Value).first; }
568 explicit operator bool() const { return static_cast<bool>(Value); }
569 operator std::error_code() const { return Value.getError(); }
570 std::error_code getError() const { return Value.getError(); }
571 const detail::InMemoryNode *operator*() const { return (*Value).second; }
572};
573
574} // namespace detail
575
576/// An in-memory file system.
578 : public RTTIExtends<InMemoryFileSystem, FileSystem> {
579 std::unique_ptr<detail::InMemoryDirectory> Root;
580 std::string WorkingDirectory;
581 bool UseNormalizedPaths = true;
582
583public:
584 static const char ID;
585
586private:
589
590 /// Create node with \p MakeNode and add it into this filesystem at \p Path.
591 bool addFile(const Twine &Path, time_t ModificationTime,
592 std::unique_ptr<llvm::MemoryBuffer> Buffer,
593 std::optional<uint32_t> User, std::optional<uint32_t> Group,
594 std::optional<llvm::sys::fs::file_type> Type,
595 std::optional<llvm::sys::fs::perms> Perms, MakeNodeFn MakeNode);
596
597 /// Looks up the in-memory node for the path \p P.
598 /// If \p FollowFinalSymlink is true, the returned node is guaranteed to
599 /// not be a symlink and its path may differ from \p P.
600 detail::NamedNodeOrError lookupNode(const Twine &P, bool FollowFinalSymlink,
601 size_t SymlinkDepth = 0) const;
602
603 class DirIterator;
604
605public:
606 explicit InMemoryFileSystem(bool UseNormalizedPaths = true);
608
609 /// Add a file containing a buffer or a directory to the VFS with a
610 /// path. The VFS owns the buffer. If present, User, Group, Type
611 /// and Perms apply to the newly-created file or directory.
612 /// \return true if the file or directory was successfully added,
613 /// false if the file or directory already exists in the file system with
614 /// different contents.
615 bool addFile(const Twine &Path, time_t ModificationTime,
616 std::unique_ptr<llvm::MemoryBuffer> Buffer,
617 std::optional<uint32_t> User = std::nullopt,
618 std::optional<uint32_t> Group = std::nullopt,
619 std::optional<llvm::sys::fs::file_type> Type = std::nullopt,
620 std::optional<llvm::sys::fs::perms> Perms = std::nullopt);
621
622 /// Add a hard link to a file.
623 ///
624 /// Here hard links are not intended to be fully equivalent to the classical
625 /// filesystem. Both the hard link and the file share the same buffer and
626 /// status (and thus have the same UniqueID). Because of this there is no way
627 /// to distinguish between the link and the file after the link has been
628 /// added.
629 ///
630 /// The \p Target path must be an existing file or a hardlink. The
631 /// \p NewLink file must not have been added before. The \p Target
632 /// path must not be a directory. The \p NewLink node is added as a hard
633 /// link which points to the resolved file of \p Target node.
634 /// \return true if the above condition is satisfied and hardlink was
635 /// successfully created, false otherwise.
636 bool addHardLink(const Twine &NewLink, const Twine &Target);
637
638 /// Arbitrary max depth to search through symlinks. We can get into problems
639 /// if a link links to a link that links back to the link, for example.
640 static constexpr size_t MaxSymlinkDepth = 16;
641
642 /// Add a symbolic link. Unlike a HardLink, because \p Target doesn't need
643 /// to refer to a file (or refer to anything, as it happens). Also, an
644 /// in-memory directory for \p Target isn't automatically created.
645 bool
646 addSymbolicLink(const Twine &NewLink, const Twine &Target,
647 time_t ModificationTime,
648 std::optional<uint32_t> User = std::nullopt,
649 std::optional<uint32_t> Group = std::nullopt,
650 std::optional<llvm::sys::fs::perms> Perms = std::nullopt);
651
652 /// Add a buffer to the VFS with a path. The VFS does not own the buffer.
653 /// If present, User, Group, Type and Perms apply to the newly-created file
654 /// or directory.
655 /// \return true if the file or directory was successfully added,
656 /// false if the file or directory already exists in the file system with
657 /// different contents.
658 bool addFileNoOwn(const Twine &Path, time_t ModificationTime,
659 const llvm::MemoryBufferRef &Buffer,
660 std::optional<uint32_t> User = std::nullopt,
661 std::optional<uint32_t> Group = std::nullopt,
662 std::optional<llvm::sys::fs::file_type> Type = std::nullopt,
663 std::optional<llvm::sys::fs::perms> Perms = std::nullopt);
664
665 std::string toString() const;
666
667 /// Return true if this file system normalizes . and .. in paths.
668 bool useNormalizedPaths() const { return UseNormalizedPaths; }
669
670 llvm::ErrorOr<Status> status(const Twine &Path) override;
672 openFileForRead(const Twine &Path) override;
673 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
674
676 return WorkingDirectory;
677 }
678 /// Canonicalizes \p Path by combining with the current working
679 /// directory and normalizing the path (e.g. remove dots). If the current
680 /// working directory is not set, this returns errc::operation_not_permitted.
681 ///
682 /// This doesn't resolve symlinks as they are not supported in in-memory file
683 /// system.
684 std::error_code getRealPath(const Twine &Path,
685 SmallVectorImpl<char> &Output) override;
686 std::error_code isLocal(const Twine &Path, bool &Result) override;
687 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
688
689protected:
690 void printImpl(raw_ostream &OS, PrintType Type,
691 unsigned IndentLevel) const override;
692};
693
694/// Get a globally unique ID for a virtual file or directory.
696
697/// Gets a \p FileSystem for a virtual file system described in YAML
698/// format.
699LLVM_ABI std::unique_ptr<FileSystem>
700getVFSFromYAML(std::unique_ptr<llvm::MemoryBuffer> Buffer,
702 StringRef YAMLFilePath, void *DiagContext = nullptr,
704
706 template <typename T1, typename T2>
707 YAMLVFSEntry(T1 &&VPath, T2 &&RPath, bool IsDirectory = false)
708 : VPath(std::forward<T1>(VPath)), RPath(std::forward<T2>(RPath)),
710 std::string VPath;
711 std::string RPath;
712 bool IsDirectory = false;
713};
714
717
718/// A virtual file system parsed from a YAML file.
719///
720/// Currently, this class allows creating virtual files and directories. Virtual
721/// files map to existing external files in \c ExternalFS, and virtual
722/// directories may either map to existing directories in \c ExternalFS or list
723/// their contents in the form of other virtual directories and/or files.
724///
725/// The basic structure of the parsed file is:
726/// \verbatim
727/// {
728/// 'version': <version number>,
729/// <optional configuration>
730/// 'roots': [
731/// <directory entries>
732/// ]
733/// }
734/// \endverbatim
735/// The roots may be absolute or relative. If relative they will be made
736/// absolute against either current working directory or the directory where
737/// the Overlay YAML file is located, depending on the 'root-relative'
738/// configuration.
739///
740/// All configuration options are optional.
741/// 'case-sensitive': <boolean, default=(true for Posix, false for Windows)>
742/// 'use-external-names': <boolean, default=true>
743/// 'root-relative': <string, one of 'cwd' or 'overlay-dir', default='cwd'>
744/// 'overlay-relative': <boolean, default=false>
745/// 'fallthrough': <boolean, default=true, deprecated - use 'redirecting-with'
746/// instead>
747/// 'redirecting-with': <string, one of 'fallthrough', 'fallback', or
748/// 'redirect-only', default='fallthrough'>
749///
750/// To clarify, 'root-relative' option will prepend the current working
751/// directory, or the overlay directory to the 'roots->name' field only if
752/// 'roots->name' is a relative path. On the other hand, when 'overlay-relative'
753/// is set to 'true', external paths will always be prepended with the overlay
754/// directory, even if external paths are not relative paths. The
755/// 'root-relative' option has no interaction with the 'overlay-relative'
756/// option.
757///
758/// Virtual directories that list their contents are represented as
759/// \verbatim
760/// {
761/// 'type': 'directory',
762/// 'name': <string>,
763/// 'contents': [ <file or directory entries> ]
764/// }
765/// \endverbatim
766/// The default attributes for such virtual directories are:
767/// \verbatim
768/// MTime = now() when created
769/// Perms = 0777
770/// User = Group = 0
771/// Size = 0
772/// UniqueID = unspecified unique value
773/// \endverbatim
774/// When a path prefix matches such a directory, the next component in the path
775/// is matched against the entries in the 'contents' array.
776///
777/// Re-mapped directories, on the other hand, are represented as
778/// /// \verbatim
779/// {
780/// 'type': 'directory-remap',
781/// 'name': <string>,
782/// 'use-external-name': <boolean>, # Optional
783/// 'external-contents': <path to external directory>
784/// }
785/// \endverbatim
786/// and inherit their attributes from the external directory. When a path
787/// prefix matches such an entry, the unmatched components are appended to the
788/// 'external-contents' path, and the resulting path is looked up in the
789/// external file system instead.
790///
791/// Re-mapped files are represented as
792/// \verbatim
793/// {
794/// 'type': 'file',
795/// 'name': <string>,
796/// 'use-external-name': <boolean>, # Optional
797/// 'external-contents': <path to external file>
798/// }
799/// \endverbatim
800/// Their attributes and file contents are determined by looking up the file at
801/// their 'external-contents' path in the external file system.
802///
803/// For 'file', 'directory' and 'directory-remap' entries the 'name' field may
804/// contain multiple path components (e.g. /path/to/file). However, any
805/// directory in such a path that contains more than one child must be uniquely
806/// represented by a 'directory' entry.
807///
808/// When the 'use-external-name' field is set, calls to \a vfs::File::status()
809/// give the external (remapped) filesystem name instead of the name the file
810/// was accessed by. This is an intentional leak through the \a
811/// RedirectingFileSystem abstraction layer. It enables clients to discover
812/// (and use) the external file location when communicating with users or tools
813/// that don't use the same VFS overlay.
814///
815/// FIXME: 'use-external-name' causes behaviour that's inconsistent with how
816/// "real" filesystems behave. Maybe there should be a separate channel for
817/// this information.
818class LLVM_ABI RedirectingFileSystem
819 : public RTTIExtends<RedirectingFileSystem, vfs::FileSystem> {
820public:
821 static const char ID;
824
825 /// The type of redirection to perform.
826 enum class RedirectKind {
827 /// Lookup the redirected path first (ie. the one specified in
828 /// 'external-contents') and if that fails "fallthrough" to a lookup of the
829 /// originally provided path.
831 /// Lookup the provided path first and if that fails, "fallback" to a
832 /// lookup of the redirected path.
834 /// Only lookup the redirected path, do not lookup the originally provided
835 /// path.
837 };
838
839 /// The type of relative path used by Roots.
840 enum class RootRelativeKind {
841 /// The roots are relative to the current working directory.
843 /// The roots are relative to the directory where the Overlay YAML file
844 // locates.
846 };
847
848 /// A single file or directory in the VFS.
849 class Entry {
850 EntryKind Kind;
851 std::string Name;
852
853 public:
854 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
855 virtual ~Entry() = default;
856
857 StringRef getName() const { return Name; }
858 EntryKind getKind() const { return Kind; }
859 };
860
861 /// A directory in the vfs with explicitly specified contents.
862 class DirectoryEntry : public Entry {
863 std::vector<std::unique_ptr<Entry>> Contents;
864 Status S;
865
866 public:
867 /// Constructs a directory entry with explicitly specified contents.
868 DirectoryEntry(StringRef Name, std::vector<std::unique_ptr<Entry>> Contents,
869 Status S)
870 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
871 S(std::move(S)) {}
872
873 /// Constructs an empty directory entry.
875 : Entry(EK_Directory, Name), S(std::move(S)) {}
876
877 Status getStatus() { return S; }
878
879 void addContent(std::unique_ptr<Entry> Content) {
880 Contents.push_back(std::move(Content));
881 }
882
883 Entry *getLastContent() const { return Contents.back().get(); }
884
885 using iterator = decltype(Contents)::iterator;
886
887 iterator contents_begin() { return Contents.begin(); }
888 iterator contents_end() { return Contents.end(); }
889
890 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
891 };
892
893 /// A file or directory in the vfs that is mapped to a file or directory in
894 /// the external filesystem.
895 class RemapEntry : public Entry {
896 std::string ExternalContentsPath;
897 NameKind UseName;
898
899 protected:
900 RemapEntry(EntryKind K, StringRef Name, StringRef ExternalContentsPath,
901 NameKind UseName)
902 : Entry(K, Name), ExternalContentsPath(ExternalContentsPath),
903 UseName(UseName) {}
904
905 public:
906 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
907
908 /// Whether to use the external path as the name for this file or directory.
909 bool useExternalName(bool GlobalUseExternalName) const {
910 return UseName == NK_NotSet ? GlobalUseExternalName
911 : (UseName == NK_External);
912 }
913
914 NameKind getUseName() const { return UseName; }
915
916 static bool classof(const Entry *E) {
917 switch (E->getKind()) {
919 [[fallthrough]];
920 case EK_File:
921 return true;
922 case EK_Directory:
923 return false;
924 }
925 llvm_unreachable("invalid entry kind");
926 }
927 };
928
929 /// A directory in the vfs that maps to a directory in the external file
930 /// system.
932 public:
933 DirectoryRemapEntry(StringRef Name, StringRef ExternalContentsPath,
934 NameKind UseName)
935 : RemapEntry(EK_DirectoryRemap, Name, ExternalContentsPath, UseName) {}
936
937 static bool classof(const Entry *E) {
938 return E->getKind() == EK_DirectoryRemap;
939 }
940 };
941
942 /// A file in the vfs that maps to a file in the external file system.
943 class FileEntry : public RemapEntry {
944 public:
945 FileEntry(StringRef Name, StringRef ExternalContentsPath, NameKind UseName)
946 : RemapEntry(EK_File, Name, ExternalContentsPath, UseName) {}
947
948 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
949 };
950
951 /// Represents the result of a path lookup into the RedirectingFileSystem.
953 /// Chain of parent directory entries for \c E.
955
956 /// The entry the looked-up path corresponds to.
958
959 private:
960 /// When the found Entry is a DirectoryRemapEntry, stores the path in the
961 /// external file system that the looked-up path in the virtual file system
962 // corresponds to.
963 std::optional<std::string> ExternalRedirect;
964
965 public:
968
969 /// If the found Entry maps the input path to a path in the external
970 /// file system (i.e. it is a FileEntry or DirectoryRemapEntry), returns
971 /// that path.
972 std::optional<StringRef> getExternalRedirect() const {
974 return StringRef(*ExternalRedirect);
975 if (auto *FE = dyn_cast<FileEntry>(E))
976 return FE->getExternalContentsPath();
977 return std::nullopt;
978 }
979
980 /// Get the (canonical) path of the found entry. This uses the as-written
981 /// path components from the VFS specification.
982 LLVM_ABI void getPath(llvm::SmallVectorImpl<char> &Path) const;
983 };
984
985private:
988
989 /// Canonicalize path by removing ".", "..", "./", components. This is
990 /// a VFS request, do not bother about symlinks in the path components
991 /// but canonicalize in order to perform the correct entry search.
992 std::error_code makeCanonicalForLookup(SmallVectorImpl<char> &Path) const;
993
994 /// Get the File status, or error, from the underlying external file system.
995 /// This returns the status with the originally requested name, while looking
996 /// up the entry using a potentially different path.
997 ErrorOr<Status> getExternalStatus(const Twine &LookupPath,
998 const Twine &OriginalPath) const;
999
1000 /// Make \a Path an absolute path.
1001 ///
1002 /// Makes \a Path absolute using the \a WorkingDir if it is not already.
1003 ///
1004 /// /absolute/path => /absolute/path
1005 /// relative/../path => <WorkingDir>/relative/../path
1006 ///
1007 /// \param WorkingDir A path that will be used as the base Dir if \a Path
1008 /// is not already absolute.
1009 /// \param Path A path that is modified to be an absolute path.
1010 /// \returns success if \a path has been made absolute, otherwise a
1011 /// platform-specific error_code.
1012 std::error_code makeAbsolute(StringRef WorkingDir,
1013 SmallVectorImpl<char> &Path) const;
1014
1015 // In a RedirectingFileSystem, keys can be specified in Posix or Windows
1016 // style (or even a mixture of both), so this comparison helper allows
1017 // slashes (representing a root) to match backslashes (and vice versa). Note
1018 // that, other than the root, path components should not contain slashes or
1019 // backslashes.
1020 bool pathComponentMatches(llvm::StringRef lhs, llvm::StringRef rhs) const {
1021 if ((CaseSensitive ? lhs == rhs : lhs.equals_insensitive(rhs)))
1022 return true;
1023 return (lhs == "/" && rhs == "\\") || (lhs == "\\" && rhs == "/");
1024 }
1025
1026 /// The root(s) of the virtual file system.
1027 std::vector<std::unique_ptr<Entry>> Roots;
1028
1029 /// The current working directory of the file system.
1030 std::string WorkingDirectory;
1031
1032 /// The file system to use for external references.
1034
1035 /// This represents the directory path that the YAML file is located.
1036 /// This will be prefixed to each 'external-contents' if IsRelativeOverlay
1037 /// is set. This will also be prefixed to each 'roots->name' if RootRelative
1038 /// is set to RootRelativeKind::OverlayDir and the path is relative.
1039 std::string OverlayFileDir;
1040
1041 /// @name Configuration
1042 /// @{
1043
1044 /// Whether to perform case-sensitive comparisons.
1045 ///
1046 /// Currently, case-insensitive matching only works correctly with ASCII.
1047 bool CaseSensitive = is_style_posix(sys::path::Style::native);
1048
1049 /// IsRelativeOverlay marks whether a OverlayFileDir path must
1050 /// be prefixed in every 'external-contents' when reading from YAML files.
1051 bool IsRelativeOverlay = false;
1052
1053 /// Whether to use to use the value of 'external-contents' for the
1054 /// names of files. This global value is overridable on a per-file basis.
1055 bool UseExternalNames = true;
1056
1057 /// True if this FS has redirected a lookup. This does not include
1058 /// fallthrough.
1059 mutable bool HasBeenUsed = false;
1060
1061 /// Used to enable or disable updating `HasBeenUsed`.
1062 bool UsageTrackingActive = false;
1063
1064 /// Determines the lookups to perform, as well as their order. See
1065 /// \c RedirectKind for details.
1066 RedirectKind Redirection = RedirectKind::Fallthrough;
1067
1068 /// Determine the prefix directory if the roots are relative paths. See
1069 /// \c RootRelativeKind for details.
1070 RootRelativeKind RootRelative = RootRelativeKind::CWD;
1071 /// @}
1072
1074
1075 // Explicitly non-copyable.
1077 RedirectingFileSystem &operator=(RedirectingFileSystem const &) = delete;
1078
1079 /// Looks up the path <tt>[Start, End)</tt> in \p From, possibly recursing
1080 /// into the contents of \p From if it is a directory. Returns a LookupResult
1081 /// giving the matched entry and, if that entry is a FileEntry or
1082 /// DirectoryRemapEntry, the path it redirects to in the external file system.
1084 lookupPathImpl(llvm::sys::path::const_iterator Start,
1086 llvm::SmallVectorImpl<Entry *> &Entries) const;
1087
1088 /// Get the status for a path with the provided \c LookupResult.
1089 ErrorOr<Status> status(const Twine &LookupPath, const Twine &OriginalPath,
1090 const LookupResult &Result);
1091
1092public:
1093 /// Looks up \p Path in \c Roots and returns a LookupResult giving the
1094 /// matched entry and, if the entry was a FileEntry or DirectoryRemapEntry,
1095 /// the path it redirects to in the external file system.
1096 ErrorOr<LookupResult> lookupPath(StringRef Path) const;
1097
1098 /// Parses \p Buffer, which is expected to be in YAML format and
1099 /// returns a virtual file system representing its contents.
1100 static std::unique_ptr<RedirectingFileSystem>
1101 create(std::unique_ptr<MemoryBuffer> Buffer,
1103 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
1104
1105 /// Redirect each of the remapped files from first to second.
1106 static std::unique_ptr<RedirectingFileSystem>
1107 create(ArrayRef<std::pair<std::string, std::string>> RemappedFiles,
1108 bool UseExternalNames, IntrusiveRefCntPtr<FileSystem> ExternalFS);
1109
1110 ErrorOr<Status> status(const Twine &Path) override;
1111 bool exists(const Twine &Path) override;
1112 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
1113
1114 std::error_code getRealPath(const Twine &Path,
1115 SmallVectorImpl<char> &Output) override;
1116
1117 void
1118 getDirectoryContentRealSources(const Twine &Dir,
1119 SmallVectorImpl<std::string> &Out) override;
1120
1121 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
1122
1123 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
1124
1125 std::error_code isLocal(const Twine &Path, bool &Result) override;
1126
1127 std::error_code makeAbsolute(SmallVectorImpl<char> &Path) const override;
1128
1129 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
1130
1131 void setOverlayFileDir(StringRef PrefixDir);
1132
1133 StringRef getOverlayFileDir() const;
1134
1135 /// Sets the redirection kind to \c Fallthrough if true or \c RedirectOnly
1136 /// otherwise. Will removed in the future, use \c setRedirection instead.
1137 void setFallthrough(bool Fallthrough);
1138
1139 void setRedirection(RedirectingFileSystem::RedirectKind Kind);
1140
1141 std::vector<llvm::StringRef> getRoots() const;
1142
1143 bool hasBeenUsed() const { return HasBeenUsed; };
1144 void clearHasBeenUsed() { HasBeenUsed = false; }
1145
1146 void setUsageTrackingActive(bool Active) { UsageTrackingActive = Active; }
1147
1148 void printEntry(raw_ostream &OS, Entry *E, unsigned IndentLevel = 0) const;
1149
1150protected:
1151 void printImpl(raw_ostream &OS, PrintType Type,
1152 unsigned IndentLevel) const override;
1153 void visitChildFileSystems(VisitCallbackTy Callback) override;
1154};
1155
1156/// Collect all pairs of <virtual path, real path> entries from the
1157/// \p VFS. This is used by the module dependency collector to forward
1158/// the entries into the reproducer output VFS YAML file.
1159LLVM_ABI void
1160collectVFSEntries(RedirectingFileSystem &VFS,
1161 SmallVectorImpl<YAMLVFSEntry> &CollectedEntries);
1162
1164 std::vector<YAMLVFSEntry> Mappings;
1165 std::optional<bool> IsCaseSensitive;
1166 std::optional<bool> IsOverlayRelative;
1167 std::optional<bool> UseExternalNames;
1168 std::string OverlayDir;
1169
1170 void addEntry(StringRef VirtualPath, StringRef RealPath, bool IsDirectory);
1171
1172public:
1173 YAMLVFSWriter() = default;
1174
1175 LLVM_ABI void addFileMapping(StringRef VirtualPath, StringRef RealPath);
1176 LLVM_ABI void addDirectoryMapping(StringRef VirtualPath, StringRef RealPath);
1177
1178 void setCaseSensitivity(bool CaseSensitive) {
1179 IsCaseSensitive = CaseSensitive;
1180 }
1181
1182 void setUseExternalNames(bool UseExtNames) { UseExternalNames = UseExtNames; }
1183
1184 void setOverlayDir(StringRef OverlayDirectory) {
1185 IsOverlayRelative = true;
1186 OverlayDir.assign(OverlayDirectory.str());
1187 }
1188
1189 const std::vector<YAMLVFSEntry> &getMappings() const { return Mappings; }
1190
1192};
1193
1194/// File system that tracks the number of calls to the underlying file system.
1195/// This is particularly useful when wrapped around \c RealFileSystem to add
1196/// lightweight tracking of expensive syscalls.
1197///
1198/// Templated on the counter type so callers can choose between non-atomic
1199/// counters (suitable for single-threaded tracing) and atomic counters
1200/// (suitable for tracing under concurrent access). Use the
1201/// \c TracingFileSystem and \c AtomicTracingFileSystem aliases below.
1202template <typename CounterT>
1204 : public llvm::RTTIExtends<TracingFileSystemImpl<CounterT>,
1205 ProxyFileSystem> {
1206public:
1207 inline static const char ID = 0;
1208
1209 CounterT NumStatusCalls = 0;
1211 CounterT NumDirBeginCalls = 0;
1213 CounterT NumExistsCalls = 0;
1214 CounterT NumIsLocalCalls = 0;
1215
1219
1220 ErrorOr<Status> status(const Twine &Path) override {
1222 return ProxyFileSystem::status(Path);
1223 }
1224
1229
1230 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override {
1232 return ProxyFileSystem::dir_begin(Dir, EC);
1233 }
1234
1235 std::error_code getRealPath(const Twine &Path,
1236 SmallVectorImpl<char> &Output) override {
1238 return ProxyFileSystem::getRealPath(Path, Output);
1239 }
1240
1241 bool exists(const Twine &Path) override {
1243 return ProxyFileSystem::exists(Path);
1244 }
1245
1246 std::error_code isLocal(const Twine &Path, bool &Result) override {
1248 return ProxyFileSystem::isLocal(Path, Result);
1249 }
1250
1251protected:
1253 unsigned IndentLevel) const override {
1254 FileSystem::printIndent(OS, IndentLevel);
1255 OS << "TracingFileSystem\n";
1257 return;
1258
1259 FileSystem::printIndent(OS, IndentLevel);
1260 OS << "NumStatusCalls=" << static_cast<std::size_t>(NumStatusCalls) << "\n";
1261 FileSystem::printIndent(OS, IndentLevel);
1262 OS << "NumOpenFileForReadCalls="
1263 << static_cast<std::size_t>(NumOpenFileForReadCalls) << "\n";
1264 FileSystem::printIndent(OS, IndentLevel);
1265 OS << "NumDirBeginCalls=" << static_cast<std::size_t>(NumDirBeginCalls)
1266 << "\n";
1267 FileSystem::printIndent(OS, IndentLevel);
1268 OS << "NumGetRealPathCalls="
1269 << static_cast<std::size_t>(NumGetRealPathCalls) << "\n";
1270 FileSystem::printIndent(OS, IndentLevel);
1271 OS << "NumExistsCalls=" << static_cast<std::size_t>(NumExistsCalls) << "\n";
1272 FileSystem::printIndent(OS, IndentLevel);
1273 OS << "NumIsLocalCalls=" << static_cast<std::size_t>(NumIsLocalCalls)
1274 << "\n";
1275
1278 this->getUnderlyingFS().print(OS, Type, IndentLevel + 1);
1279 }
1280};
1281
1282/// Single-threaded tracing filesystem. Counters are plain \c std::size_t and
1283/// must not be incremented concurrently.
1285
1286/// Concurrent-safe tracing filesystem. Counters are \c std::atomic<std::size_t>
1287/// so the proxy can be shared across threads.
1289
1290} // namespace vfs
1291} // namespace llvm
1292
1293#endif // LLVM_SUPPORT_VIRTUALFILESYSTEM_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
Provides ErrorOr<T> smart pointer.
static void makeAbsolute(vfs::FileSystem &VFS, SmallVectorImpl< char > &Path)
Make Path absolute.
This file defines the RefCountedBase, ThreadSafeRefCountedBase, and IntrusiveRefCntPtr classes.
#define I(x, y, z)
Definition MD5.cpp:57
static const char * toString(MIToken::TokenKind TokenKind)
Definition MIParser.cpp:609
#define T1
static void printImpl(const MCAsmInfo &MAI, raw_ostream &OS, const MCSpecifierExpr &Expr)
#define P(N)
This file defines the SmallVector class.
static void DiagHandler(const SMDiagnostic &Diag, void *Context)
Contains the forward declaration for vfs::FileSystem, as well as the IntrusiveRefCntPtrInfo specializ...
Value * RHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Represents either an error or a value T.
Definition ErrorOr.h:56
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Inheritance utility for extensible RTTI.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
std::reverse_iterator< const_iterator > const_reverse_iterator
std::reverse_iterator< iterator > reverse_iterator
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
void(*)(const SMDiagnostic &, void *Context) DiagHandlerTy
Clients that want to handle their own diagnostics in a custom way can register a function pointer+con...
Definition SourceMgr.h:46
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
bool equals_insensitive(StringRef RHS) const
Check for string equality, ignoring case.
Definition StringRef.h:170
Target - Wrapper for Target specific information.
A thread-safe version of RefCountedBase.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
An efficient, type-erasing, non-owning reference to a callable.
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Represents the result of a call to sys::fs::status().
Definition FileSystem.h:214
The virtual file system interface.
llvm::function_ref< void(FileSystem &)> VisitCallbackTy
virtual llvm::ErrorOr< std::string > getCurrentWorkingDirectory() const =0
Get the working directory of this file system.
virtual llvm::ErrorOr< std::unique_ptr< File > > openFileForReadBinary(const Twine &Path)
Get a File object for the binary file at Path, if one exists.
virtual std::error_code setCurrentWorkingDirectory(const Twine &Path)=0
Set the working directory.
virtual void printImpl(raw_ostream &OS, PrintType Type, unsigned IndentLevel) const
virtual void getDirectoryContentRealSources(const Twine &Dir, SmallVectorImpl< std::string > &Out)
Collect the paths in the real file system that contribute to a potentially virtual directory when ite...
virtual llvm::ErrorOr< std::unique_ptr< File > > openFileForRead(const Twine &Path)=0
Get a File object for the text file at Path, if one exists.
virtual std::error_code getRealPath(const Twine &Path, SmallVectorImpl< char > &Output)
Gets real path of Path e.g.
virtual directory_iterator dir_begin(const Twine &Dir, std::error_code &EC)=0
Get a directory_iterator for Dir.
void printIndent(raw_ostream &OS, unsigned IndentLevel) const
void print(raw_ostream &OS, PrintType Type=PrintType::Contents, unsigned IndentLevel=0) const
virtual void visitChildFileSystems(VisitCallbackTy Callback)
void visit(VisitCallbackTy Callback)
virtual llvm::ErrorOr< Status > status(const Twine &Path)=0
Get the status of the entry at Path, if one exists.
Represents an open file.
static ErrorOr< std::unique_ptr< File > > getWithPath(ErrorOr< std::unique_ptr< File > > Result, const Twine &P)
virtual llvm::ErrorOr< Status > status()=0
Get the status of the file.
virtual llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBuffer(const Twine &Name, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)=0
Get the contents of the file as a MemoryBuffer.
virtual llvm::ErrorOr< std::string > getName()
Get the name of the file.
virtual void setPath(const Twine &Path)
virtual ~File()
Destroy the file after closing it (if open).
virtual std::error_code close()=0
Closes the file.
Adaptor from InMemoryDir::iterator to directory_iterator.
static constexpr size_t MaxSymlinkDepth
Arbitrary max depth to search through symlinks.
InMemoryFileSystem(bool UseNormalizedPaths=true)
bool useNormalizedPaths() const
Return true if this file system normalizes . and .. in paths.
llvm::ErrorOr< std::string > getCurrentWorkingDirectory() const override
bool addHardLink(const Twine &NewLink, const Twine &Target)
Add a hard link to a file.
bool addFileNoOwn(const Twine &Path, time_t ModificationTime, const llvm::MemoryBufferRef &Buffer, std::optional< uint32_t > User=std::nullopt, std::optional< uint32_t > Group=std::nullopt, std::optional< llvm::sys::fs::file_type > Type=std::nullopt, std::optional< llvm::sys::fs::perms > Perms=std::nullopt)
Add a buffer to the VFS with a path.
bool addSymbolicLink(const Twine &NewLink, const Twine &Target, time_t ModificationTime, std::optional< uint32_t > User=std::nullopt, std::optional< uint32_t > Group=std::nullopt, std::optional< llvm::sys::fs::perms > Perms=std::nullopt)
Add a symbolic link.
const_iterator overlays_end() const
const_iterator overlays_begin() const
directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override
reverse_iterator overlays_rbegin()
Get an iterator pointing to the least recently added file system.
const_range overlays_range() const
const_reverse_iterator overlays_rend() const
iterator_range< iterator > range
llvm::ErrorOr< std::unique_ptr< File > > openFileForRead(const Twine &Path) override
reverse_iterator overlays_rend()
Get an iterator pointing one-past the most recently added file system.
std::error_code getRealPath(const Twine &Path, SmallVectorImpl< char > &Output) override
std::error_code setCurrentWorkingDirectory(const Twine &Path) override
void pushOverlay(IntrusiveRefCntPtr< FileSystem > FS)
Pushes a file system on top of the stack.
FileSystemList::const_reverse_iterator const_iterator
OverlayFileSystem(IntrusiveRefCntPtr< FileSystem > Base)
FileSystemList::const_iterator const_reverse_iterator
llvm::ErrorOr< std::string > getCurrentWorkingDirectory() const override
void getDirectoryContentRealSources(const Twine &Dir, SmallVectorImpl< std::string > &Out) override
iterator overlays_end()
Get an iterator pointing one-past the least recently added file system.
std::error_code isLocal(const Twine &Path, bool &Result) override
FileSystemList::iterator reverse_iterator
bool exists(const Twine &Path) override
llvm::ErrorOr< Status > status(const Twine &Path) override
iterator overlays_begin()
Get an iterator pointing to the most recently added file system.
iterator_range< const_iterator > const_range
const_reverse_iterator overlays_rbegin() const
FileSystemList::reverse_iterator iterator
By default, this delegates all calls to the underlying file system.
llvm::ErrorOr< std::unique_ptr< File > > openFileForRead(const Twine &Path) override
void visitChildFileSystems(VisitCallbackTy Callback) override
std::error_code getRealPath(const Twine &Path, SmallVectorImpl< char > &Output) override
directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override
llvm::ErrorOr< Status > status(const Twine &Path) override
bool exists(const Twine &Path) override
std::error_code setCurrentWorkingDirectory(const Twine &Path) override
std::error_code isLocal(const Twine &Path, bool &Result) override
ProxyFileSystem(IntrusiveRefCntPtr< FileSystem > FS)
void getDirectoryContentRealSources(const Twine &Dir, SmallVectorImpl< std::string > &Out) override
llvm::ErrorOr< std::string > getCurrentWorkingDirectory() const override
FileSystem & getUnderlyingFS() const
Directory iterator implementation for RedirectingFileSystem's directory entries.
A helper class to hold the common YAML parsing state.
DirectoryEntry(StringRef Name, Status S)
Constructs an empty directory entry.
DirectoryEntry(StringRef Name, std::vector< std::unique_ptr< Entry > > Contents, Status S)
Constructs a directory entry with explicitly specified contents.
void addContent(std::unique_ptr< Entry > Content)
DirectoryRemapEntry(StringRef Name, StringRef ExternalContentsPath, NameKind UseName)
A single file or directory in the VFS.
FileEntry(StringRef Name, StringRef ExternalContentsPath, NameKind UseName)
RemapEntry(EntryKind K, StringRef Name, StringRef ExternalContentsPath, NameKind UseName)
bool useExternalName(bool GlobalUseExternalName) const
Whether to use the external path as the name for this file or directory.
A virtual file system parsed from a YAML file.
RootRelativeKind
The type of relative path used by Roots.
@ OverlayDir
The roots are relative to the directory where the Overlay YAML file.
@ CWD
The roots are relative to the current working directory.
RedirectKind
The type of redirection to perform.
@ Fallthrough
Lookup the redirected path first (ie.
@ Fallback
Lookup the provided path first and if that fails, "fallback" to a lookup of the redirected path.
@ RedirectOnly
Only lookup the redirected path, do not lookup the originally provided path.
The result of a status operation.
llvm::sys::fs::perms getPermissions() const
llvm::sys::fs::UniqueID getUniqueID() const
uint32_t getUser() const
LLVM_ABI bool equivalent(const Status &Other) const
static LLVM_ABI Status copyWithNewName(const Status &In, const Twine &NewName)
Get a copy of a Status with a different name.
uint64_t getSize() const
LLVM_ABI bool isStatusKnown() const
LLVM_ABI bool exists() const
bool ExposesExternalVFSPath
Whether this entity has an external path different from the virtual path, and the external path is ex...
uint32_t getGroup() const
static LLVM_ABI Status copyWithNewSize(const Status &In, uint64_t NewSize)
Get a copy of a Status with a different size.
LLVM_ABI bool isOther() const
LLVM_ABI bool isSymlink() const
llvm::sys::TimePoint getLastModificationTime() const
llvm::sys::fs::file_type getType() const
LLVM_ABI bool isRegularFile() const
LLVM_ABI bool isExecutable() const
Returns true if any of the owner, group, or others execute permissions is set.
LLVM_ABI bool isDirectory() const
StringRef getName() const
Returns the name that should be used for this file or directory.
File system that tracks the number of calls to the underlying file system.
void printImpl(raw_ostream &OS, FileSystem::PrintType Type, unsigned IndentLevel) const override
TracingFileSystemImpl(llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS)
directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override
std::error_code isLocal(const Twine &Path, bool &Result) override
ErrorOr< std::unique_ptr< File > > openFileForRead(const Twine &Path) override
std::error_code getRealPath(const Twine &Path, SmallVectorImpl< char > &Output) override
bool exists(const Twine &Path) override
ErrorOr< Status > status(const Twine &Path) override
LLVM_ABI void addFileMapping(StringRef VirtualPath, StringRef RealPath)
void setCaseSensitivity(bool CaseSensitive)
void setOverlayDir(StringRef OverlayDirectory)
const std::vector< YAMLVFSEntry > & getMappings() const
LLVM_ABI void write(llvm::raw_ostream &OS)
LLVM_ABI void addDirectoryMapping(StringRef VirtualPath, StringRef RealPath)
void setUseExternalNames(bool UseExtNames)
The in memory file system is a tree of Nodes.
const detail::InMemoryNode * operator*() const
NamedNodeOrError(llvm::SmallString< 128 > Name, const detail::InMemoryNode *Node)
A member of a directory, yielded by a directory_iterator.
directory_entry()=default
directory_entry(std::string Path, llvm::sys::fs::file_type Type)
llvm::StringRef path() const
llvm::sys::fs::file_type type() const
An input iterator over the entries in a virtual path, similar to llvm::sys::fs::directory_iterator.
directory_iterator(std::shared_ptr< detail::DirIterImpl > I)
bool operator==(const directory_iterator &RHS) const
const directory_entry * operator->() const
const directory_entry & operator*() const
directory_iterator & increment(std::error_code &EC)
Equivalent to operator++, with an error code.
bool operator!=(const directory_iterator &RHS) const
directory_iterator()=default
Construct an 'end' iterator.
const directory_entry & operator*() const
LLVM_ABI recursive_directory_iterator(FileSystem &FS, const Twine &Path, std::error_code &EC)
recursive_directory_iterator()=default
Construct an 'end' iterator.
bool operator!=(const recursive_directory_iterator &RHS) const
bool operator==(const recursive_directory_iterator &Other) const
int level() const
Gets the current level. Starting path is at level 0.
LLVM_ABI recursive_directory_iterator & increment(std::error_code &EC)
Equivalent to operator++, with an error code.
const directory_entry * operator->() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
file_type
An enumeration for the file system's view of the type.
Definition FileSystem.h:54
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
Definition Chrono.h:34
TracingFileSystemImpl< std::atomic< std::size_t > > AtomicTracingFileSystem
Concurrent-safe tracing filesystem.
TracingFileSystemImpl< std::size_t > TracingFileSystem
Single-threaded tracing filesystem.
LLVM_ABI void collectVFSEntries(RedirectingFileSystem &VFS, SmallVectorImpl< YAMLVFSEntry > &CollectedEntries)
Collect all pairs of <virtual path, real path> entries from the VFS.
LLVM_ABI std::unique_ptr< FileSystem > createPhysicalFileSystem()
Create an vfs::FileSystem for the 'real' file system, as seen by the operating system.
LLVM_ABI llvm::sys::fs::UniqueID getNextVirtualUniqueID()
Get a globally unique ID for a virtual file or directory.
LLVM_ABI std::optional< std::string > findFileInParentDirectories(FileSystem &FS, StringRef Dir, ArrayRef< StringRef > FileNames)
Searches Dir and then each of its parent directories for a regular file named one of FileNames,...
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
LLVM_ABI std::unique_ptr< FileSystem > getVFSFromYAML(std::unique_ptr< llvm::MemoryBuffer > Buffer, llvm::SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath, void *DiagContext=nullptr, IntrusiveRefCntPtr< FileSystem > ExternalFS=getRealFileSystem())
Gets a FileSystem for a virtual file system described in YAML format.
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
errc
Definition Errc.h:35
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Other
Any other memory.
Definition ModRef.h:68
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
std::optional< StringRef > getExternalRedirect() const
If the found Entry maps the input path to a path in the external file system (i.e.
Entry * E
The entry the looked-up path corresponds to.
LLVM_ABI LookupResult(Entry *E, sys::path::const_iterator Start, sys::path::const_iterator End)
llvm::SmallVector< Entry *, 32 > Parents
Chain of parent directory entries for E.
YAMLVFSEntry(T1 &&VPath, T2 &&RPath, bool IsDirectory=false)
An interface for virtual file systems to provide an iterator over the (non-recursive) contents of a d...
virtual std::error_code increment()=0
Sets CurrentEntry to the next entry in the directory on success, to directory_entry() at end,...
std::unique_ptr< llvm::MemoryBuffer > Buffer
Keeps state for the recursive_directory_iterator.
std::vector< directory_iterator > Stack