xref: /aosp_15_r20/external/clang/lib/Basic/VirtualFileSystem.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===- VirtualFileSystem.cpp - Virtual File System Layer --------*- C++ -*-===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li // This file implements the VirtualFileSystem interface.
10*67e74705SXin Li //===----------------------------------------------------------------------===//
11*67e74705SXin Li 
12*67e74705SXin Li #include "clang/Basic/VirtualFileSystem.h"
13*67e74705SXin Li #include "clang/Basic/FileManager.h"
14*67e74705SXin Li #include "llvm/ADT/DenseMap.h"
15*67e74705SXin Li #include "llvm/ADT/STLExtras.h"
16*67e74705SXin Li #include "llvm/ADT/StringExtras.h"
17*67e74705SXin Li #include "llvm/ADT/StringSet.h"
18*67e74705SXin Li #include "llvm/ADT/iterator_range.h"
19*67e74705SXin Li #include "llvm/Config/llvm-config.h"
20*67e74705SXin Li #include "llvm/Support/Debug.h"
21*67e74705SXin Li #include "llvm/Support/Errc.h"
22*67e74705SXin Li #include "llvm/Support/MemoryBuffer.h"
23*67e74705SXin Li #include "llvm/Support/Path.h"
24*67e74705SXin Li #include "llvm/Support/Process.h"
25*67e74705SXin Li #include "llvm/Support/YAMLParser.h"
26*67e74705SXin Li #include <atomic>
27*67e74705SXin Li #include <memory>
28*67e74705SXin Li #include <utility>
29*67e74705SXin Li 
30*67e74705SXin Li // For chdir.
31*67e74705SXin Li #ifdef LLVM_ON_WIN32
32*67e74705SXin Li #  include <direct.h>
33*67e74705SXin Li #else
34*67e74705SXin Li #  include <unistd.h>
35*67e74705SXin Li #endif
36*67e74705SXin Li 
37*67e74705SXin Li using namespace clang;
38*67e74705SXin Li using namespace clang::vfs;
39*67e74705SXin Li using namespace llvm;
40*67e74705SXin Li using llvm::sys::fs::file_status;
41*67e74705SXin Li using llvm::sys::fs::file_type;
42*67e74705SXin Li using llvm::sys::fs::perms;
43*67e74705SXin Li using llvm::sys::fs::UniqueID;
44*67e74705SXin Li 
Status(const file_status & Status)45*67e74705SXin Li Status::Status(const file_status &Status)
46*67e74705SXin Li     : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
47*67e74705SXin Li       User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
48*67e74705SXin Li       Type(Status.type()), Perms(Status.permissions()), IsVFSMapped(false)  {}
49*67e74705SXin Li 
Status(StringRef Name,UniqueID UID,sys::TimeValue MTime,uint32_t User,uint32_t Group,uint64_t Size,file_type Type,perms Perms)50*67e74705SXin Li Status::Status(StringRef Name, UniqueID UID, sys::TimeValue MTime,
51*67e74705SXin Li                uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
52*67e74705SXin Li                perms Perms)
53*67e74705SXin Li     : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
54*67e74705SXin Li       Type(Type), Perms(Perms), IsVFSMapped(false) {}
55*67e74705SXin Li 
copyWithNewName(const Status & In,StringRef NewName)56*67e74705SXin Li Status Status::copyWithNewName(const Status &In, StringRef NewName) {
57*67e74705SXin Li   return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
58*67e74705SXin Li                 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
59*67e74705SXin Li                 In.getPermissions());
60*67e74705SXin Li }
61*67e74705SXin Li 
copyWithNewName(const file_status & In,StringRef NewName)62*67e74705SXin Li Status Status::copyWithNewName(const file_status &In, StringRef NewName) {
63*67e74705SXin Li   return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
64*67e74705SXin Li                 In.getUser(), In.getGroup(), In.getSize(), In.type(),
65*67e74705SXin Li                 In.permissions());
66*67e74705SXin Li }
67*67e74705SXin Li 
equivalent(const Status & Other) const68*67e74705SXin Li bool Status::equivalent(const Status &Other) const {
69*67e74705SXin Li   return getUniqueID() == Other.getUniqueID();
70*67e74705SXin Li }
isDirectory() const71*67e74705SXin Li bool Status::isDirectory() const {
72*67e74705SXin Li   return Type == file_type::directory_file;
73*67e74705SXin Li }
isRegularFile() const74*67e74705SXin Li bool Status::isRegularFile() const {
75*67e74705SXin Li   return Type == file_type::regular_file;
76*67e74705SXin Li }
isOther() const77*67e74705SXin Li bool Status::isOther() const {
78*67e74705SXin Li   return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
79*67e74705SXin Li }
isSymlink() const80*67e74705SXin Li bool Status::isSymlink() const {
81*67e74705SXin Li   return Type == file_type::symlink_file;
82*67e74705SXin Li }
isStatusKnown() const83*67e74705SXin Li bool Status::isStatusKnown() const {
84*67e74705SXin Li   return Type != file_type::status_error;
85*67e74705SXin Li }
exists() const86*67e74705SXin Li bool Status::exists() const {
87*67e74705SXin Li   return isStatusKnown() && Type != file_type::file_not_found;
88*67e74705SXin Li }
89*67e74705SXin Li 
~File()90*67e74705SXin Li File::~File() {}
91*67e74705SXin Li 
~FileSystem()92*67e74705SXin Li FileSystem::~FileSystem() {}
93*67e74705SXin Li 
94*67e74705SXin Li ErrorOr<std::unique_ptr<MemoryBuffer>>
getBufferForFile(const llvm::Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)95*67e74705SXin Li FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
96*67e74705SXin Li                              bool RequiresNullTerminator, bool IsVolatile) {
97*67e74705SXin Li   auto F = openFileForRead(Name);
98*67e74705SXin Li   if (!F)
99*67e74705SXin Li     return F.getError();
100*67e74705SXin Li 
101*67e74705SXin Li   return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
102*67e74705SXin Li }
103*67e74705SXin Li 
makeAbsolute(SmallVectorImpl<char> & Path) const104*67e74705SXin Li std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
105*67e74705SXin Li   if (llvm::sys::path::is_absolute(Path))
106*67e74705SXin Li     return std::error_code();
107*67e74705SXin Li 
108*67e74705SXin Li   auto WorkingDir = getCurrentWorkingDirectory();
109*67e74705SXin Li   if (!WorkingDir)
110*67e74705SXin Li     return WorkingDir.getError();
111*67e74705SXin Li 
112*67e74705SXin Li   return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
113*67e74705SXin Li }
114*67e74705SXin Li 
exists(const Twine & Path)115*67e74705SXin Li bool FileSystem::exists(const Twine &Path) {
116*67e74705SXin Li   auto Status = status(Path);
117*67e74705SXin Li   return Status && Status->exists();
118*67e74705SXin Li }
119*67e74705SXin Li 
120*67e74705SXin Li #ifndef NDEBUG
isTraversalComponent(StringRef Component)121*67e74705SXin Li static bool isTraversalComponent(StringRef Component) {
122*67e74705SXin Li   return Component.equals("..") || Component.equals(".");
123*67e74705SXin Li }
124*67e74705SXin Li 
pathHasTraversal(StringRef Path)125*67e74705SXin Li static bool pathHasTraversal(StringRef Path) {
126*67e74705SXin Li   using namespace llvm::sys;
127*67e74705SXin Li   for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
128*67e74705SXin Li     if (isTraversalComponent(Comp))
129*67e74705SXin Li       return true;
130*67e74705SXin Li   return false;
131*67e74705SXin Li }
132*67e74705SXin Li #endif
133*67e74705SXin Li 
134*67e74705SXin Li //===-----------------------------------------------------------------------===/
135*67e74705SXin Li // RealFileSystem implementation
136*67e74705SXin Li //===-----------------------------------------------------------------------===/
137*67e74705SXin Li 
138*67e74705SXin Li namespace {
139*67e74705SXin Li /// \brief Wrapper around a raw file descriptor.
140*67e74705SXin Li class RealFile : public File {
141*67e74705SXin Li   int FD;
142*67e74705SXin Li   Status S;
143*67e74705SXin Li   std::string RealName;
144*67e74705SXin Li   friend class RealFileSystem;
RealFile(int FD,StringRef NewName,StringRef NewRealPathName)145*67e74705SXin Li   RealFile(int FD, StringRef NewName, StringRef NewRealPathName)
146*67e74705SXin Li       : FD(FD), S(NewName, {}, {}, {}, {}, {},
147*67e74705SXin Li                   llvm::sys::fs::file_type::status_error, {}),
148*67e74705SXin Li         RealName(NewRealPathName.str()) {
149*67e74705SXin Li     assert(FD >= 0 && "Invalid or inactive file descriptor");
150*67e74705SXin Li   }
151*67e74705SXin Li 
152*67e74705SXin Li public:
153*67e74705SXin Li   ~RealFile() override;
154*67e74705SXin Li   ErrorOr<Status> status() override;
155*67e74705SXin Li   ErrorOr<std::string> getName() override;
156*67e74705SXin Li   ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
157*67e74705SXin Li                                                    int64_t FileSize,
158*67e74705SXin Li                                                    bool RequiresNullTerminator,
159*67e74705SXin Li                                                    bool IsVolatile) override;
160*67e74705SXin Li   std::error_code close() override;
161*67e74705SXin Li };
162*67e74705SXin Li } // end anonymous namespace
~RealFile()163*67e74705SXin Li RealFile::~RealFile() { close(); }
164*67e74705SXin Li 
status()165*67e74705SXin Li ErrorOr<Status> RealFile::status() {
166*67e74705SXin Li   assert(FD != -1 && "cannot stat closed file");
167*67e74705SXin Li   if (!S.isStatusKnown()) {
168*67e74705SXin Li     file_status RealStatus;
169*67e74705SXin Li     if (std::error_code EC = sys::fs::status(FD, RealStatus))
170*67e74705SXin Li       return EC;
171*67e74705SXin Li     S = Status::copyWithNewName(RealStatus, S.getName());
172*67e74705SXin Li   }
173*67e74705SXin Li   return S;
174*67e74705SXin Li }
175*67e74705SXin Li 
getName()176*67e74705SXin Li ErrorOr<std::string> RealFile::getName() {
177*67e74705SXin Li   return RealName.empty() ? S.getName().str() : RealName;
178*67e74705SXin Li }
179*67e74705SXin Li 
180*67e74705SXin Li ErrorOr<std::unique_ptr<MemoryBuffer>>
getBuffer(const Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)181*67e74705SXin Li RealFile::getBuffer(const Twine &Name, int64_t FileSize,
182*67e74705SXin Li                     bool RequiresNullTerminator, bool IsVolatile) {
183*67e74705SXin Li   assert(FD != -1 && "cannot get buffer for closed file");
184*67e74705SXin Li   return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
185*67e74705SXin Li                                    IsVolatile);
186*67e74705SXin Li }
187*67e74705SXin Li 
close()188*67e74705SXin Li std::error_code RealFile::close() {
189*67e74705SXin Li   std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD);
190*67e74705SXin Li   FD = -1;
191*67e74705SXin Li   return EC;
192*67e74705SXin Li }
193*67e74705SXin Li 
194*67e74705SXin Li namespace {
195*67e74705SXin Li /// \brief The file system according to your operating system.
196*67e74705SXin Li class RealFileSystem : public FileSystem {
197*67e74705SXin Li public:
198*67e74705SXin Li   ErrorOr<Status> status(const Twine &Path) override;
199*67e74705SXin Li   ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
200*67e74705SXin Li   directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
201*67e74705SXin Li 
202*67e74705SXin Li   llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
203*67e74705SXin Li   std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
204*67e74705SXin Li };
205*67e74705SXin Li } // end anonymous namespace
206*67e74705SXin Li 
status(const Twine & Path)207*67e74705SXin Li ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
208*67e74705SXin Li   sys::fs::file_status RealStatus;
209*67e74705SXin Li   if (std::error_code EC = sys::fs::status(Path, RealStatus))
210*67e74705SXin Li     return EC;
211*67e74705SXin Li   return Status::copyWithNewName(RealStatus, Path.str());
212*67e74705SXin Li }
213*67e74705SXin Li 
214*67e74705SXin Li ErrorOr<std::unique_ptr<File>>
openFileForRead(const Twine & Name)215*67e74705SXin Li RealFileSystem::openFileForRead(const Twine &Name) {
216*67e74705SXin Li   int FD;
217*67e74705SXin Li   SmallString<256> RealName;
218*67e74705SXin Li   if (std::error_code EC = sys::fs::openFileForRead(Name, FD, &RealName))
219*67e74705SXin Li     return EC;
220*67e74705SXin Li   return std::unique_ptr<File>(new RealFile(FD, Name.str(), RealName.str()));
221*67e74705SXin Li }
222*67e74705SXin Li 
getCurrentWorkingDirectory() const223*67e74705SXin Li llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
224*67e74705SXin Li   SmallString<256> Dir;
225*67e74705SXin Li   if (std::error_code EC = llvm::sys::fs::current_path(Dir))
226*67e74705SXin Li     return EC;
227*67e74705SXin Li   return Dir.str().str();
228*67e74705SXin Li }
229*67e74705SXin Li 
setCurrentWorkingDirectory(const Twine & Path)230*67e74705SXin Li std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
231*67e74705SXin Li   // FIXME: chdir is thread hostile; on the other hand, creating the same
232*67e74705SXin Li   // behavior as chdir is complex: chdir resolves the path once, thus
233*67e74705SXin Li   // guaranteeing that all subsequent relative path operations work
234*67e74705SXin Li   // on the same path the original chdir resulted in. This makes a
235*67e74705SXin Li   // difference for example on network filesystems, where symlinks might be
236*67e74705SXin Li   // switched during runtime of the tool. Fixing this depends on having a
237*67e74705SXin Li   // file system abstraction that allows openat() style interactions.
238*67e74705SXin Li   SmallString<256> Storage;
239*67e74705SXin Li   StringRef Dir = Path.toNullTerminatedStringRef(Storage);
240*67e74705SXin Li   if (int Err = ::chdir(Dir.data()))
241*67e74705SXin Li     return std::error_code(Err, std::generic_category());
242*67e74705SXin Li   return std::error_code();
243*67e74705SXin Li }
244*67e74705SXin Li 
getRealFileSystem()245*67e74705SXin Li IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
246*67e74705SXin Li   static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
247*67e74705SXin Li   return FS;
248*67e74705SXin Li }
249*67e74705SXin Li 
250*67e74705SXin Li namespace {
251*67e74705SXin Li class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
252*67e74705SXin Li   std::string Path;
253*67e74705SXin Li   llvm::sys::fs::directory_iterator Iter;
254*67e74705SXin Li public:
RealFSDirIter(const Twine & _Path,std::error_code & EC)255*67e74705SXin Li   RealFSDirIter(const Twine &_Path, std::error_code &EC)
256*67e74705SXin Li       : Path(_Path.str()), Iter(Path, EC) {
257*67e74705SXin Li     if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
258*67e74705SXin Li       llvm::sys::fs::file_status S;
259*67e74705SXin Li       EC = Iter->status(S);
260*67e74705SXin Li       if (!EC)
261*67e74705SXin Li         CurrentEntry = Status::copyWithNewName(S, Iter->path());
262*67e74705SXin Li     }
263*67e74705SXin Li   }
264*67e74705SXin Li 
increment()265*67e74705SXin Li   std::error_code increment() override {
266*67e74705SXin Li     std::error_code EC;
267*67e74705SXin Li     Iter.increment(EC);
268*67e74705SXin Li     if (EC) {
269*67e74705SXin Li       return EC;
270*67e74705SXin Li     } else if (Iter == llvm::sys::fs::directory_iterator()) {
271*67e74705SXin Li       CurrentEntry = Status();
272*67e74705SXin Li     } else {
273*67e74705SXin Li       llvm::sys::fs::file_status S;
274*67e74705SXin Li       EC = Iter->status(S);
275*67e74705SXin Li       CurrentEntry = Status::copyWithNewName(S, Iter->path());
276*67e74705SXin Li     }
277*67e74705SXin Li     return EC;
278*67e74705SXin Li   }
279*67e74705SXin Li };
280*67e74705SXin Li }
281*67e74705SXin Li 
dir_begin(const Twine & Dir,std::error_code & EC)282*67e74705SXin Li directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
283*67e74705SXin Li                                              std::error_code &EC) {
284*67e74705SXin Li   return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
285*67e74705SXin Li }
286*67e74705SXin Li 
287*67e74705SXin Li //===-----------------------------------------------------------------------===/
288*67e74705SXin Li // OverlayFileSystem implementation
289*67e74705SXin Li //===-----------------------------------------------------------------------===/
OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS)290*67e74705SXin Li OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
291*67e74705SXin Li   FSList.push_back(std::move(BaseFS));
292*67e74705SXin Li }
293*67e74705SXin Li 
pushOverlay(IntrusiveRefCntPtr<FileSystem> FS)294*67e74705SXin Li void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
295*67e74705SXin Li   FSList.push_back(FS);
296*67e74705SXin Li   // Synchronize added file systems by duplicating the working directory from
297*67e74705SXin Li   // the first one in the list.
298*67e74705SXin Li   FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
299*67e74705SXin Li }
300*67e74705SXin Li 
status(const Twine & Path)301*67e74705SXin Li ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
302*67e74705SXin Li   // FIXME: handle symlinks that cross file systems
303*67e74705SXin Li   for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
304*67e74705SXin Li     ErrorOr<Status> Status = (*I)->status(Path);
305*67e74705SXin Li     if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
306*67e74705SXin Li       return Status;
307*67e74705SXin Li   }
308*67e74705SXin Li   return make_error_code(llvm::errc::no_such_file_or_directory);
309*67e74705SXin Li }
310*67e74705SXin Li 
311*67e74705SXin Li ErrorOr<std::unique_ptr<File>>
openFileForRead(const llvm::Twine & Path)312*67e74705SXin Li OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
313*67e74705SXin Li   // FIXME: handle symlinks that cross file systems
314*67e74705SXin Li   for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
315*67e74705SXin Li     auto Result = (*I)->openFileForRead(Path);
316*67e74705SXin Li     if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
317*67e74705SXin Li       return Result;
318*67e74705SXin Li   }
319*67e74705SXin Li   return make_error_code(llvm::errc::no_such_file_or_directory);
320*67e74705SXin Li }
321*67e74705SXin Li 
322*67e74705SXin Li llvm::ErrorOr<std::string>
getCurrentWorkingDirectory() const323*67e74705SXin Li OverlayFileSystem::getCurrentWorkingDirectory() const {
324*67e74705SXin Li   // All file systems are synchronized, just take the first working directory.
325*67e74705SXin Li   return FSList.front()->getCurrentWorkingDirectory();
326*67e74705SXin Li }
327*67e74705SXin Li std::error_code
setCurrentWorkingDirectory(const Twine & Path)328*67e74705SXin Li OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
329*67e74705SXin Li   for (auto &FS : FSList)
330*67e74705SXin Li     if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
331*67e74705SXin Li       return EC;
332*67e74705SXin Li   return std::error_code();
333*67e74705SXin Li }
334*67e74705SXin Li 
~DirIterImpl()335*67e74705SXin Li clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
336*67e74705SXin Li 
337*67e74705SXin Li namespace {
338*67e74705SXin Li class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
339*67e74705SXin Li   OverlayFileSystem &Overlays;
340*67e74705SXin Li   std::string Path;
341*67e74705SXin Li   OverlayFileSystem::iterator CurrentFS;
342*67e74705SXin Li   directory_iterator CurrentDirIter;
343*67e74705SXin Li   llvm::StringSet<> SeenNames;
344*67e74705SXin Li 
incrementFS()345*67e74705SXin Li   std::error_code incrementFS() {
346*67e74705SXin Li     assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
347*67e74705SXin Li     ++CurrentFS;
348*67e74705SXin Li     for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
349*67e74705SXin Li       std::error_code EC;
350*67e74705SXin Li       CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
351*67e74705SXin Li       if (EC && EC != errc::no_such_file_or_directory)
352*67e74705SXin Li         return EC;
353*67e74705SXin Li       if (CurrentDirIter != directory_iterator())
354*67e74705SXin Li         break; // found
355*67e74705SXin Li     }
356*67e74705SXin Li     return std::error_code();
357*67e74705SXin Li   }
358*67e74705SXin Li 
incrementDirIter(bool IsFirstTime)359*67e74705SXin Li   std::error_code incrementDirIter(bool IsFirstTime) {
360*67e74705SXin Li     assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
361*67e74705SXin Li            "incrementing past end");
362*67e74705SXin Li     std::error_code EC;
363*67e74705SXin Li     if (!IsFirstTime)
364*67e74705SXin Li       CurrentDirIter.increment(EC);
365*67e74705SXin Li     if (!EC && CurrentDirIter == directory_iterator())
366*67e74705SXin Li       EC = incrementFS();
367*67e74705SXin Li     return EC;
368*67e74705SXin Li   }
369*67e74705SXin Li 
incrementImpl(bool IsFirstTime)370*67e74705SXin Li   std::error_code incrementImpl(bool IsFirstTime) {
371*67e74705SXin Li     while (true) {
372*67e74705SXin Li       std::error_code EC = incrementDirIter(IsFirstTime);
373*67e74705SXin Li       if (EC || CurrentDirIter == directory_iterator()) {
374*67e74705SXin Li         CurrentEntry = Status();
375*67e74705SXin Li         return EC;
376*67e74705SXin Li       }
377*67e74705SXin Li       CurrentEntry = *CurrentDirIter;
378*67e74705SXin Li       StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
379*67e74705SXin Li       if (SeenNames.insert(Name).second)
380*67e74705SXin Li         return EC; // name not seen before
381*67e74705SXin Li     }
382*67e74705SXin Li     llvm_unreachable("returned above");
383*67e74705SXin Li   }
384*67e74705SXin Li 
385*67e74705SXin Li public:
OverlayFSDirIterImpl(const Twine & Path,OverlayFileSystem & FS,std::error_code & EC)386*67e74705SXin Li   OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
387*67e74705SXin Li                        std::error_code &EC)
388*67e74705SXin Li       : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
389*67e74705SXin Li     CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
390*67e74705SXin Li     EC = incrementImpl(true);
391*67e74705SXin Li   }
392*67e74705SXin Li 
increment()393*67e74705SXin Li   std::error_code increment() override { return incrementImpl(false); }
394*67e74705SXin Li };
395*67e74705SXin Li } // end anonymous namespace
396*67e74705SXin Li 
dir_begin(const Twine & Dir,std::error_code & EC)397*67e74705SXin Li directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
398*67e74705SXin Li                                                 std::error_code &EC) {
399*67e74705SXin Li   return directory_iterator(
400*67e74705SXin Li       std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
401*67e74705SXin Li }
402*67e74705SXin Li 
403*67e74705SXin Li namespace clang {
404*67e74705SXin Li namespace vfs {
405*67e74705SXin Li namespace detail {
406*67e74705SXin Li 
407*67e74705SXin Li enum InMemoryNodeKind { IME_File, IME_Directory };
408*67e74705SXin Li 
409*67e74705SXin Li /// The in memory file system is a tree of Nodes. Every node can either be a
410*67e74705SXin Li /// file or a directory.
411*67e74705SXin Li class InMemoryNode {
412*67e74705SXin Li   Status Stat;
413*67e74705SXin Li   InMemoryNodeKind Kind;
414*67e74705SXin Li 
415*67e74705SXin Li public:
InMemoryNode(Status Stat,InMemoryNodeKind Kind)416*67e74705SXin Li   InMemoryNode(Status Stat, InMemoryNodeKind Kind)
417*67e74705SXin Li       : Stat(std::move(Stat)), Kind(Kind) {}
~InMemoryNode()418*67e74705SXin Li   virtual ~InMemoryNode() {}
getStatus() const419*67e74705SXin Li   const Status &getStatus() const { return Stat; }
getKind() const420*67e74705SXin Li   InMemoryNodeKind getKind() const { return Kind; }
421*67e74705SXin Li   virtual std::string toString(unsigned Indent) const = 0;
422*67e74705SXin Li };
423*67e74705SXin Li 
424*67e74705SXin Li namespace {
425*67e74705SXin Li class InMemoryFile : public InMemoryNode {
426*67e74705SXin Li   std::unique_ptr<llvm::MemoryBuffer> Buffer;
427*67e74705SXin Li 
428*67e74705SXin Li public:
InMemoryFile(Status Stat,std::unique_ptr<llvm::MemoryBuffer> Buffer)429*67e74705SXin Li   InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
430*67e74705SXin Li       : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
431*67e74705SXin Li 
getBuffer()432*67e74705SXin Li   llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
toString(unsigned Indent) const433*67e74705SXin Li   std::string toString(unsigned Indent) const override {
434*67e74705SXin Li     return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
435*67e74705SXin Li   }
classof(const InMemoryNode * N)436*67e74705SXin Li   static bool classof(const InMemoryNode *N) {
437*67e74705SXin Li     return N->getKind() == IME_File;
438*67e74705SXin Li   }
439*67e74705SXin Li };
440*67e74705SXin Li 
441*67e74705SXin Li /// Adapt a InMemoryFile for VFS' File interface.
442*67e74705SXin Li class InMemoryFileAdaptor : public File {
443*67e74705SXin Li   InMemoryFile &Node;
444*67e74705SXin Li 
445*67e74705SXin Li public:
InMemoryFileAdaptor(InMemoryFile & Node)446*67e74705SXin Li   explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
447*67e74705SXin Li 
status()448*67e74705SXin Li   llvm::ErrorOr<Status> status() override { return Node.getStatus(); }
449*67e74705SXin Li   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
getBuffer(const Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)450*67e74705SXin Li   getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
451*67e74705SXin Li             bool IsVolatile) override {
452*67e74705SXin Li     llvm::MemoryBuffer *Buf = Node.getBuffer();
453*67e74705SXin Li     return llvm::MemoryBuffer::getMemBuffer(
454*67e74705SXin Li         Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
455*67e74705SXin Li   }
close()456*67e74705SXin Li   std::error_code close() override { return std::error_code(); }
457*67e74705SXin Li };
458*67e74705SXin Li } // end anonymous namespace
459*67e74705SXin Li 
460*67e74705SXin Li class InMemoryDirectory : public InMemoryNode {
461*67e74705SXin Li   std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
462*67e74705SXin Li 
463*67e74705SXin Li public:
InMemoryDirectory(Status Stat)464*67e74705SXin Li   InMemoryDirectory(Status Stat)
465*67e74705SXin Li       : InMemoryNode(std::move(Stat), IME_Directory) {}
getChild(StringRef Name)466*67e74705SXin Li   InMemoryNode *getChild(StringRef Name) {
467*67e74705SXin Li     auto I = Entries.find(Name);
468*67e74705SXin Li     if (I != Entries.end())
469*67e74705SXin Li       return I->second.get();
470*67e74705SXin Li     return nullptr;
471*67e74705SXin Li   }
addChild(StringRef Name,std::unique_ptr<InMemoryNode> Child)472*67e74705SXin Li   InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
473*67e74705SXin Li     return Entries.insert(make_pair(Name, std::move(Child)))
474*67e74705SXin Li         .first->second.get();
475*67e74705SXin Li   }
476*67e74705SXin Li 
477*67e74705SXin Li   typedef decltype(Entries)::const_iterator const_iterator;
begin() const478*67e74705SXin Li   const_iterator begin() const { return Entries.begin(); }
end() const479*67e74705SXin Li   const_iterator end() const { return Entries.end(); }
480*67e74705SXin Li 
toString(unsigned Indent) const481*67e74705SXin Li   std::string toString(unsigned Indent) const override {
482*67e74705SXin Li     std::string Result =
483*67e74705SXin Li         (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
484*67e74705SXin Li     for (const auto &Entry : Entries) {
485*67e74705SXin Li       Result += Entry.second->toString(Indent + 2);
486*67e74705SXin Li     }
487*67e74705SXin Li     return Result;
488*67e74705SXin Li   }
classof(const InMemoryNode * N)489*67e74705SXin Li   static bool classof(const InMemoryNode *N) {
490*67e74705SXin Li     return N->getKind() == IME_Directory;
491*67e74705SXin Li   }
492*67e74705SXin Li };
493*67e74705SXin Li }
494*67e74705SXin Li 
InMemoryFileSystem(bool UseNormalizedPaths)495*67e74705SXin Li InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
496*67e74705SXin Li     : Root(new detail::InMemoryDirectory(
497*67e74705SXin Li           Status("", getNextVirtualUniqueID(), llvm::sys::TimeValue::MinTime(),
498*67e74705SXin Li                  0, 0, 0, llvm::sys::fs::file_type::directory_file,
499*67e74705SXin Li                  llvm::sys::fs::perms::all_all))),
500*67e74705SXin Li       UseNormalizedPaths(UseNormalizedPaths) {}
501*67e74705SXin Li 
~InMemoryFileSystem()502*67e74705SXin Li InMemoryFileSystem::~InMemoryFileSystem() {}
503*67e74705SXin Li 
toString() const504*67e74705SXin Li std::string InMemoryFileSystem::toString() const {
505*67e74705SXin Li   return Root->toString(/*Indent=*/0);
506*67e74705SXin Li }
507*67e74705SXin Li 
addFile(const Twine & P,time_t ModificationTime,std::unique_ptr<llvm::MemoryBuffer> Buffer)508*67e74705SXin Li bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
509*67e74705SXin Li                                  std::unique_ptr<llvm::MemoryBuffer> Buffer) {
510*67e74705SXin Li   SmallString<128> Path;
511*67e74705SXin Li   P.toVector(Path);
512*67e74705SXin Li 
513*67e74705SXin Li   // Fix up relative paths. This just prepends the current working directory.
514*67e74705SXin Li   std::error_code EC = makeAbsolute(Path);
515*67e74705SXin Li   assert(!EC);
516*67e74705SXin Li   (void)EC;
517*67e74705SXin Li 
518*67e74705SXin Li   if (useNormalizedPaths())
519*67e74705SXin Li     llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
520*67e74705SXin Li 
521*67e74705SXin Li   if (Path.empty())
522*67e74705SXin Li     return false;
523*67e74705SXin Li 
524*67e74705SXin Li   detail::InMemoryDirectory *Dir = Root.get();
525*67e74705SXin Li   auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
526*67e74705SXin Li   while (true) {
527*67e74705SXin Li     StringRef Name = *I;
528*67e74705SXin Li     detail::InMemoryNode *Node = Dir->getChild(Name);
529*67e74705SXin Li     ++I;
530*67e74705SXin Li     if (!Node) {
531*67e74705SXin Li       if (I == E) {
532*67e74705SXin Li         // End of the path, create a new file.
533*67e74705SXin Li         // FIXME: expose the status details in the interface.
534*67e74705SXin Li         Status Stat(P.str(), getNextVirtualUniqueID(),
535*67e74705SXin Li                     llvm::sys::TimeValue(ModificationTime, 0), 0, 0,
536*67e74705SXin Li                     Buffer->getBufferSize(),
537*67e74705SXin Li                     llvm::sys::fs::file_type::regular_file,
538*67e74705SXin Li                     llvm::sys::fs::all_all);
539*67e74705SXin Li         Dir->addChild(Name, llvm::make_unique<detail::InMemoryFile>(
540*67e74705SXin Li                                 std::move(Stat), std::move(Buffer)));
541*67e74705SXin Li         return true;
542*67e74705SXin Li       }
543*67e74705SXin Li 
544*67e74705SXin Li       // Create a new directory. Use the path up to here.
545*67e74705SXin Li       // FIXME: expose the status details in the interface.
546*67e74705SXin Li       Status Stat(
547*67e74705SXin Li           StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
548*67e74705SXin Li           getNextVirtualUniqueID(), llvm::sys::TimeValue(ModificationTime, 0),
549*67e74705SXin Li           0, 0, Buffer->getBufferSize(),
550*67e74705SXin Li           llvm::sys::fs::file_type::directory_file, llvm::sys::fs::all_all);
551*67e74705SXin Li       Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
552*67e74705SXin Li           Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
553*67e74705SXin Li       continue;
554*67e74705SXin Li     }
555*67e74705SXin Li 
556*67e74705SXin Li     if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
557*67e74705SXin Li       Dir = NewDir;
558*67e74705SXin Li     } else {
559*67e74705SXin Li       assert(isa<detail::InMemoryFile>(Node) &&
560*67e74705SXin Li              "Must be either file or directory!");
561*67e74705SXin Li 
562*67e74705SXin Li       // Trying to insert a directory in place of a file.
563*67e74705SXin Li       if (I != E)
564*67e74705SXin Li         return false;
565*67e74705SXin Li 
566*67e74705SXin Li       // Return false only if the new file is different from the existing one.
567*67e74705SXin Li       return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
568*67e74705SXin Li              Buffer->getBuffer();
569*67e74705SXin Li     }
570*67e74705SXin Li   }
571*67e74705SXin Li }
572*67e74705SXin Li 
addFileNoOwn(const Twine & P,time_t ModificationTime,llvm::MemoryBuffer * Buffer)573*67e74705SXin Li bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
574*67e74705SXin Li                                       llvm::MemoryBuffer *Buffer) {
575*67e74705SXin Li   return addFile(P, ModificationTime,
576*67e74705SXin Li                  llvm::MemoryBuffer::getMemBuffer(
577*67e74705SXin Li                      Buffer->getBuffer(), Buffer->getBufferIdentifier()));
578*67e74705SXin Li }
579*67e74705SXin Li 
580*67e74705SXin Li static ErrorOr<detail::InMemoryNode *>
lookupInMemoryNode(const InMemoryFileSystem & FS,detail::InMemoryDirectory * Dir,const Twine & P)581*67e74705SXin Li lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
582*67e74705SXin Li                    const Twine &P) {
583*67e74705SXin Li   SmallString<128> Path;
584*67e74705SXin Li   P.toVector(Path);
585*67e74705SXin Li 
586*67e74705SXin Li   // Fix up relative paths. This just prepends the current working directory.
587*67e74705SXin Li   std::error_code EC = FS.makeAbsolute(Path);
588*67e74705SXin Li   assert(!EC);
589*67e74705SXin Li   (void)EC;
590*67e74705SXin Li 
591*67e74705SXin Li   if (FS.useNormalizedPaths())
592*67e74705SXin Li     llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
593*67e74705SXin Li 
594*67e74705SXin Li   if (Path.empty())
595*67e74705SXin Li     return Dir;
596*67e74705SXin Li 
597*67e74705SXin Li   auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
598*67e74705SXin Li   while (true) {
599*67e74705SXin Li     detail::InMemoryNode *Node = Dir->getChild(*I);
600*67e74705SXin Li     ++I;
601*67e74705SXin Li     if (!Node)
602*67e74705SXin Li       return errc::no_such_file_or_directory;
603*67e74705SXin Li 
604*67e74705SXin Li     // Return the file if it's at the end of the path.
605*67e74705SXin Li     if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
606*67e74705SXin Li       if (I == E)
607*67e74705SXin Li         return File;
608*67e74705SXin Li       return errc::no_such_file_or_directory;
609*67e74705SXin Li     }
610*67e74705SXin Li 
611*67e74705SXin Li     // Traverse directories.
612*67e74705SXin Li     Dir = cast<detail::InMemoryDirectory>(Node);
613*67e74705SXin Li     if (I == E)
614*67e74705SXin Li       return Dir;
615*67e74705SXin Li   }
616*67e74705SXin Li }
617*67e74705SXin Li 
status(const Twine & Path)618*67e74705SXin Li llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
619*67e74705SXin Li   auto Node = lookupInMemoryNode(*this, Root.get(), Path);
620*67e74705SXin Li   if (Node)
621*67e74705SXin Li     return (*Node)->getStatus();
622*67e74705SXin Li   return Node.getError();
623*67e74705SXin Li }
624*67e74705SXin Li 
625*67e74705SXin Li llvm::ErrorOr<std::unique_ptr<File>>
openFileForRead(const Twine & Path)626*67e74705SXin Li InMemoryFileSystem::openFileForRead(const Twine &Path) {
627*67e74705SXin Li   auto Node = lookupInMemoryNode(*this, Root.get(), Path);
628*67e74705SXin Li   if (!Node)
629*67e74705SXin Li     return Node.getError();
630*67e74705SXin Li 
631*67e74705SXin Li   // When we have a file provide a heap-allocated wrapper for the memory buffer
632*67e74705SXin Li   // to match the ownership semantics for File.
633*67e74705SXin Li   if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
634*67e74705SXin Li     return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
635*67e74705SXin Li 
636*67e74705SXin Li   // FIXME: errc::not_a_file?
637*67e74705SXin Li   return make_error_code(llvm::errc::invalid_argument);
638*67e74705SXin Li }
639*67e74705SXin Li 
640*67e74705SXin Li namespace {
641*67e74705SXin Li /// Adaptor from InMemoryDir::iterator to directory_iterator.
642*67e74705SXin Li class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
643*67e74705SXin Li   detail::InMemoryDirectory::const_iterator I;
644*67e74705SXin Li   detail::InMemoryDirectory::const_iterator E;
645*67e74705SXin Li 
646*67e74705SXin Li public:
InMemoryDirIterator()647*67e74705SXin Li   InMemoryDirIterator() {}
InMemoryDirIterator(detail::InMemoryDirectory & Dir)648*67e74705SXin Li   explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
649*67e74705SXin Li       : I(Dir.begin()), E(Dir.end()) {
650*67e74705SXin Li     if (I != E)
651*67e74705SXin Li       CurrentEntry = I->second->getStatus();
652*67e74705SXin Li   }
653*67e74705SXin Li 
increment()654*67e74705SXin Li   std::error_code increment() override {
655*67e74705SXin Li     ++I;
656*67e74705SXin Li     // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
657*67e74705SXin Li     // the rest.
658*67e74705SXin Li     CurrentEntry = I != E ? I->second->getStatus() : Status();
659*67e74705SXin Li     return std::error_code();
660*67e74705SXin Li   }
661*67e74705SXin Li };
662*67e74705SXin Li } // end anonymous namespace
663*67e74705SXin Li 
dir_begin(const Twine & Dir,std::error_code & EC)664*67e74705SXin Li directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
665*67e74705SXin Li                                                  std::error_code &EC) {
666*67e74705SXin Li   auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
667*67e74705SXin Li   if (!Node) {
668*67e74705SXin Li     EC = Node.getError();
669*67e74705SXin Li     return directory_iterator(std::make_shared<InMemoryDirIterator>());
670*67e74705SXin Li   }
671*67e74705SXin Li 
672*67e74705SXin Li   if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
673*67e74705SXin Li     return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
674*67e74705SXin Li 
675*67e74705SXin Li   EC = make_error_code(llvm::errc::not_a_directory);
676*67e74705SXin Li   return directory_iterator(std::make_shared<InMemoryDirIterator>());
677*67e74705SXin Li }
678*67e74705SXin Li 
setCurrentWorkingDirectory(const Twine & P)679*67e74705SXin Li std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
680*67e74705SXin Li   SmallString<128> Path;
681*67e74705SXin Li   P.toVector(Path);
682*67e74705SXin Li 
683*67e74705SXin Li   // Fix up relative paths. This just prepends the current working directory.
684*67e74705SXin Li   std::error_code EC = makeAbsolute(Path);
685*67e74705SXin Li   assert(!EC);
686*67e74705SXin Li   (void)EC;
687*67e74705SXin Li 
688*67e74705SXin Li   if (useNormalizedPaths())
689*67e74705SXin Li     llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
690*67e74705SXin Li 
691*67e74705SXin Li   if (!Path.empty())
692*67e74705SXin Li     WorkingDirectory = Path.str();
693*67e74705SXin Li   return std::error_code();
694*67e74705SXin Li }
695*67e74705SXin Li }
696*67e74705SXin Li }
697*67e74705SXin Li 
698*67e74705SXin Li //===-----------------------------------------------------------------------===/
699*67e74705SXin Li // RedirectingFileSystem implementation
700*67e74705SXin Li //===-----------------------------------------------------------------------===/
701*67e74705SXin Li 
702*67e74705SXin Li namespace {
703*67e74705SXin Li 
704*67e74705SXin Li enum EntryKind {
705*67e74705SXin Li   EK_Directory,
706*67e74705SXin Li   EK_File
707*67e74705SXin Li };
708*67e74705SXin Li 
709*67e74705SXin Li /// \brief A single file or directory in the VFS.
710*67e74705SXin Li class Entry {
711*67e74705SXin Li   EntryKind Kind;
712*67e74705SXin Li   std::string Name;
713*67e74705SXin Li 
714*67e74705SXin Li public:
715*67e74705SXin Li   virtual ~Entry();
Entry(EntryKind K,StringRef Name)716*67e74705SXin Li   Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
getName() const717*67e74705SXin Li   StringRef getName() const { return Name; }
getKind() const718*67e74705SXin Li   EntryKind getKind() const { return Kind; }
719*67e74705SXin Li };
720*67e74705SXin Li 
721*67e74705SXin Li class RedirectingDirectoryEntry : public Entry {
722*67e74705SXin Li   std::vector<std::unique_ptr<Entry>> Contents;
723*67e74705SXin Li   Status S;
724*67e74705SXin Li 
725*67e74705SXin Li public:
RedirectingDirectoryEntry(StringRef Name,std::vector<std::unique_ptr<Entry>> Contents,Status S)726*67e74705SXin Li   RedirectingDirectoryEntry(StringRef Name,
727*67e74705SXin Li                             std::vector<std::unique_ptr<Entry>> Contents,
728*67e74705SXin Li                             Status S)
729*67e74705SXin Li       : Entry(EK_Directory, Name), Contents(std::move(Contents)),
730*67e74705SXin Li         S(std::move(S)) {}
RedirectingDirectoryEntry(StringRef Name,Status S)731*67e74705SXin Li   RedirectingDirectoryEntry(StringRef Name, Status S)
732*67e74705SXin Li       : Entry(EK_Directory, Name), S(std::move(S)) {}
getStatus()733*67e74705SXin Li   Status getStatus() { return S; }
addContent(std::unique_ptr<Entry> Content)734*67e74705SXin Li   void addContent(std::unique_ptr<Entry> Content) {
735*67e74705SXin Li     Contents.push_back(std::move(Content));
736*67e74705SXin Li   }
getLastContent() const737*67e74705SXin Li   Entry *getLastContent() const { return Contents.back().get(); }
738*67e74705SXin Li   typedef decltype(Contents)::iterator iterator;
contents_begin()739*67e74705SXin Li   iterator contents_begin() { return Contents.begin(); }
contents_end()740*67e74705SXin Li   iterator contents_end() { return Contents.end(); }
classof(const Entry * E)741*67e74705SXin Li   static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
742*67e74705SXin Li };
743*67e74705SXin Li 
744*67e74705SXin Li class RedirectingFileEntry : public Entry {
745*67e74705SXin Li public:
746*67e74705SXin Li   enum NameKind {
747*67e74705SXin Li     NK_NotSet,
748*67e74705SXin Li     NK_External,
749*67e74705SXin Li     NK_Virtual
750*67e74705SXin Li   };
751*67e74705SXin Li private:
752*67e74705SXin Li   std::string ExternalContentsPath;
753*67e74705SXin Li   NameKind UseName;
754*67e74705SXin Li public:
RedirectingFileEntry(StringRef Name,StringRef ExternalContentsPath,NameKind UseName)755*67e74705SXin Li   RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
756*67e74705SXin Li                        NameKind UseName)
757*67e74705SXin Li       : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
758*67e74705SXin Li         UseName(UseName) {}
getExternalContentsPath() const759*67e74705SXin Li   StringRef getExternalContentsPath() const { return ExternalContentsPath; }
760*67e74705SXin Li   /// \brief whether to use the external path as the name for this file.
useExternalName(bool GlobalUseExternalName) const761*67e74705SXin Li   bool useExternalName(bool GlobalUseExternalName) const {
762*67e74705SXin Li     return UseName == NK_NotSet ? GlobalUseExternalName
763*67e74705SXin Li                                 : (UseName == NK_External);
764*67e74705SXin Li   }
getUseName() const765*67e74705SXin Li   NameKind getUseName() const { return UseName; }
classof(const Entry * E)766*67e74705SXin Li   static bool classof(const Entry *E) { return E->getKind() == EK_File; }
767*67e74705SXin Li };
768*67e74705SXin Li 
769*67e74705SXin Li class RedirectingFileSystem;
770*67e74705SXin Li 
771*67e74705SXin Li class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
772*67e74705SXin Li   std::string Dir;
773*67e74705SXin Li   RedirectingFileSystem &FS;
774*67e74705SXin Li   RedirectingDirectoryEntry::iterator Current, End;
775*67e74705SXin Li 
776*67e74705SXin Li public:
777*67e74705SXin Li   VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
778*67e74705SXin Li                          RedirectingDirectoryEntry::iterator Begin,
779*67e74705SXin Li                          RedirectingDirectoryEntry::iterator End,
780*67e74705SXin Li                          std::error_code &EC);
781*67e74705SXin Li   std::error_code increment() override;
782*67e74705SXin Li };
783*67e74705SXin Li 
784*67e74705SXin Li /// \brief A virtual file system parsed from a YAML file.
785*67e74705SXin Li ///
786*67e74705SXin Li /// Currently, this class allows creating virtual directories and mapping
787*67e74705SXin Li /// virtual file paths to existing external files, available in \c ExternalFS.
788*67e74705SXin Li ///
789*67e74705SXin Li /// The basic structure of the parsed file is:
790*67e74705SXin Li /// \verbatim
791*67e74705SXin Li /// {
792*67e74705SXin Li ///   'version': <version number>,
793*67e74705SXin Li ///   <optional configuration>
794*67e74705SXin Li ///   'roots': [
795*67e74705SXin Li ///              <directory entries>
796*67e74705SXin Li ///            ]
797*67e74705SXin Li /// }
798*67e74705SXin Li /// \endverbatim
799*67e74705SXin Li ///
800*67e74705SXin Li /// All configuration options are optional.
801*67e74705SXin Li ///   'case-sensitive': <boolean, default=true>
802*67e74705SXin Li ///   'use-external-names': <boolean, default=true>
803*67e74705SXin Li ///   'overlay-relative': <boolean, default=false>
804*67e74705SXin Li ///
805*67e74705SXin Li /// Virtual directories are represented as
806*67e74705SXin Li /// \verbatim
807*67e74705SXin Li /// {
808*67e74705SXin Li ///   'type': 'directory',
809*67e74705SXin Li ///   'name': <string>,
810*67e74705SXin Li ///   'contents': [ <file or directory entries> ]
811*67e74705SXin Li /// }
812*67e74705SXin Li /// \endverbatim
813*67e74705SXin Li ///
814*67e74705SXin Li /// The default attributes for virtual directories are:
815*67e74705SXin Li /// \verbatim
816*67e74705SXin Li /// MTime = now() when created
817*67e74705SXin Li /// Perms = 0777
818*67e74705SXin Li /// User = Group = 0
819*67e74705SXin Li /// Size = 0
820*67e74705SXin Li /// UniqueID = unspecified unique value
821*67e74705SXin Li /// \endverbatim
822*67e74705SXin Li ///
823*67e74705SXin Li /// Re-mapped files are represented as
824*67e74705SXin Li /// \verbatim
825*67e74705SXin Li /// {
826*67e74705SXin Li ///   'type': 'file',
827*67e74705SXin Li ///   'name': <string>,
828*67e74705SXin Li ///   'use-external-name': <boolean> # Optional
829*67e74705SXin Li ///   'external-contents': <path to external file>)
830*67e74705SXin Li /// }
831*67e74705SXin Li /// \endverbatim
832*67e74705SXin Li ///
833*67e74705SXin Li /// and inherit their attributes from the external contents.
834*67e74705SXin Li ///
835*67e74705SXin Li /// In both cases, the 'name' field may contain multiple path components (e.g.
836*67e74705SXin Li /// /path/to/file). However, any directory that contains more than one child
837*67e74705SXin Li /// must be uniquely represented by a directory entry.
838*67e74705SXin Li class RedirectingFileSystem : public vfs::FileSystem {
839*67e74705SXin Li   /// The root(s) of the virtual file system.
840*67e74705SXin Li   std::vector<std::unique_ptr<Entry>> Roots;
841*67e74705SXin Li   /// \brief The file system to use for external references.
842*67e74705SXin Li   IntrusiveRefCntPtr<FileSystem> ExternalFS;
843*67e74705SXin Li   /// If IsRelativeOverlay is set, this represents the directory
844*67e74705SXin Li   /// path that should be prefixed to each 'external-contents' entry
845*67e74705SXin Li   /// when reading from YAML files.
846*67e74705SXin Li   std::string ExternalContentsPrefixDir;
847*67e74705SXin Li 
848*67e74705SXin Li   /// @name Configuration
849*67e74705SXin Li   /// @{
850*67e74705SXin Li 
851*67e74705SXin Li   /// \brief Whether to perform case-sensitive comparisons.
852*67e74705SXin Li   ///
853*67e74705SXin Li   /// Currently, case-insensitive matching only works correctly with ASCII.
854*67e74705SXin Li   bool CaseSensitive = true;
855*67e74705SXin Li 
856*67e74705SXin Li   /// IsRelativeOverlay marks whether a IsExternalContentsPrefixDir path must
857*67e74705SXin Li   /// be prefixed in every 'external-contents' when reading from YAML files.
858*67e74705SXin Li   bool IsRelativeOverlay = false;
859*67e74705SXin Li 
860*67e74705SXin Li   /// \brief Whether to use to use the value of 'external-contents' for the
861*67e74705SXin Li   /// names of files.  This global value is overridable on a per-file basis.
862*67e74705SXin Li   bool UseExternalNames = true;
863*67e74705SXin Li   /// @}
864*67e74705SXin Li 
865*67e74705SXin Li   /// Virtual file paths and external files could be canonicalized without "..",
866*67e74705SXin Li   /// "." and "./" in their paths. FIXME: some unittests currently fail on
867*67e74705SXin Li   /// win32 when using remove_dots and remove_leading_dotslash on paths.
868*67e74705SXin Li   bool UseCanonicalizedPaths =
869*67e74705SXin Li #ifdef LLVM_ON_WIN32
870*67e74705SXin Li       false;
871*67e74705SXin Li #else
872*67e74705SXin Li       true;
873*67e74705SXin Li #endif
874*67e74705SXin Li 
875*67e74705SXin Li   friend class RedirectingFileSystemParser;
876*67e74705SXin Li 
877*67e74705SXin Li private:
RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)878*67e74705SXin Li   RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
879*67e74705SXin Li       : ExternalFS(std::move(ExternalFS)) {}
880*67e74705SXin Li 
881*67e74705SXin Li   /// \brief Looks up \p Path in \c Roots.
882*67e74705SXin Li   ErrorOr<Entry *> lookupPath(const Twine &Path);
883*67e74705SXin Li 
884*67e74705SXin Li   /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
885*67e74705SXin Li   /// recursing into the contents of \p From if it is a directory.
886*67e74705SXin Li   ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
887*67e74705SXin Li                               sys::path::const_iterator End, Entry *From);
888*67e74705SXin Li 
889*67e74705SXin Li   /// \brief Get the status of a given an \c Entry.
890*67e74705SXin Li   ErrorOr<Status> status(const Twine &Path, Entry *E);
891*67e74705SXin Li 
892*67e74705SXin Li public:
893*67e74705SXin Li   /// \brief Parses \p Buffer, which is expected to be in YAML format and
894*67e74705SXin Li   /// returns a virtual file system representing its contents.
895*67e74705SXin Li   static RedirectingFileSystem *
896*67e74705SXin Li   create(std::unique_ptr<MemoryBuffer> Buffer,
897*67e74705SXin Li          SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
898*67e74705SXin Li          void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
899*67e74705SXin Li 
900*67e74705SXin Li   ErrorOr<Status> status(const Twine &Path) override;
901*67e74705SXin Li   ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
902*67e74705SXin Li 
getCurrentWorkingDirectory() const903*67e74705SXin Li   llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
904*67e74705SXin Li     return ExternalFS->getCurrentWorkingDirectory();
905*67e74705SXin Li   }
setCurrentWorkingDirectory(const Twine & Path)906*67e74705SXin Li   std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
907*67e74705SXin Li     return ExternalFS->setCurrentWorkingDirectory(Path);
908*67e74705SXin Li   }
909*67e74705SXin Li 
dir_begin(const Twine & Dir,std::error_code & EC)910*67e74705SXin Li   directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
911*67e74705SXin Li     ErrorOr<Entry *> E = lookupPath(Dir);
912*67e74705SXin Li     if (!E) {
913*67e74705SXin Li       EC = E.getError();
914*67e74705SXin Li       return directory_iterator();
915*67e74705SXin Li     }
916*67e74705SXin Li     ErrorOr<Status> S = status(Dir, *E);
917*67e74705SXin Li     if (!S) {
918*67e74705SXin Li       EC = S.getError();
919*67e74705SXin Li       return directory_iterator();
920*67e74705SXin Li     }
921*67e74705SXin Li     if (!S->isDirectory()) {
922*67e74705SXin Li       EC = std::error_code(static_cast<int>(errc::not_a_directory),
923*67e74705SXin Li                            std::system_category());
924*67e74705SXin Li       return directory_iterator();
925*67e74705SXin Li     }
926*67e74705SXin Li 
927*67e74705SXin Li     auto *D = cast<RedirectingDirectoryEntry>(*E);
928*67e74705SXin Li     return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
929*67e74705SXin Li         *this, D->contents_begin(), D->contents_end(), EC));
930*67e74705SXin Li   }
931*67e74705SXin Li 
setExternalContentsPrefixDir(StringRef PrefixDir)932*67e74705SXin Li   void setExternalContentsPrefixDir(StringRef PrefixDir) {
933*67e74705SXin Li     ExternalContentsPrefixDir = PrefixDir.str();
934*67e74705SXin Li   }
935*67e74705SXin Li 
getExternalContentsPrefixDir() const936*67e74705SXin Li   StringRef getExternalContentsPrefixDir() const {
937*67e74705SXin Li     return ExternalContentsPrefixDir;
938*67e74705SXin Li   }
939*67e74705SXin Li 
940*67e74705SXin Li #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const941*67e74705SXin Li LLVM_DUMP_METHOD void dump() const {
942*67e74705SXin Li     for (const std::unique_ptr<Entry> &Root : Roots)
943*67e74705SXin Li       dumpEntry(Root.get());
944*67e74705SXin Li   }
945*67e74705SXin Li 
dumpEntry(Entry * E,int NumSpaces=0) const946*67e74705SXin Li LLVM_DUMP_METHOD void dumpEntry(Entry *E, int NumSpaces = 0) const {
947*67e74705SXin Li     StringRef Name = E->getName();
948*67e74705SXin Li     for (int i = 0, e = NumSpaces; i < e; ++i)
949*67e74705SXin Li       dbgs() << " ";
950*67e74705SXin Li     dbgs() << "'" << Name.str().c_str() << "'" << "\n";
951*67e74705SXin Li 
952*67e74705SXin Li     if (E->getKind() == EK_Directory) {
953*67e74705SXin Li       auto *DE = dyn_cast<RedirectingDirectoryEntry>(E);
954*67e74705SXin Li       assert(DE && "Should be a directory");
955*67e74705SXin Li 
956*67e74705SXin Li       for (std::unique_ptr<Entry> &SubEntry :
957*67e74705SXin Li            llvm::make_range(DE->contents_begin(), DE->contents_end()))
958*67e74705SXin Li         dumpEntry(SubEntry.get(), NumSpaces+2);
959*67e74705SXin Li     }
960*67e74705SXin Li   }
961*67e74705SXin Li #endif
962*67e74705SXin Li 
963*67e74705SXin Li };
964*67e74705SXin Li 
965*67e74705SXin Li /// \brief A helper class to hold the common YAML parsing state.
966*67e74705SXin Li class RedirectingFileSystemParser {
967*67e74705SXin Li   yaml::Stream &Stream;
968*67e74705SXin Li 
error(yaml::Node * N,const Twine & Msg)969*67e74705SXin Li   void error(yaml::Node *N, const Twine &Msg) {
970*67e74705SXin Li     Stream.printError(N, Msg);
971*67e74705SXin Li   }
972*67e74705SXin Li 
973*67e74705SXin Li   // false on error
parseScalarString(yaml::Node * N,StringRef & Result,SmallVectorImpl<char> & Storage)974*67e74705SXin Li   bool parseScalarString(yaml::Node *N, StringRef &Result,
975*67e74705SXin Li                          SmallVectorImpl<char> &Storage) {
976*67e74705SXin Li     yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
977*67e74705SXin Li     if (!S) {
978*67e74705SXin Li       error(N, "expected string");
979*67e74705SXin Li       return false;
980*67e74705SXin Li     }
981*67e74705SXin Li     Result = S->getValue(Storage);
982*67e74705SXin Li     return true;
983*67e74705SXin Li   }
984*67e74705SXin Li 
985*67e74705SXin Li   // false on error
parseScalarBool(yaml::Node * N,bool & Result)986*67e74705SXin Li   bool parseScalarBool(yaml::Node *N, bool &Result) {
987*67e74705SXin Li     SmallString<5> Storage;
988*67e74705SXin Li     StringRef Value;
989*67e74705SXin Li     if (!parseScalarString(N, Value, Storage))
990*67e74705SXin Li       return false;
991*67e74705SXin Li 
992*67e74705SXin Li     if (Value.equals_lower("true") || Value.equals_lower("on") ||
993*67e74705SXin Li         Value.equals_lower("yes") || Value == "1") {
994*67e74705SXin Li       Result = true;
995*67e74705SXin Li       return true;
996*67e74705SXin Li     } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
997*67e74705SXin Li                Value.equals_lower("no") || Value == "0") {
998*67e74705SXin Li       Result = false;
999*67e74705SXin Li       return true;
1000*67e74705SXin Li     }
1001*67e74705SXin Li 
1002*67e74705SXin Li     error(N, "expected boolean value");
1003*67e74705SXin Li     return false;
1004*67e74705SXin Li   }
1005*67e74705SXin Li 
1006*67e74705SXin Li   struct KeyStatus {
KeyStatus__anon00a5ee8f0711::RedirectingFileSystemParser::KeyStatus1007*67e74705SXin Li     KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
1008*67e74705SXin Li     bool Required;
1009*67e74705SXin Li     bool Seen;
1010*67e74705SXin Li   };
1011*67e74705SXin Li   typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
1012*67e74705SXin Li 
1013*67e74705SXin Li   // false on error
checkDuplicateOrUnknownKey(yaml::Node * KeyNode,StringRef Key,DenseMap<StringRef,KeyStatus> & Keys)1014*67e74705SXin Li   bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1015*67e74705SXin Li                                   DenseMap<StringRef, KeyStatus> &Keys) {
1016*67e74705SXin Li     if (!Keys.count(Key)) {
1017*67e74705SXin Li       error(KeyNode, "unknown key");
1018*67e74705SXin Li       return false;
1019*67e74705SXin Li     }
1020*67e74705SXin Li     KeyStatus &S = Keys[Key];
1021*67e74705SXin Li     if (S.Seen) {
1022*67e74705SXin Li       error(KeyNode, Twine("duplicate key '") + Key + "'");
1023*67e74705SXin Li       return false;
1024*67e74705SXin Li     }
1025*67e74705SXin Li     S.Seen = true;
1026*67e74705SXin Li     return true;
1027*67e74705SXin Li   }
1028*67e74705SXin Li 
1029*67e74705SXin Li   // false on error
checkMissingKeys(yaml::Node * Obj,DenseMap<StringRef,KeyStatus> & Keys)1030*67e74705SXin Li   bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
1031*67e74705SXin Li     for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
1032*67e74705SXin Li          E = Keys.end();
1033*67e74705SXin Li          I != E; ++I) {
1034*67e74705SXin Li       if (I->second.Required && !I->second.Seen) {
1035*67e74705SXin Li         error(Obj, Twine("missing key '") + I->first + "'");
1036*67e74705SXin Li         return false;
1037*67e74705SXin Li       }
1038*67e74705SXin Li     }
1039*67e74705SXin Li     return true;
1040*67e74705SXin Li   }
1041*67e74705SXin Li 
lookupOrCreateEntry(RedirectingFileSystem * FS,StringRef Name,Entry * ParentEntry=nullptr)1042*67e74705SXin Li   Entry *lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1043*67e74705SXin Li                              Entry *ParentEntry = nullptr) {
1044*67e74705SXin Li     if (!ParentEntry) { // Look for a existent root
1045*67e74705SXin Li       for (const std::unique_ptr<Entry> &Root : FS->Roots) {
1046*67e74705SXin Li         if (Name.equals(Root->getName())) {
1047*67e74705SXin Li           ParentEntry = Root.get();
1048*67e74705SXin Li           return ParentEntry;
1049*67e74705SXin Li         }
1050*67e74705SXin Li       }
1051*67e74705SXin Li     } else { // Advance to the next component
1052*67e74705SXin Li       auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1053*67e74705SXin Li       for (std::unique_ptr<Entry> &Content :
1054*67e74705SXin Li            llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1055*67e74705SXin Li         auto *DirContent = dyn_cast<RedirectingDirectoryEntry>(Content.get());
1056*67e74705SXin Li         if (DirContent && Name.equals(Content->getName()))
1057*67e74705SXin Li           return DirContent;
1058*67e74705SXin Li       }
1059*67e74705SXin Li     }
1060*67e74705SXin Li 
1061*67e74705SXin Li     // ... or create a new one
1062*67e74705SXin Li     std::unique_ptr<Entry> E = llvm::make_unique<RedirectingDirectoryEntry>(
1063*67e74705SXin Li         Name, Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0,
1064*67e74705SXin Li                      0, file_type::directory_file, sys::fs::all_all));
1065*67e74705SXin Li 
1066*67e74705SXin Li     if (!ParentEntry) { // Add a new root to the overlay
1067*67e74705SXin Li       FS->Roots.push_back(std::move(E));
1068*67e74705SXin Li       ParentEntry = FS->Roots.back().get();
1069*67e74705SXin Li       return ParentEntry;
1070*67e74705SXin Li     }
1071*67e74705SXin Li 
1072*67e74705SXin Li     auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1073*67e74705SXin Li     DE->addContent(std::move(E));
1074*67e74705SXin Li     return DE->getLastContent();
1075*67e74705SXin Li   }
1076*67e74705SXin Li 
uniqueOverlayTree(RedirectingFileSystem * FS,Entry * SrcE,Entry * NewParentE=nullptr)1077*67e74705SXin Li   void uniqueOverlayTree(RedirectingFileSystem *FS, Entry *SrcE,
1078*67e74705SXin Li                          Entry *NewParentE = nullptr) {
1079*67e74705SXin Li     StringRef Name = SrcE->getName();
1080*67e74705SXin Li     switch (SrcE->getKind()) {
1081*67e74705SXin Li     case EK_Directory: {
1082*67e74705SXin Li       auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1083*67e74705SXin Li       assert(DE && "Must be a directory");
1084*67e74705SXin Li       // Empty directories could be present in the YAML as a way to
1085*67e74705SXin Li       // describe a file for a current directory after some of its subdir
1086*67e74705SXin Li       // is parsed. This only leads to redundant walks, ignore it.
1087*67e74705SXin Li       if (!Name.empty())
1088*67e74705SXin Li         NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1089*67e74705SXin Li       for (std::unique_ptr<Entry> &SubEntry :
1090*67e74705SXin Li            llvm::make_range(DE->contents_begin(), DE->contents_end()))
1091*67e74705SXin Li         uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1092*67e74705SXin Li       break;
1093*67e74705SXin Li     }
1094*67e74705SXin Li     case EK_File: {
1095*67e74705SXin Li       auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1096*67e74705SXin Li       assert(FE && "Must be a file");
1097*67e74705SXin Li       assert(NewParentE && "Parent entry must exist");
1098*67e74705SXin Li       auto *DE = dyn_cast<RedirectingDirectoryEntry>(NewParentE);
1099*67e74705SXin Li       DE->addContent(llvm::make_unique<RedirectingFileEntry>(
1100*67e74705SXin Li           Name, FE->getExternalContentsPath(), FE->getUseName()));
1101*67e74705SXin Li       break;
1102*67e74705SXin Li     }
1103*67e74705SXin Li     }
1104*67e74705SXin Li   }
1105*67e74705SXin Li 
parseEntry(yaml::Node * N,RedirectingFileSystem * FS)1106*67e74705SXin Li   std::unique_ptr<Entry> parseEntry(yaml::Node *N, RedirectingFileSystem *FS) {
1107*67e74705SXin Li     yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
1108*67e74705SXin Li     if (!M) {
1109*67e74705SXin Li       error(N, "expected mapping node for file or directory entry");
1110*67e74705SXin Li       return nullptr;
1111*67e74705SXin Li     }
1112*67e74705SXin Li 
1113*67e74705SXin Li     KeyStatusPair Fields[] = {
1114*67e74705SXin Li       KeyStatusPair("name", true),
1115*67e74705SXin Li       KeyStatusPair("type", true),
1116*67e74705SXin Li       KeyStatusPair("contents", false),
1117*67e74705SXin Li       KeyStatusPair("external-contents", false),
1118*67e74705SXin Li       KeyStatusPair("use-external-name", false),
1119*67e74705SXin Li     };
1120*67e74705SXin Li 
1121*67e74705SXin Li     DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
1122*67e74705SXin Li 
1123*67e74705SXin Li     bool HasContents = false; // external or otherwise
1124*67e74705SXin Li     std::vector<std::unique_ptr<Entry>> EntryArrayContents;
1125*67e74705SXin Li     std::string ExternalContentsPath;
1126*67e74705SXin Li     std::string Name;
1127*67e74705SXin Li     auto UseExternalName = RedirectingFileEntry::NK_NotSet;
1128*67e74705SXin Li     EntryKind Kind;
1129*67e74705SXin Li 
1130*67e74705SXin Li     for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
1131*67e74705SXin Li          ++I) {
1132*67e74705SXin Li       StringRef Key;
1133*67e74705SXin Li       // Reuse the buffer for key and value, since we don't look at key after
1134*67e74705SXin Li       // parsing value.
1135*67e74705SXin Li       SmallString<256> Buffer;
1136*67e74705SXin Li       if (!parseScalarString(I->getKey(), Key, Buffer))
1137*67e74705SXin Li         return nullptr;
1138*67e74705SXin Li 
1139*67e74705SXin Li       if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1140*67e74705SXin Li         return nullptr;
1141*67e74705SXin Li 
1142*67e74705SXin Li       StringRef Value;
1143*67e74705SXin Li       if (Key == "name") {
1144*67e74705SXin Li         if (!parseScalarString(I->getValue(), Value, Buffer))
1145*67e74705SXin Li           return nullptr;
1146*67e74705SXin Li 
1147*67e74705SXin Li         if (FS->UseCanonicalizedPaths) {
1148*67e74705SXin Li           SmallString<256> Path(Value);
1149*67e74705SXin Li           // Guarantee that old YAML files containing paths with ".." and "."
1150*67e74705SXin Li           // are properly canonicalized before read into the VFS.
1151*67e74705SXin Li           Path = sys::path::remove_leading_dotslash(Path);
1152*67e74705SXin Li           sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1153*67e74705SXin Li           Name = Path.str();
1154*67e74705SXin Li         } else {
1155*67e74705SXin Li           Name = Value;
1156*67e74705SXin Li         }
1157*67e74705SXin Li       } else if (Key == "type") {
1158*67e74705SXin Li         if (!parseScalarString(I->getValue(), Value, Buffer))
1159*67e74705SXin Li           return nullptr;
1160*67e74705SXin Li         if (Value == "file")
1161*67e74705SXin Li           Kind = EK_File;
1162*67e74705SXin Li         else if (Value == "directory")
1163*67e74705SXin Li           Kind = EK_Directory;
1164*67e74705SXin Li         else {
1165*67e74705SXin Li           error(I->getValue(), "unknown value for 'type'");
1166*67e74705SXin Li           return nullptr;
1167*67e74705SXin Li         }
1168*67e74705SXin Li       } else if (Key == "contents") {
1169*67e74705SXin Li         if (HasContents) {
1170*67e74705SXin Li           error(I->getKey(),
1171*67e74705SXin Li                 "entry already has 'contents' or 'external-contents'");
1172*67e74705SXin Li           return nullptr;
1173*67e74705SXin Li         }
1174*67e74705SXin Li         HasContents = true;
1175*67e74705SXin Li         yaml::SequenceNode *Contents =
1176*67e74705SXin Li             dyn_cast<yaml::SequenceNode>(I->getValue());
1177*67e74705SXin Li         if (!Contents) {
1178*67e74705SXin Li           // FIXME: this is only for directories, what about files?
1179*67e74705SXin Li           error(I->getValue(), "expected array");
1180*67e74705SXin Li           return nullptr;
1181*67e74705SXin Li         }
1182*67e74705SXin Li 
1183*67e74705SXin Li         for (yaml::SequenceNode::iterator I = Contents->begin(),
1184*67e74705SXin Li                                           E = Contents->end();
1185*67e74705SXin Li              I != E; ++I) {
1186*67e74705SXin Li           if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
1187*67e74705SXin Li             EntryArrayContents.push_back(std::move(E));
1188*67e74705SXin Li           else
1189*67e74705SXin Li             return nullptr;
1190*67e74705SXin Li         }
1191*67e74705SXin Li       } else if (Key == "external-contents") {
1192*67e74705SXin Li         if (HasContents) {
1193*67e74705SXin Li           error(I->getKey(),
1194*67e74705SXin Li                 "entry already has 'contents' or 'external-contents'");
1195*67e74705SXin Li           return nullptr;
1196*67e74705SXin Li         }
1197*67e74705SXin Li         HasContents = true;
1198*67e74705SXin Li         if (!parseScalarString(I->getValue(), Value, Buffer))
1199*67e74705SXin Li           return nullptr;
1200*67e74705SXin Li 
1201*67e74705SXin Li         SmallString<256> FullPath;
1202*67e74705SXin Li         if (FS->IsRelativeOverlay) {
1203*67e74705SXin Li           FullPath = FS->getExternalContentsPrefixDir();
1204*67e74705SXin Li           assert(!FullPath.empty() &&
1205*67e74705SXin Li                  "External contents prefix directory must exist");
1206*67e74705SXin Li           llvm::sys::path::append(FullPath, Value);
1207*67e74705SXin Li         } else {
1208*67e74705SXin Li           FullPath = Value;
1209*67e74705SXin Li         }
1210*67e74705SXin Li 
1211*67e74705SXin Li         if (FS->UseCanonicalizedPaths) {
1212*67e74705SXin Li           // Guarantee that old YAML files containing paths with ".." and "."
1213*67e74705SXin Li           // are properly canonicalized before read into the VFS.
1214*67e74705SXin Li           FullPath = sys::path::remove_leading_dotslash(FullPath);
1215*67e74705SXin Li           sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
1216*67e74705SXin Li         }
1217*67e74705SXin Li         ExternalContentsPath = FullPath.str();
1218*67e74705SXin Li       } else if (Key == "use-external-name") {
1219*67e74705SXin Li         bool Val;
1220*67e74705SXin Li         if (!parseScalarBool(I->getValue(), Val))
1221*67e74705SXin Li           return nullptr;
1222*67e74705SXin Li         UseExternalName = Val ? RedirectingFileEntry::NK_External
1223*67e74705SXin Li                               : RedirectingFileEntry::NK_Virtual;
1224*67e74705SXin Li       } else {
1225*67e74705SXin Li         llvm_unreachable("key missing from Keys");
1226*67e74705SXin Li       }
1227*67e74705SXin Li     }
1228*67e74705SXin Li 
1229*67e74705SXin Li     if (Stream.failed())
1230*67e74705SXin Li       return nullptr;
1231*67e74705SXin Li 
1232*67e74705SXin Li     // check for missing keys
1233*67e74705SXin Li     if (!HasContents) {
1234*67e74705SXin Li       error(N, "missing key 'contents' or 'external-contents'");
1235*67e74705SXin Li       return nullptr;
1236*67e74705SXin Li     }
1237*67e74705SXin Li     if (!checkMissingKeys(N, Keys))
1238*67e74705SXin Li       return nullptr;
1239*67e74705SXin Li 
1240*67e74705SXin Li     // check invalid configuration
1241*67e74705SXin Li     if (Kind == EK_Directory &&
1242*67e74705SXin Li         UseExternalName != RedirectingFileEntry::NK_NotSet) {
1243*67e74705SXin Li       error(N, "'use-external-name' is not supported for directories");
1244*67e74705SXin Li       return nullptr;
1245*67e74705SXin Li     }
1246*67e74705SXin Li 
1247*67e74705SXin Li     // Remove trailing slash(es), being careful not to remove the root path
1248*67e74705SXin Li     StringRef Trimmed(Name);
1249*67e74705SXin Li     size_t RootPathLen = sys::path::root_path(Trimmed).size();
1250*67e74705SXin Li     while (Trimmed.size() > RootPathLen &&
1251*67e74705SXin Li            sys::path::is_separator(Trimmed.back()))
1252*67e74705SXin Li       Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1253*67e74705SXin Li     // Get the last component
1254*67e74705SXin Li     StringRef LastComponent = sys::path::filename(Trimmed);
1255*67e74705SXin Li 
1256*67e74705SXin Li     std::unique_ptr<Entry> Result;
1257*67e74705SXin Li     switch (Kind) {
1258*67e74705SXin Li     case EK_File:
1259*67e74705SXin Li       Result = llvm::make_unique<RedirectingFileEntry>(
1260*67e74705SXin Li           LastComponent, std::move(ExternalContentsPath), UseExternalName);
1261*67e74705SXin Li       break;
1262*67e74705SXin Li     case EK_Directory:
1263*67e74705SXin Li       Result = llvm::make_unique<RedirectingDirectoryEntry>(
1264*67e74705SXin Li           LastComponent, std::move(EntryArrayContents),
1265*67e74705SXin Li           Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1266*67e74705SXin Li                  file_type::directory_file, sys::fs::all_all));
1267*67e74705SXin Li       break;
1268*67e74705SXin Li     }
1269*67e74705SXin Li 
1270*67e74705SXin Li     StringRef Parent = sys::path::parent_path(Trimmed);
1271*67e74705SXin Li     if (Parent.empty())
1272*67e74705SXin Li       return Result;
1273*67e74705SXin Li 
1274*67e74705SXin Li     // if 'name' contains multiple components, create implicit directory entries
1275*67e74705SXin Li     for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1276*67e74705SXin Li                                      E = sys::path::rend(Parent);
1277*67e74705SXin Li          I != E; ++I) {
1278*67e74705SXin Li       std::vector<std::unique_ptr<Entry>> Entries;
1279*67e74705SXin Li       Entries.push_back(std::move(Result));
1280*67e74705SXin Li       Result = llvm::make_unique<RedirectingDirectoryEntry>(
1281*67e74705SXin Li           *I, std::move(Entries),
1282*67e74705SXin Li           Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
1283*67e74705SXin Li                  file_type::directory_file, sys::fs::all_all));
1284*67e74705SXin Li     }
1285*67e74705SXin Li     return Result;
1286*67e74705SXin Li   }
1287*67e74705SXin Li 
1288*67e74705SXin Li public:
RedirectingFileSystemParser(yaml::Stream & S)1289*67e74705SXin Li   RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
1290*67e74705SXin Li 
1291*67e74705SXin Li   // false on error
parse(yaml::Node * Root,RedirectingFileSystem * FS)1292*67e74705SXin Li   bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
1293*67e74705SXin Li     yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
1294*67e74705SXin Li     if (!Top) {
1295*67e74705SXin Li       error(Root, "expected mapping node");
1296*67e74705SXin Li       return false;
1297*67e74705SXin Li     }
1298*67e74705SXin Li 
1299*67e74705SXin Li     KeyStatusPair Fields[] = {
1300*67e74705SXin Li       KeyStatusPair("version", true),
1301*67e74705SXin Li       KeyStatusPair("case-sensitive", false),
1302*67e74705SXin Li       KeyStatusPair("use-external-names", false),
1303*67e74705SXin Li       KeyStatusPair("overlay-relative", false),
1304*67e74705SXin Li       KeyStatusPair("roots", true),
1305*67e74705SXin Li     };
1306*67e74705SXin Li 
1307*67e74705SXin Li     DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
1308*67e74705SXin Li     std::vector<std::unique_ptr<Entry>> RootEntries;
1309*67e74705SXin Li 
1310*67e74705SXin Li     // Parse configuration and 'roots'
1311*67e74705SXin Li     for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
1312*67e74705SXin Li          ++I) {
1313*67e74705SXin Li       SmallString<10> KeyBuffer;
1314*67e74705SXin Li       StringRef Key;
1315*67e74705SXin Li       if (!parseScalarString(I->getKey(), Key, KeyBuffer))
1316*67e74705SXin Li         return false;
1317*67e74705SXin Li 
1318*67e74705SXin Li       if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1319*67e74705SXin Li         return false;
1320*67e74705SXin Li 
1321*67e74705SXin Li       if (Key == "roots") {
1322*67e74705SXin Li         yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
1323*67e74705SXin Li         if (!Roots) {
1324*67e74705SXin Li           error(I->getValue(), "expected array");
1325*67e74705SXin Li           return false;
1326*67e74705SXin Li         }
1327*67e74705SXin Li 
1328*67e74705SXin Li         for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
1329*67e74705SXin Li              I != E; ++I) {
1330*67e74705SXin Li           if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
1331*67e74705SXin Li             RootEntries.push_back(std::move(E));
1332*67e74705SXin Li           else
1333*67e74705SXin Li             return false;
1334*67e74705SXin Li         }
1335*67e74705SXin Li       } else if (Key == "version") {
1336*67e74705SXin Li         StringRef VersionString;
1337*67e74705SXin Li         SmallString<4> Storage;
1338*67e74705SXin Li         if (!parseScalarString(I->getValue(), VersionString, Storage))
1339*67e74705SXin Li           return false;
1340*67e74705SXin Li         int Version;
1341*67e74705SXin Li         if (VersionString.getAsInteger<int>(10, Version)) {
1342*67e74705SXin Li           error(I->getValue(), "expected integer");
1343*67e74705SXin Li           return false;
1344*67e74705SXin Li         }
1345*67e74705SXin Li         if (Version < 0) {
1346*67e74705SXin Li           error(I->getValue(), "invalid version number");
1347*67e74705SXin Li           return false;
1348*67e74705SXin Li         }
1349*67e74705SXin Li         if (Version != 0) {
1350*67e74705SXin Li           error(I->getValue(), "version mismatch, expected 0");
1351*67e74705SXin Li           return false;
1352*67e74705SXin Li         }
1353*67e74705SXin Li       } else if (Key == "case-sensitive") {
1354*67e74705SXin Li         if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
1355*67e74705SXin Li           return false;
1356*67e74705SXin Li       } else if (Key == "overlay-relative") {
1357*67e74705SXin Li         if (!parseScalarBool(I->getValue(), FS->IsRelativeOverlay))
1358*67e74705SXin Li           return false;
1359*67e74705SXin Li       } else if (Key == "use-external-names") {
1360*67e74705SXin Li         if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
1361*67e74705SXin Li           return false;
1362*67e74705SXin Li       } else {
1363*67e74705SXin Li         llvm_unreachable("key missing from Keys");
1364*67e74705SXin Li       }
1365*67e74705SXin Li     }
1366*67e74705SXin Li 
1367*67e74705SXin Li     if (Stream.failed())
1368*67e74705SXin Li       return false;
1369*67e74705SXin Li 
1370*67e74705SXin Li     if (!checkMissingKeys(Top, Keys))
1371*67e74705SXin Li       return false;
1372*67e74705SXin Li 
1373*67e74705SXin Li     // Now that we sucessefully parsed the YAML file, canonicalize the internal
1374*67e74705SXin Li     // representation to a proper directory tree so that we can search faster
1375*67e74705SXin Li     // inside the VFS.
1376*67e74705SXin Li     for (std::unique_ptr<Entry> &E : RootEntries)
1377*67e74705SXin Li       uniqueOverlayTree(FS, E.get());
1378*67e74705SXin Li 
1379*67e74705SXin Li     return true;
1380*67e74705SXin Li   }
1381*67e74705SXin Li };
1382*67e74705SXin Li } // end of anonymous namespace
1383*67e74705SXin Li 
1384*67e74705SXin Li Entry::~Entry() = default;
1385*67e74705SXin Li 
1386*67e74705SXin Li RedirectingFileSystem *
create(std::unique_ptr<MemoryBuffer> Buffer,SourceMgr::DiagHandlerTy DiagHandler,StringRef YAMLFilePath,void * DiagContext,IntrusiveRefCntPtr<FileSystem> ExternalFS)1387*67e74705SXin Li RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1388*67e74705SXin Li                               SourceMgr::DiagHandlerTy DiagHandler,
1389*67e74705SXin Li                               StringRef YAMLFilePath, void *DiagContext,
1390*67e74705SXin Li                               IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1391*67e74705SXin Li 
1392*67e74705SXin Li   SourceMgr SM;
1393*67e74705SXin Li   yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
1394*67e74705SXin Li 
1395*67e74705SXin Li   SM.setDiagHandler(DiagHandler, DiagContext);
1396*67e74705SXin Li   yaml::document_iterator DI = Stream.begin();
1397*67e74705SXin Li   yaml::Node *Root = DI->getRoot();
1398*67e74705SXin Li   if (DI == Stream.end() || !Root) {
1399*67e74705SXin Li     SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
1400*67e74705SXin Li     return nullptr;
1401*67e74705SXin Li   }
1402*67e74705SXin Li 
1403*67e74705SXin Li   RedirectingFileSystemParser P(Stream);
1404*67e74705SXin Li 
1405*67e74705SXin Li   std::unique_ptr<RedirectingFileSystem> FS(
1406*67e74705SXin Li       new RedirectingFileSystem(std::move(ExternalFS)));
1407*67e74705SXin Li 
1408*67e74705SXin Li   if (!YAMLFilePath.empty()) {
1409*67e74705SXin Li     // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1410*67e74705SXin Li     // to each 'external-contents' path.
1411*67e74705SXin Li     //
1412*67e74705SXin Li     // Example:
1413*67e74705SXin Li     //    -ivfsoverlay dummy.cache/vfs/vfs.yaml
1414*67e74705SXin Li     // yields:
1415*67e74705SXin Li     //  FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1416*67e74705SXin Li     //
1417*67e74705SXin Li     SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1418*67e74705SXin Li     std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1419*67e74705SXin Li     assert(!EC && "Overlay dir final path must be absolute");
1420*67e74705SXin Li     (void)EC;
1421*67e74705SXin Li     FS->setExternalContentsPrefixDir(OverlayAbsDir);
1422*67e74705SXin Li   }
1423*67e74705SXin Li 
1424*67e74705SXin Li   if (!P.parse(Root, FS.get()))
1425*67e74705SXin Li     return nullptr;
1426*67e74705SXin Li 
1427*67e74705SXin Li   return FS.release();
1428*67e74705SXin Li }
1429*67e74705SXin Li 
lookupPath(const Twine & Path_)1430*67e74705SXin Li ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
1431*67e74705SXin Li   SmallString<256> Path;
1432*67e74705SXin Li   Path_.toVector(Path);
1433*67e74705SXin Li 
1434*67e74705SXin Li   // Handle relative paths
1435*67e74705SXin Li   if (std::error_code EC = makeAbsolute(Path))
1436*67e74705SXin Li     return EC;
1437*67e74705SXin Li 
1438*67e74705SXin Li   // Canonicalize path by removing ".", "..", "./", etc components. This is
1439*67e74705SXin Li   // a VFS request, do bot bother about symlinks in the path components
1440*67e74705SXin Li   // but canonicalize in order to perform the correct entry search.
1441*67e74705SXin Li   if (UseCanonicalizedPaths) {
1442*67e74705SXin Li     Path = sys::path::remove_leading_dotslash(Path);
1443*67e74705SXin Li     sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1444*67e74705SXin Li   }
1445*67e74705SXin Li 
1446*67e74705SXin Li   if (Path.empty())
1447*67e74705SXin Li     return make_error_code(llvm::errc::invalid_argument);
1448*67e74705SXin Li 
1449*67e74705SXin Li   sys::path::const_iterator Start = sys::path::begin(Path);
1450*67e74705SXin Li   sys::path::const_iterator End = sys::path::end(Path);
1451*67e74705SXin Li   for (const std::unique_ptr<Entry> &Root : Roots) {
1452*67e74705SXin Li     ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
1453*67e74705SXin Li     if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
1454*67e74705SXin Li       return Result;
1455*67e74705SXin Li   }
1456*67e74705SXin Li   return make_error_code(llvm::errc::no_such_file_or_directory);
1457*67e74705SXin Li }
1458*67e74705SXin Li 
1459*67e74705SXin Li ErrorOr<Entry *>
lookupPath(sys::path::const_iterator Start,sys::path::const_iterator End,Entry * From)1460*67e74705SXin Li RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1461*67e74705SXin Li                                   sys::path::const_iterator End, Entry *From) {
1462*67e74705SXin Li #ifndef LLVM_ON_WIN32
1463*67e74705SXin Li   assert(!isTraversalComponent(*Start) &&
1464*67e74705SXin Li          !isTraversalComponent(From->getName()) &&
1465*67e74705SXin Li          "Paths should not contain traversal components");
1466*67e74705SXin Li #else
1467*67e74705SXin Li   // FIXME: this is here to support windows, remove it once canonicalized
1468*67e74705SXin Li   // paths become globally default.
1469*67e74705SXin Li   if (Start->equals("."))
1470*67e74705SXin Li     ++Start;
1471*67e74705SXin Li #endif
1472*67e74705SXin Li 
1473*67e74705SXin Li   StringRef FromName = From->getName();
1474*67e74705SXin Li 
1475*67e74705SXin Li   // Forward the search to the next component in case this is an empty one.
1476*67e74705SXin Li   if (!FromName.empty()) {
1477*67e74705SXin Li     if (CaseSensitive ? !Start->equals(FromName)
1478*67e74705SXin Li                       : !Start->equals_lower(FromName))
1479*67e74705SXin Li       // failure to match
1480*67e74705SXin Li       return make_error_code(llvm::errc::no_such_file_or_directory);
1481*67e74705SXin Li 
1482*67e74705SXin Li     ++Start;
1483*67e74705SXin Li 
1484*67e74705SXin Li     if (Start == End) {
1485*67e74705SXin Li       // Match!
1486*67e74705SXin Li       return From;
1487*67e74705SXin Li     }
1488*67e74705SXin Li   }
1489*67e74705SXin Li 
1490*67e74705SXin Li   auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
1491*67e74705SXin Li   if (!DE)
1492*67e74705SXin Li     return make_error_code(llvm::errc::not_a_directory);
1493*67e74705SXin Li 
1494*67e74705SXin Li   for (const std::unique_ptr<Entry> &DirEntry :
1495*67e74705SXin Li        llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1496*67e74705SXin Li     ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
1497*67e74705SXin Li     if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
1498*67e74705SXin Li       return Result;
1499*67e74705SXin Li   }
1500*67e74705SXin Li   return make_error_code(llvm::errc::no_such_file_or_directory);
1501*67e74705SXin Li }
1502*67e74705SXin Li 
getRedirectedFileStatus(const Twine & Path,bool UseExternalNames,Status ExternalStatus)1503*67e74705SXin Li static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1504*67e74705SXin Li                                       Status ExternalStatus) {
1505*67e74705SXin Li   Status S = ExternalStatus;
1506*67e74705SXin Li   if (!UseExternalNames)
1507*67e74705SXin Li     S = Status::copyWithNewName(S, Path.str());
1508*67e74705SXin Li   S.IsVFSMapped = true;
1509*67e74705SXin Li   return S;
1510*67e74705SXin Li }
1511*67e74705SXin Li 
status(const Twine & Path,Entry * E)1512*67e74705SXin Li ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
1513*67e74705SXin Li   assert(E != nullptr);
1514*67e74705SXin Li   if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
1515*67e74705SXin Li     ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
1516*67e74705SXin Li     assert(!S || S->getName() == F->getExternalContentsPath());
1517*67e74705SXin Li     if (S)
1518*67e74705SXin Li       return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1519*67e74705SXin Li                                      *S);
1520*67e74705SXin Li     return S;
1521*67e74705SXin Li   } else { // directory
1522*67e74705SXin Li     auto *DE = cast<RedirectingDirectoryEntry>(E);
1523*67e74705SXin Li     return Status::copyWithNewName(DE->getStatus(), Path.str());
1524*67e74705SXin Li   }
1525*67e74705SXin Li }
1526*67e74705SXin Li 
status(const Twine & Path)1527*67e74705SXin Li ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
1528*67e74705SXin Li   ErrorOr<Entry *> Result = lookupPath(Path);
1529*67e74705SXin Li   if (!Result)
1530*67e74705SXin Li     return Result.getError();
1531*67e74705SXin Li   return status(Path, *Result);
1532*67e74705SXin Li }
1533*67e74705SXin Li 
1534*67e74705SXin Li namespace {
1535*67e74705SXin Li /// Provide a file wrapper with an overriden status.
1536*67e74705SXin Li class FileWithFixedStatus : public File {
1537*67e74705SXin Li   std::unique_ptr<File> InnerFile;
1538*67e74705SXin Li   Status S;
1539*67e74705SXin Li 
1540*67e74705SXin Li public:
FileWithFixedStatus(std::unique_ptr<File> InnerFile,Status S)1541*67e74705SXin Li   FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
1542*67e74705SXin Li       : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
1543*67e74705SXin Li 
status()1544*67e74705SXin Li   ErrorOr<Status> status() override { return S; }
1545*67e74705SXin Li   ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
getBuffer(const Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)1546*67e74705SXin Li   getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1547*67e74705SXin Li             bool IsVolatile) override {
1548*67e74705SXin Li     return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1549*67e74705SXin Li                                 IsVolatile);
1550*67e74705SXin Li   }
close()1551*67e74705SXin Li   std::error_code close() override { return InnerFile->close(); }
1552*67e74705SXin Li };
1553*67e74705SXin Li } // end anonymous namespace
1554*67e74705SXin Li 
1555*67e74705SXin Li ErrorOr<std::unique_ptr<File>>
openFileForRead(const Twine & Path)1556*67e74705SXin Li RedirectingFileSystem::openFileForRead(const Twine &Path) {
1557*67e74705SXin Li   ErrorOr<Entry *> E = lookupPath(Path);
1558*67e74705SXin Li   if (!E)
1559*67e74705SXin Li     return E.getError();
1560*67e74705SXin Li 
1561*67e74705SXin Li   auto *F = dyn_cast<RedirectingFileEntry>(*E);
1562*67e74705SXin Li   if (!F) // FIXME: errc::not_a_file?
1563*67e74705SXin Li     return make_error_code(llvm::errc::invalid_argument);
1564*67e74705SXin Li 
1565*67e74705SXin Li   auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1566*67e74705SXin Li   if (!Result)
1567*67e74705SXin Li     return Result;
1568*67e74705SXin Li 
1569*67e74705SXin Li   auto ExternalStatus = (*Result)->status();
1570*67e74705SXin Li   if (!ExternalStatus)
1571*67e74705SXin Li     return ExternalStatus.getError();
1572*67e74705SXin Li 
1573*67e74705SXin Li   // FIXME: Update the status with the name and VFSMapped.
1574*67e74705SXin Li   Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1575*67e74705SXin Li                                      *ExternalStatus);
1576*67e74705SXin Li   return std::unique_ptr<File>(
1577*67e74705SXin Li       llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
1578*67e74705SXin Li }
1579*67e74705SXin Li 
1580*67e74705SXin Li IntrusiveRefCntPtr<FileSystem>
getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,SourceMgr::DiagHandlerTy DiagHandler,StringRef YAMLFilePath,void * DiagContext,IntrusiveRefCntPtr<FileSystem> ExternalFS)1581*67e74705SXin Li vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1582*67e74705SXin Li                     SourceMgr::DiagHandlerTy DiagHandler,
1583*67e74705SXin Li                     StringRef YAMLFilePath,
1584*67e74705SXin Li                     void *DiagContext,
1585*67e74705SXin Li                     IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1586*67e74705SXin Li   return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
1587*67e74705SXin Li                                        YAMLFilePath, DiagContext,
1588*67e74705SXin Li                                        std::move(ExternalFS));
1589*67e74705SXin Li }
1590*67e74705SXin Li 
getNextVirtualUniqueID()1591*67e74705SXin Li UniqueID vfs::getNextVirtualUniqueID() {
1592*67e74705SXin Li   static std::atomic<unsigned> UID;
1593*67e74705SXin Li   unsigned ID = ++UID;
1594*67e74705SXin Li   // The following assumes that uint64_t max will never collide with a real
1595*67e74705SXin Li   // dev_t value from the OS.
1596*67e74705SXin Li   return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1597*67e74705SXin Li }
1598*67e74705SXin Li 
addFileMapping(StringRef VirtualPath,StringRef RealPath)1599*67e74705SXin Li void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1600*67e74705SXin Li   assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1601*67e74705SXin Li   assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1602*67e74705SXin Li   assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1603*67e74705SXin Li   Mappings.emplace_back(VirtualPath, RealPath);
1604*67e74705SXin Li }
1605*67e74705SXin Li 
1606*67e74705SXin Li namespace {
1607*67e74705SXin Li class JSONWriter {
1608*67e74705SXin Li   llvm::raw_ostream &OS;
1609*67e74705SXin Li   SmallVector<StringRef, 16> DirStack;
getDirIndent()1610*67e74705SXin Li   inline unsigned getDirIndent() { return 4 * DirStack.size(); }
getFileIndent()1611*67e74705SXin Li   inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1612*67e74705SXin Li   bool containedIn(StringRef Parent, StringRef Path);
1613*67e74705SXin Li   StringRef containedPart(StringRef Parent, StringRef Path);
1614*67e74705SXin Li   void startDirectory(StringRef Path);
1615*67e74705SXin Li   void endDirectory();
1616*67e74705SXin Li   void writeEntry(StringRef VPath, StringRef RPath);
1617*67e74705SXin Li 
1618*67e74705SXin Li public:
JSONWriter(llvm::raw_ostream & OS)1619*67e74705SXin Li   JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
1620*67e74705SXin Li   void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
1621*67e74705SXin Li              Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
1622*67e74705SXin Li              StringRef OverlayDir);
1623*67e74705SXin Li };
1624*67e74705SXin Li }
1625*67e74705SXin Li 
containedIn(StringRef Parent,StringRef Path)1626*67e74705SXin Li bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
1627*67e74705SXin Li   using namespace llvm::sys;
1628*67e74705SXin Li   // Compare each path component.
1629*67e74705SXin Li   auto IParent = path::begin(Parent), EParent = path::end(Parent);
1630*67e74705SXin Li   for (auto IChild = path::begin(Path), EChild = path::end(Path);
1631*67e74705SXin Li        IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1632*67e74705SXin Li     if (*IParent != *IChild)
1633*67e74705SXin Li       return false;
1634*67e74705SXin Li   }
1635*67e74705SXin Li   // Have we exhausted the parent path?
1636*67e74705SXin Li   return IParent == EParent;
1637*67e74705SXin Li }
1638*67e74705SXin Li 
containedPart(StringRef Parent,StringRef Path)1639*67e74705SXin Li StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1640*67e74705SXin Li   assert(!Parent.empty());
1641*67e74705SXin Li   assert(containedIn(Parent, Path));
1642*67e74705SXin Li   return Path.slice(Parent.size() + 1, StringRef::npos);
1643*67e74705SXin Li }
1644*67e74705SXin Li 
startDirectory(StringRef Path)1645*67e74705SXin Li void JSONWriter::startDirectory(StringRef Path) {
1646*67e74705SXin Li   StringRef Name =
1647*67e74705SXin Li       DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1648*67e74705SXin Li   DirStack.push_back(Path);
1649*67e74705SXin Li   unsigned Indent = getDirIndent();
1650*67e74705SXin Li   OS.indent(Indent) << "{\n";
1651*67e74705SXin Li   OS.indent(Indent + 2) << "'type': 'directory',\n";
1652*67e74705SXin Li   OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1653*67e74705SXin Li   OS.indent(Indent + 2) << "'contents': [\n";
1654*67e74705SXin Li }
1655*67e74705SXin Li 
endDirectory()1656*67e74705SXin Li void JSONWriter::endDirectory() {
1657*67e74705SXin Li   unsigned Indent = getDirIndent();
1658*67e74705SXin Li   OS.indent(Indent + 2) << "]\n";
1659*67e74705SXin Li   OS.indent(Indent) << "}";
1660*67e74705SXin Li 
1661*67e74705SXin Li   DirStack.pop_back();
1662*67e74705SXin Li }
1663*67e74705SXin Li 
writeEntry(StringRef VPath,StringRef RPath)1664*67e74705SXin Li void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1665*67e74705SXin Li   unsigned Indent = getFileIndent();
1666*67e74705SXin Li   OS.indent(Indent) << "{\n";
1667*67e74705SXin Li   OS.indent(Indent + 2) << "'type': 'file',\n";
1668*67e74705SXin Li   OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1669*67e74705SXin Li   OS.indent(Indent + 2) << "'external-contents': \""
1670*67e74705SXin Li                         << llvm::yaml::escape(RPath) << "\"\n";
1671*67e74705SXin Li   OS.indent(Indent) << "}";
1672*67e74705SXin Li }
1673*67e74705SXin Li 
write(ArrayRef<YAMLVFSEntry> Entries,Optional<bool> UseExternalNames,Optional<bool> IsCaseSensitive,Optional<bool> IsOverlayRelative,StringRef OverlayDir)1674*67e74705SXin Li void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
1675*67e74705SXin Li                        Optional<bool> UseExternalNames,
1676*67e74705SXin Li                        Optional<bool> IsCaseSensitive,
1677*67e74705SXin Li                        Optional<bool> IsOverlayRelative,
1678*67e74705SXin Li                        StringRef OverlayDir) {
1679*67e74705SXin Li   using namespace llvm::sys;
1680*67e74705SXin Li 
1681*67e74705SXin Li   OS << "{\n"
1682*67e74705SXin Li         "  'version': 0,\n";
1683*67e74705SXin Li   if (IsCaseSensitive.hasValue())
1684*67e74705SXin Li     OS << "  'case-sensitive': '"
1685*67e74705SXin Li        << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
1686*67e74705SXin Li   if (UseExternalNames.hasValue())
1687*67e74705SXin Li     OS << "  'use-external-names': '"
1688*67e74705SXin Li        << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
1689*67e74705SXin Li   bool UseOverlayRelative = false;
1690*67e74705SXin Li   if (IsOverlayRelative.hasValue()) {
1691*67e74705SXin Li     UseOverlayRelative = IsOverlayRelative.getValue();
1692*67e74705SXin Li     OS << "  'overlay-relative': '"
1693*67e74705SXin Li        << (UseOverlayRelative ? "true" : "false") << "',\n";
1694*67e74705SXin Li   }
1695*67e74705SXin Li   OS << "  'roots': [\n";
1696*67e74705SXin Li 
1697*67e74705SXin Li   if (!Entries.empty()) {
1698*67e74705SXin Li     const YAMLVFSEntry &Entry = Entries.front();
1699*67e74705SXin Li     startDirectory(path::parent_path(Entry.VPath));
1700*67e74705SXin Li 
1701*67e74705SXin Li     StringRef RPath = Entry.RPath;
1702*67e74705SXin Li     if (UseOverlayRelative) {
1703*67e74705SXin Li       unsigned OverlayDirLen = OverlayDir.size();
1704*67e74705SXin Li       assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1705*67e74705SXin Li              "Overlay dir must be contained in RPath");
1706*67e74705SXin Li       RPath = RPath.slice(OverlayDirLen, RPath.size());
1707*67e74705SXin Li     }
1708*67e74705SXin Li 
1709*67e74705SXin Li     writeEntry(path::filename(Entry.VPath), RPath);
1710*67e74705SXin Li 
1711*67e74705SXin Li     for (const auto &Entry : Entries.slice(1)) {
1712*67e74705SXin Li       StringRef Dir = path::parent_path(Entry.VPath);
1713*67e74705SXin Li       if (Dir == DirStack.back())
1714*67e74705SXin Li         OS << ",\n";
1715*67e74705SXin Li       else {
1716*67e74705SXin Li         while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1717*67e74705SXin Li           OS << "\n";
1718*67e74705SXin Li           endDirectory();
1719*67e74705SXin Li         }
1720*67e74705SXin Li         OS << ",\n";
1721*67e74705SXin Li         startDirectory(Dir);
1722*67e74705SXin Li       }
1723*67e74705SXin Li       StringRef RPath = Entry.RPath;
1724*67e74705SXin Li       if (UseOverlayRelative) {
1725*67e74705SXin Li         unsigned OverlayDirLen = OverlayDir.size();
1726*67e74705SXin Li         assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1727*67e74705SXin Li                "Overlay dir must be contained in RPath");
1728*67e74705SXin Li         RPath = RPath.slice(OverlayDirLen, RPath.size());
1729*67e74705SXin Li       }
1730*67e74705SXin Li       writeEntry(path::filename(Entry.VPath), RPath);
1731*67e74705SXin Li     }
1732*67e74705SXin Li 
1733*67e74705SXin Li     while (!DirStack.empty()) {
1734*67e74705SXin Li       OS << "\n";
1735*67e74705SXin Li       endDirectory();
1736*67e74705SXin Li     }
1737*67e74705SXin Li     OS << "\n";
1738*67e74705SXin Li   }
1739*67e74705SXin Li 
1740*67e74705SXin Li   OS << "  ]\n"
1741*67e74705SXin Li      << "}\n";
1742*67e74705SXin Li }
1743*67e74705SXin Li 
write(llvm::raw_ostream & OS)1744*67e74705SXin Li void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1745*67e74705SXin Li   std::sort(Mappings.begin(), Mappings.end(),
1746*67e74705SXin Li             [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
1747*67e74705SXin Li     return LHS.VPath < RHS.VPath;
1748*67e74705SXin Li   });
1749*67e74705SXin Li 
1750*67e74705SXin Li   JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
1751*67e74705SXin Li                        IsOverlayRelative, OverlayDir);
1752*67e74705SXin Li }
1753*67e74705SXin Li 
VFSFromYamlDirIterImpl(const Twine & _Path,RedirectingFileSystem & FS,RedirectingDirectoryEntry::iterator Begin,RedirectingDirectoryEntry::iterator End,std::error_code & EC)1754*67e74705SXin Li VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1755*67e74705SXin Li     const Twine &_Path, RedirectingFileSystem &FS,
1756*67e74705SXin Li     RedirectingDirectoryEntry::iterator Begin,
1757*67e74705SXin Li     RedirectingDirectoryEntry::iterator End, std::error_code &EC)
1758*67e74705SXin Li     : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
1759*67e74705SXin Li   if (Current != End) {
1760*67e74705SXin Li     SmallString<128> PathStr(Dir);
1761*67e74705SXin Li     llvm::sys::path::append(PathStr, (*Current)->getName());
1762*67e74705SXin Li     llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
1763*67e74705SXin Li     if (S)
1764*67e74705SXin Li       CurrentEntry = *S;
1765*67e74705SXin Li     else
1766*67e74705SXin Li       EC = S.getError();
1767*67e74705SXin Li   }
1768*67e74705SXin Li }
1769*67e74705SXin Li 
increment()1770*67e74705SXin Li std::error_code VFSFromYamlDirIterImpl::increment() {
1771*67e74705SXin Li   assert(Current != End && "cannot iterate past end");
1772*67e74705SXin Li   if (++Current != End) {
1773*67e74705SXin Li     SmallString<128> PathStr(Dir);
1774*67e74705SXin Li     llvm::sys::path::append(PathStr, (*Current)->getName());
1775*67e74705SXin Li     llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
1776*67e74705SXin Li     if (!S)
1777*67e74705SXin Li       return S.getError();
1778*67e74705SXin Li     CurrentEntry = *S;
1779*67e74705SXin Li   } else {
1780*67e74705SXin Li     CurrentEntry = Status();
1781*67e74705SXin Li   }
1782*67e74705SXin Li   return std::error_code();
1783*67e74705SXin Li }
1784*67e74705SXin Li 
recursive_directory_iterator(FileSystem & FS_,const Twine & Path,std::error_code & EC)1785*67e74705SXin Li vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1786*67e74705SXin Li                                                            const Twine &Path,
1787*67e74705SXin Li                                                            std::error_code &EC)
1788*67e74705SXin Li     : FS(&FS_) {
1789*67e74705SXin Li   directory_iterator I = FS->dir_begin(Path, EC);
1790*67e74705SXin Li   if (!EC && I != directory_iterator()) {
1791*67e74705SXin Li     State = std::make_shared<IterState>();
1792*67e74705SXin Li     State->push(I);
1793*67e74705SXin Li   }
1794*67e74705SXin Li }
1795*67e74705SXin Li 
1796*67e74705SXin Li vfs::recursive_directory_iterator &
increment(std::error_code & EC)1797*67e74705SXin Li recursive_directory_iterator::increment(std::error_code &EC) {
1798*67e74705SXin Li   assert(FS && State && !State->empty() && "incrementing past end");
1799*67e74705SXin Li   assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1800*67e74705SXin Li   vfs::directory_iterator End;
1801*67e74705SXin Li   if (State->top()->isDirectory()) {
1802*67e74705SXin Li     vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
1803*67e74705SXin Li     if (EC)
1804*67e74705SXin Li       return *this;
1805*67e74705SXin Li     if (I != End) {
1806*67e74705SXin Li       State->push(I);
1807*67e74705SXin Li       return *this;
1808*67e74705SXin Li     }
1809*67e74705SXin Li   }
1810*67e74705SXin Li 
1811*67e74705SXin Li   while (!State->empty() && State->top().increment(EC) == End)
1812*67e74705SXin Li     State->pop();
1813*67e74705SXin Li 
1814*67e74705SXin Li   if (State->empty())
1815*67e74705SXin Li     State.reset(); // end iterator
1816*67e74705SXin Li 
1817*67e74705SXin Li   return *this;
1818*67e74705SXin Li }
1819