blob: df446bbcd51ca803dd8ad900f0bd2b9784191838 [file] [log] [blame]
Ben Langmuirc8130a72014-02-20 21:59:23 +00001//===- VirtualFileSystem.cpp - Virtual File System Layer --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// This file implements the VirtualFileSystem interface.
10//===----------------------------------------------------------------------===//
11
12#include "clang/Basic/VirtualFileSystem.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000013#include "llvm/ADT/DenseMap.h"
Justin Bogner9c785292014-05-20 21:43:27 +000014#include "llvm/ADT/iterator_range.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000015#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/StringExtras.h"
Ben Langmuir740812b2014-06-24 19:37:16 +000017#include "llvm/ADT/StringSet.h"
Rafael Espindola71de0b62014-06-13 17:20:50 +000018#include "llvm/Support/Errc.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000019#include "llvm/Support/MemoryBuffer.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000020#include "llvm/Support/Path.h"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000021#include "llvm/Support/YAMLParser.h"
Benjamin Kramer4527fb22014-03-02 17:08:31 +000022#include <atomic>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000023#include <memory>
Ben Langmuirc8130a72014-02-20 21:59:23 +000024
25using namespace clang;
26using namespace clang::vfs;
27using namespace llvm;
28using llvm::sys::fs::file_status;
29using llvm::sys::fs::file_type;
30using llvm::sys::fs::perms;
31using llvm::sys::fs::UniqueID;
32
33Status::Status(const file_status &Status)
34 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
35 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
Ben Langmuir5de00f32014-05-23 18:15:47 +000036 Type(Status.type()), Perms(Status.permissions()), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000037
38Status::Status(StringRef Name, StringRef ExternalName, UniqueID UID,
39 sys::TimeValue MTime, uint32_t User, uint32_t Group,
40 uint64_t Size, file_type Type, perms Perms)
Ben Langmuirb59cf672014-02-27 00:25:12 +000041 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
Ben Langmuir5de00f32014-05-23 18:15:47 +000042 Type(Type), Perms(Perms), IsVFSMapped(false) {}
Ben Langmuirc8130a72014-02-20 21:59:23 +000043
44bool Status::equivalent(const Status &Other) const {
45 return getUniqueID() == Other.getUniqueID();
46}
47bool Status::isDirectory() const {
48 return Type == file_type::directory_file;
49}
50bool Status::isRegularFile() const {
51 return Type == file_type::regular_file;
52}
53bool Status::isOther() const {
54 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
55}
56bool Status::isSymlink() const {
57 return Type == file_type::symlink_file;
58}
59bool Status::isStatusKnown() const {
60 return Type != file_type::status_error;
61}
62bool Status::exists() const {
63 return isStatusKnown() && Type != file_type::file_not_found;
64}
65
66File::~File() {}
67
68FileSystem::~FileSystem() {}
69
Rafael Espindola8e650d72014-06-12 20:37:59 +000070std::error_code FileSystem::getBufferForFile(
71 const llvm::Twine &Name, std::unique_ptr<MemoryBuffer> &Result,
72 int64_t FileSize, bool RequiresNullTerminator, bool IsVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +000073 std::unique_ptr<File> F;
Rafael Espindola8e650d72014-06-12 20:37:59 +000074 if (std::error_code EC = openFileForRead(Name, F))
Ben Langmuirc8130a72014-02-20 21:59:23 +000075 return EC;
76
Rafael Espindola8e650d72014-06-12 20:37:59 +000077 std::error_code EC =
78 F->getBuffer(Name, Result, FileSize, RequiresNullTerminator, IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +000079 return EC;
80}
81
82//===-----------------------------------------------------------------------===/
83// RealFileSystem implementation
84//===-----------------------------------------------------------------------===/
85
Benjamin Kramer3d6220d2014-03-01 17:21:22 +000086namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +000087/// \brief Wrapper around a raw file descriptor.
88class RealFile : public File {
89 int FD;
Ben Langmuird066d4c2014-02-28 21:16:07 +000090 Status S;
Ben Langmuirc8130a72014-02-20 21:59:23 +000091 friend class RealFileSystem;
92 RealFile(int FD) : FD(FD) {
93 assert(FD >= 0 && "Invalid or inactive file descriptor");
94 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +000095
Ben Langmuirc8130a72014-02-20 21:59:23 +000096public:
97 ~RealFile();
Craig Toppera798a9d2014-03-02 09:32:10 +000098 ErrorOr<Status> status() override;
Rafael Espindola8e650d72014-06-12 20:37:59 +000099 std::error_code getBuffer(const Twine &Name,
100 std::unique_ptr<MemoryBuffer> &Result,
101 int64_t FileSize = -1,
102 bool RequiresNullTerminator = true,
103 bool IsVolatile = false) override;
104 std::error_code close() override;
Craig Toppera798a9d2014-03-02 09:32:10 +0000105 void setName(StringRef Name) override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000106};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000107} // end anonymous namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000108RealFile::~RealFile() { close(); }
Ben Langmuirc8130a72014-02-20 21:59:23 +0000109
110ErrorOr<Status> RealFile::status() {
111 assert(FD != -1 && "cannot stat closed file");
Ben Langmuird066d4c2014-02-28 21:16:07 +0000112 if (!S.isStatusKnown()) {
113 file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000114 if (std::error_code EC = sys::fs::status(FD, RealStatus))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000115 return EC;
116 Status NewS(RealStatus);
117 NewS.setName(S.getName());
Chandler Carruthc72d9b32014-03-02 04:02:40 +0000118 S = std::move(NewS);
Ben Langmuird066d4c2014-02-28 21:16:07 +0000119 }
120 return S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000121}
122
Rafael Espindola8e650d72014-06-12 20:37:59 +0000123std::error_code RealFile::getBuffer(const Twine &Name,
124 std::unique_ptr<MemoryBuffer> &Result,
125 int64_t FileSize,
126 bool RequiresNullTerminator,
127 bool IsVolatile) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000128 assert(FD != -1 && "cannot get buffer for closed file");
Rafael Espindola2d2b4202014-07-06 17:43:24 +0000129 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
130 MemoryBuffer::getOpenFile(FD, Name.str().c_str(), FileSize,
131 RequiresNullTerminator, IsVolatile);
132 if (std::error_code EC = BufferOrErr.getError())
133 return EC;
134 Result = std::move(BufferOrErr.get());
135 return std::error_code();
Ben Langmuirc8130a72014-02-20 21:59:23 +0000136}
137
138// FIXME: This is terrible, we need this for ::close.
139#if !defined(_MSC_VER) && !defined(__MINGW32__)
140#include <unistd.h>
141#include <sys/uio.h>
142#else
143#include <io.h>
144#ifndef S_ISFIFO
145#define S_ISFIFO(x) (0)
146#endif
147#endif
Rafael Espindola8e650d72014-06-12 20:37:59 +0000148std::error_code RealFile::close() {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000149 if (::close(FD))
Rafael Espindola8e650d72014-06-12 20:37:59 +0000150 return std::error_code(errno, std::generic_category());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000151 FD = -1;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000152 return std::error_code();
Ben Langmuirc8130a72014-02-20 21:59:23 +0000153}
154
Ben Langmuird066d4c2014-02-28 21:16:07 +0000155void RealFile::setName(StringRef Name) {
156 S.setName(Name);
157}
158
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000159namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000160/// \brief The file system according to your operating system.
161class RealFileSystem : public FileSystem {
162public:
Craig Toppera798a9d2014-03-02 09:32:10 +0000163 ErrorOr<Status> status(const Twine &Path) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000164 std::error_code openFileForRead(const Twine &Path,
165 std::unique_ptr<File> &Result) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000166 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000167};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000168} // end anonymous namespace
Ben Langmuirc8130a72014-02-20 21:59:23 +0000169
170ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
171 sys::fs::file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000172 if (std::error_code EC = sys::fs::status(Path, RealStatus))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000173 return EC;
174 Status Result(RealStatus);
175 Result.setName(Path.str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000176 return Result;
177}
178
Rafael Espindola8e650d72014-06-12 20:37:59 +0000179std::error_code RealFileSystem::openFileForRead(const Twine &Name,
180 std::unique_ptr<File> &Result) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000181 int FD;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000182 if (std::error_code EC = sys::fs::openFileForRead(Name, FD))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000183 return EC;
184 Result.reset(new RealFile(FD));
Ben Langmuird066d4c2014-02-28 21:16:07 +0000185 Result->setName(Name.str());
Rafael Espindola8e650d72014-06-12 20:37:59 +0000186 return std::error_code();
Ben Langmuirc8130a72014-02-20 21:59:23 +0000187}
188
189IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
190 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
191 return FS;
192}
193
Ben Langmuir740812b2014-06-24 19:37:16 +0000194namespace {
195class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
196 std::string Path;
197 llvm::sys::fs::directory_iterator Iter;
198public:
199 RealFSDirIter(const Twine &_Path, std::error_code &EC)
200 : Path(_Path.str()), Iter(Path, EC) {
201 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
202 llvm::sys::fs::file_status S;
203 EC = Iter->status(S);
204 if (!EC) {
205 CurrentEntry = Status(S);
206 CurrentEntry.setName(Iter->path());
207 }
208 }
209 }
210
211 std::error_code increment() override {
212 std::error_code EC;
213 Iter.increment(EC);
214 if (EC) {
215 return EC;
216 } else if (Iter == llvm::sys::fs::directory_iterator()) {
217 CurrentEntry = Status();
218 } else {
219 llvm::sys::fs::file_status S;
220 EC = Iter->status(S);
221 CurrentEntry = Status(S);
222 CurrentEntry.setName(Iter->path());
223 }
224 return EC;
225 }
226};
227}
228
229directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
230 std::error_code &EC) {
231 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
232}
233
Ben Langmuirc8130a72014-02-20 21:59:23 +0000234//===-----------------------------------------------------------------------===/
235// OverlayFileSystem implementation
236//===-----------------------------------------------------------------------===/
237OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
238 pushOverlay(BaseFS);
239}
240
241void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
242 FSList.push_back(FS);
243}
244
245ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
246 // FIXME: handle symlinks that cross file systems
247 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
248 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000249 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000250 return Status;
251 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000252 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000253}
254
Rafael Espindola8e650d72014-06-12 20:37:59 +0000255std::error_code
256OverlayFileSystem::openFileForRead(const llvm::Twine &Path,
257 std::unique_ptr<File> &Result) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000258 // FIXME: handle symlinks that cross file systems
259 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Rafael Espindola8e650d72014-06-12 20:37:59 +0000260 std::error_code EC = (*I)->openFileForRead(Path, Result);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000261 if (!EC || EC != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000262 return EC;
263 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000264 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000265}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000266
Ben Langmuir740812b2014-06-24 19:37:16 +0000267clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
268
269namespace {
270class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
271 OverlayFileSystem &Overlays;
272 std::string Path;
273 OverlayFileSystem::iterator CurrentFS;
274 directory_iterator CurrentDirIter;
275 llvm::StringSet<> SeenNames;
276
277 std::error_code incrementFS() {
278 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
279 ++CurrentFS;
280 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
281 std::error_code EC;
282 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
283 if (EC && EC != errc::no_such_file_or_directory)
284 return EC;
285 if (CurrentDirIter != directory_iterator())
286 break; // found
287 }
288 return std::error_code();
289 }
290
291 std::error_code incrementDirIter(bool IsFirstTime) {
292 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
293 "incrementing past end");
294 std::error_code EC;
295 if (!IsFirstTime)
296 CurrentDirIter.increment(EC);
297 if (!EC && CurrentDirIter == directory_iterator())
298 EC = incrementFS();
299 return EC;
300 }
301
302 std::error_code incrementImpl(bool IsFirstTime) {
303 while (true) {
304 std::error_code EC = incrementDirIter(IsFirstTime);
305 if (EC || CurrentDirIter == directory_iterator()) {
306 CurrentEntry = Status();
307 return EC;
308 }
309 CurrentEntry = *CurrentDirIter;
310 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
311 if (SeenNames.insert(Name))
312 return EC; // name not seen before
313 }
314 llvm_unreachable("returned above");
315 }
316
317public:
318 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
319 std::error_code &EC)
320 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
321 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
322 EC = incrementImpl(true);
323 }
324
325 std::error_code increment() override { return incrementImpl(false); }
326};
327} // end anonymous namespace
328
329directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
330 std::error_code &EC) {
331 return directory_iterator(
332 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
333}
334
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000335//===-----------------------------------------------------------------------===/
336// VFSFromYAML implementation
337//===-----------------------------------------------------------------------===/
338
339// Allow DenseMap<StringRef, ...>. This is useful below because we know all the
340// strings are literals and will outlive the map, and there is no reason to
341// store them.
342namespace llvm {
343 template<>
344 struct DenseMapInfo<StringRef> {
345 // This assumes that "" will never be a valid key.
346 static inline StringRef getEmptyKey() { return StringRef(""); }
347 static inline StringRef getTombstoneKey() { return StringRef(); }
348 static unsigned getHashValue(StringRef Val) { return HashString(Val); }
349 static bool isEqual(StringRef LHS, StringRef RHS) { return LHS == RHS; }
350 };
351}
352
353namespace {
354
355enum EntryKind {
356 EK_Directory,
357 EK_File
358};
359
360/// \brief A single file or directory in the VFS.
361class Entry {
362 EntryKind Kind;
363 std::string Name;
364
365public:
366 virtual ~Entry();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000367 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
368 StringRef getName() const { return Name; }
369 EntryKind getKind() const { return Kind; }
370};
371
372class DirectoryEntry : public Entry {
373 std::vector<Entry *> Contents;
374 Status S;
375
376public:
377 virtual ~DirectoryEntry();
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000378 DirectoryEntry(StringRef Name, std::vector<Entry *> Contents, Status S)
379 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000380 S(std::move(S)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000381 Status getStatus() { return S; }
382 typedef std::vector<Entry *>::iterator iterator;
383 iterator contents_begin() { return Contents.begin(); }
384 iterator contents_end() { return Contents.end(); }
385 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
386};
387
388class FileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000389public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000390 enum NameKind {
391 NK_NotSet,
392 NK_External,
393 NK_Virtual
394 };
395private:
396 std::string ExternalContentsPath;
397 NameKind UseName;
398public:
399 FileEntry(StringRef Name, StringRef ExternalContentsPath, NameKind UseName)
400 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
401 UseName(UseName) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000402 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Ben Langmuirb59cf672014-02-27 00:25:12 +0000403 /// \brief whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000404 bool useExternalName(bool GlobalUseExternalName) const {
405 return UseName == NK_NotSet ? GlobalUseExternalName
406 : (UseName == NK_External);
407 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000408 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
409};
410
Ben Langmuir740812b2014-06-24 19:37:16 +0000411class VFSFromYAML;
412
413class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
414 std::string Dir;
415 VFSFromYAML &FS;
416 DirectoryEntry::iterator Current, End;
417public:
418 VFSFromYamlDirIterImpl(const Twine &Path, VFSFromYAML &FS,
419 DirectoryEntry::iterator Begin,
420 DirectoryEntry::iterator End, std::error_code &EC);
421 std::error_code increment() override;
422};
423
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000424/// \brief A virtual file system parsed from a YAML file.
425///
426/// Currently, this class allows creating virtual directories and mapping
427/// virtual file paths to existing external files, available in \c ExternalFS.
428///
429/// The basic structure of the parsed file is:
430/// \verbatim
431/// {
432/// 'version': <version number>,
433/// <optional configuration>
434/// 'roots': [
435/// <directory entries>
436/// ]
437/// }
438/// \endverbatim
439///
440/// All configuration options are optional.
441/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000442/// 'use-external-names': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000443///
444/// Virtual directories are represented as
445/// \verbatim
446/// {
447/// 'type': 'directory',
448/// 'name': <string>,
449/// 'contents': [ <file or directory entries> ]
450/// }
451/// \endverbatim
452///
453/// The default attributes for virtual directories are:
454/// \verbatim
455/// MTime = now() when created
456/// Perms = 0777
457/// User = Group = 0
458/// Size = 0
459/// UniqueID = unspecified unique value
460/// \endverbatim
461///
462/// Re-mapped files are represented as
463/// \verbatim
464/// {
465/// 'type': 'file',
466/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000467/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000468/// 'external-contents': <path to external file>)
469/// }
470/// \endverbatim
471///
472/// and inherit their attributes from the external contents.
473///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000474/// In both cases, the 'name' field may contain multiple path components (e.g.
475/// /path/to/file). However, any directory that contains more than one child
476/// must be uniquely represented by a directory entry.
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000477class VFSFromYAML : public vfs::FileSystem {
478 std::vector<Entry *> Roots; ///< The root(s) of the virtual file system.
479 /// \brief The file system to use for external references.
480 IntrusiveRefCntPtr<FileSystem> ExternalFS;
481
482 /// @name Configuration
483 /// @{
484
485 /// \brief Whether to perform case-sensitive comparisons.
486 ///
487 /// Currently, case-insensitive matching only works correctly with ASCII.
Ben Langmuirb59cf672014-02-27 00:25:12 +0000488 bool CaseSensitive;
489
490 /// \brief Whether to use to use the value of 'external-contents' for the
491 /// names of files. This global value is overridable on a per-file basis.
492 bool UseExternalNames;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000493 /// @}
494
495 friend class VFSFromYAMLParser;
496
497private:
498 VFSFromYAML(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000499 : ExternalFS(ExternalFS), CaseSensitive(true), UseExternalNames(true) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000500
501 /// \brief Looks up \p Path in \c Roots.
502 ErrorOr<Entry *> lookupPath(const Twine &Path);
503
504 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
505 /// recursing into the contents of \p From if it is a directory.
506 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
507 sys::path::const_iterator End, Entry *From);
508
Ben Langmuir740812b2014-06-24 19:37:16 +0000509 /// \brief Get the status of a given an \c Entry.
510 ErrorOr<Status> status(const Twine &Path, Entry *E);
511
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000512public:
513 ~VFSFromYAML();
514
515 /// \brief Parses \p Buffer, which is expected to be in YAML format and
516 /// returns a virtual file system representing its contents.
Rafael Espindola04ab21d72014-08-17 22:12:58 +0000517 static VFSFromYAML *create(std::unique_ptr<MemoryBuffer> Buffer,
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000518 SourceMgr::DiagHandlerTy DiagHandler,
Ben Langmuir97882e72014-02-24 20:56:37 +0000519 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000520 IntrusiveRefCntPtr<FileSystem> ExternalFS);
521
Craig Toppera798a9d2014-03-02 09:32:10 +0000522 ErrorOr<Status> status(const Twine &Path) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000523 std::error_code openFileForRead(const Twine &Path,
524 std::unique_ptr<File> &Result) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000525
526 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
527 ErrorOr<Entry *> E = lookupPath(Dir);
528 if (!E) {
529 EC = E.getError();
530 return directory_iterator();
531 }
532 ErrorOr<Status> S = status(Dir, *E);
533 if (!S) {
534 EC = S.getError();
535 return directory_iterator();
536 }
537 if (!S->isDirectory()) {
538 EC = std::error_code(static_cast<int>(errc::not_a_directory),
539 std::system_category());
540 return directory_iterator();
541 }
542
543 DirectoryEntry *D = cast<DirectoryEntry>(*E);
544 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
545 *this, D->contents_begin(), D->contents_end(), EC));
546 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000547};
548
549/// \brief A helper class to hold the common YAML parsing state.
550class VFSFromYAMLParser {
551 yaml::Stream &Stream;
552
553 void error(yaml::Node *N, const Twine &Msg) {
554 Stream.printError(N, Msg);
555 }
556
557 // false on error
558 bool parseScalarString(yaml::Node *N, StringRef &Result,
559 SmallVectorImpl<char> &Storage) {
560 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
561 if (!S) {
562 error(N, "expected string");
563 return false;
564 }
565 Result = S->getValue(Storage);
566 return true;
567 }
568
569 // false on error
570 bool parseScalarBool(yaml::Node *N, bool &Result) {
571 SmallString<5> Storage;
572 StringRef Value;
573 if (!parseScalarString(N, Value, Storage))
574 return false;
575
576 if (Value.equals_lower("true") || Value.equals_lower("on") ||
577 Value.equals_lower("yes") || Value == "1") {
578 Result = true;
579 return true;
580 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
581 Value.equals_lower("no") || Value == "0") {
582 Result = false;
583 return true;
584 }
585
586 error(N, "expected boolean value");
587 return false;
588 }
589
590 struct KeyStatus {
591 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
592 bool Required;
593 bool Seen;
594 };
595 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
596
597 // false on error
598 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
599 DenseMap<StringRef, KeyStatus> &Keys) {
600 if (!Keys.count(Key)) {
601 error(KeyNode, "unknown key");
602 return false;
603 }
604 KeyStatus &S = Keys[Key];
605 if (S.Seen) {
606 error(KeyNode, Twine("duplicate key '") + Key + "'");
607 return false;
608 }
609 S.Seen = true;
610 return true;
611 }
612
613 // false on error
614 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
615 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
616 E = Keys.end();
617 I != E; ++I) {
618 if (I->second.Required && !I->second.Seen) {
619 error(Obj, Twine("missing key '") + I->first + "'");
620 return false;
621 }
622 }
623 return true;
624 }
625
626 Entry *parseEntry(yaml::Node *N) {
627 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
628 if (!M) {
629 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +0000630 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000631 }
632
633 KeyStatusPair Fields[] = {
634 KeyStatusPair("name", true),
635 KeyStatusPair("type", true),
636 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +0000637 KeyStatusPair("external-contents", false),
638 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000639 };
640
641 DenseMap<StringRef, KeyStatus> Keys(
642 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
643
644 bool HasContents = false; // external or otherwise
645 std::vector<Entry *> EntryArrayContents;
646 std::string ExternalContentsPath;
647 std::string Name;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000648 FileEntry::NameKind UseExternalName = FileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000649 EntryKind Kind;
650
651 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
652 ++I) {
653 StringRef Key;
654 // Reuse the buffer for key and value, since we don't look at key after
655 // parsing value.
656 SmallString<256> Buffer;
657 if (!parseScalarString(I->getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000658 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000659
660 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +0000661 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000662
663 StringRef Value;
664 if (Key == "name") {
665 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000666 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000667 Name = Value;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000668 } else if (Key == "type") {
669 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000670 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000671 if (Value == "file")
672 Kind = EK_File;
673 else if (Value == "directory")
674 Kind = EK_Directory;
675 else {
676 error(I->getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +0000677 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000678 }
679 } else if (Key == "contents") {
680 if (HasContents) {
681 error(I->getKey(),
682 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +0000683 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000684 }
685 HasContents = true;
686 yaml::SequenceNode *Contents =
687 dyn_cast<yaml::SequenceNode>(I->getValue());
688 if (!Contents) {
689 // FIXME: this is only for directories, what about files?
690 error(I->getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +0000691 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000692 }
693
694 for (yaml::SequenceNode::iterator I = Contents->begin(),
695 E = Contents->end();
696 I != E; ++I) {
697 if (Entry *E = parseEntry(&*I))
698 EntryArrayContents.push_back(E);
699 else
Craig Topperf1186c52014-05-08 06:41:40 +0000700 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000701 }
702 } else if (Key == "external-contents") {
703 if (HasContents) {
704 error(I->getKey(),
705 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +0000706 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000707 }
708 HasContents = true;
709 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000710 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000711 ExternalContentsPath = Value;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000712 } else if (Key == "use-external-name") {
713 bool Val;
714 if (!parseScalarBool(I->getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +0000715 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000716 UseExternalName = Val ? FileEntry::NK_External : FileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000717 } else {
718 llvm_unreachable("key missing from Keys");
719 }
720 }
721
722 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +0000723 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000724
725 // check for missing keys
726 if (!HasContents) {
727 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +0000728 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000729 }
730 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +0000731 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000732
Ben Langmuirb59cf672014-02-27 00:25:12 +0000733 // check invalid configuration
734 if (Kind == EK_Directory && UseExternalName != FileEntry::NK_NotSet) {
735 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +0000736 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000737 }
738
Ben Langmuir93853232014-03-05 21:32:20 +0000739 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000740 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +0000741 size_t RootPathLen = sys::path::root_path(Trimmed).size();
742 while (Trimmed.size() > RootPathLen &&
743 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000744 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
745 // Get the last component
746 StringRef LastComponent = sys::path::filename(Trimmed);
747
Craig Topperf1186c52014-05-08 06:41:40 +0000748 Entry *Result = nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000749 switch (Kind) {
750 case EK_File:
Chandler Carruthc72d9b32014-03-02 04:02:40 +0000751 Result = new FileEntry(LastComponent, std::move(ExternalContentsPath),
Ben Langmuirb59cf672014-02-27 00:25:12 +0000752 UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000753 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000754 case EK_Directory:
Chandler Carruthc72d9b32014-03-02 04:02:40 +0000755 Result = new DirectoryEntry(LastComponent, std::move(EntryArrayContents),
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000756 Status("", "", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0,
757 0, file_type::directory_file, sys::fs::all_all));
758 break;
759 }
760
761 StringRef Parent = sys::path::parent_path(Trimmed);
762 if (Parent.empty())
763 return Result;
764
765 // if 'name' contains multiple components, create implicit directory entries
766 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
767 E = sys::path::rend(Parent);
768 I != E; ++I) {
Benjamin Kramer3f755aa2014-03-10 17:55:02 +0000769 Result = new DirectoryEntry(*I, llvm::makeArrayRef(Result),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000770 Status("", "", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0,
771 0, file_type::directory_file, sys::fs::all_all));
772 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000773 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000774 }
775
776public:
777 VFSFromYAMLParser(yaml::Stream &S) : Stream(S) {}
778
779 // false on error
780 bool parse(yaml::Node *Root, VFSFromYAML *FS) {
781 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
782 if (!Top) {
783 error(Root, "expected mapping node");
784 return false;
785 }
786
787 KeyStatusPair Fields[] = {
788 KeyStatusPair("version", true),
789 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +0000790 KeyStatusPair("use-external-names", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000791 KeyStatusPair("roots", true),
792 };
793
794 DenseMap<StringRef, KeyStatus> Keys(
795 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
796
797 // Parse configuration and 'roots'
798 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
799 ++I) {
800 SmallString<10> KeyBuffer;
801 StringRef Key;
802 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
803 return false;
804
805 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
806 return false;
807
808 if (Key == "roots") {
809 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
810 if (!Roots) {
811 error(I->getValue(), "expected array");
812 return false;
813 }
814
815 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
816 I != E; ++I) {
817 if (Entry *E = parseEntry(&*I))
818 FS->Roots.push_back(E);
819 else
820 return false;
821 }
822 } else if (Key == "version") {
823 StringRef VersionString;
824 SmallString<4> Storage;
825 if (!parseScalarString(I->getValue(), VersionString, Storage))
826 return false;
827 int Version;
828 if (VersionString.getAsInteger<int>(10, Version)) {
829 error(I->getValue(), "expected integer");
830 return false;
831 }
832 if (Version < 0) {
833 error(I->getValue(), "invalid version number");
834 return false;
835 }
836 if (Version != 0) {
837 error(I->getValue(), "version mismatch, expected 0");
838 return false;
839 }
840 } else if (Key == "case-sensitive") {
841 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
842 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000843 } else if (Key == "use-external-names") {
844 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
845 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000846 } else {
847 llvm_unreachable("key missing from Keys");
848 }
849 }
850
851 if (Stream.failed())
852 return false;
853
854 if (!checkMissingKeys(Top, Keys))
855 return false;
856 return true;
857 }
858};
859} // end of anonymous namespace
860
861Entry::~Entry() {}
862DirectoryEntry::~DirectoryEntry() { llvm::DeleteContainerPointers(Contents); }
863
864VFSFromYAML::~VFSFromYAML() { llvm::DeleteContainerPointers(Roots); }
865
Rafael Espindola04ab21d72014-08-17 22:12:58 +0000866VFSFromYAML *VFSFromYAML::create(std::unique_ptr<MemoryBuffer> Buffer,
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000867 SourceMgr::DiagHandlerTy DiagHandler,
Ben Langmuir97882e72014-02-24 20:56:37 +0000868 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000869 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
870
871 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +0000872 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000873
Ben Langmuir97882e72014-02-24 20:56:37 +0000874 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000875 yaml::document_iterator DI = Stream.begin();
876 yaml::Node *Root = DI->getRoot();
877 if (DI == Stream.end() || !Root) {
878 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +0000879 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000880 }
881
882 VFSFromYAMLParser P(Stream);
883
Ahmed Charlesb8984322014-03-07 20:03:18 +0000884 std::unique_ptr<VFSFromYAML> FS(new VFSFromYAML(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000885 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +0000886 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000887
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000888 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000889}
890
891ErrorOr<Entry *> VFSFromYAML::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +0000892 SmallString<256> Path;
893 Path_.toVector(Path);
894
895 // Handle relative paths
Rafael Espindola8e650d72014-06-12 20:37:59 +0000896 if (std::error_code EC = sys::fs::make_absolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +0000897 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000898
899 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +0000900 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000901
902 sys::path::const_iterator Start = sys::path::begin(Path);
903 sys::path::const_iterator End = sys::path::end(Path);
904 for (std::vector<Entry *>::iterator I = Roots.begin(), E = Roots.end();
905 I != E; ++I) {
906 ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000907 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000908 return Result;
909 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000910 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000911}
912
913ErrorOr<Entry *> VFSFromYAML::lookupPath(sys::path::const_iterator Start,
914 sys::path::const_iterator End,
915 Entry *From) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +0000916 if (Start->equals("."))
917 ++Start;
918
919 // FIXME: handle ..
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000920 if (CaseSensitive ? !Start->equals(From->getName())
921 : !Start->equals_lower(From->getName()))
922 // failure to match
Rafael Espindola71de0b62014-06-13 17:20:50 +0000923 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000924
925 ++Start;
926
927 if (Start == End) {
928 // Match!
929 return From;
930 }
931
932 DirectoryEntry *DE = dyn_cast<DirectoryEntry>(From);
933 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +0000934 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000935
936 for (DirectoryEntry::iterator I = DE->contents_begin(),
937 E = DE->contents_end();
938 I != E; ++I) {
939 ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000940 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000941 return Result;
942 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000943 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000944}
945
Ben Langmuir740812b2014-06-24 19:37:16 +0000946ErrorOr<Status> VFSFromYAML::status(const Twine &Path, Entry *E) {
947 assert(E != nullptr);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000948 std::string PathStr(Path.str());
Ben Langmuir740812b2014-06-24 19:37:16 +0000949 if (FileEntry *F = dyn_cast<FileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000950 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +0000951 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000952 if (S && !F->useExternalName(UseExternalNames))
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000953 S->setName(PathStr);
Ben Langmuir5de00f32014-05-23 18:15:47 +0000954 if (S)
955 S->IsVFSMapped = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000956 return S;
957 } else { // directory
Ben Langmuir740812b2014-06-24 19:37:16 +0000958 DirectoryEntry *DE = cast<DirectoryEntry>(E);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000959 Status S = DE->getStatus();
960 S.setName(PathStr);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000961 return S;
962 }
963}
964
Ben Langmuir740812b2014-06-24 19:37:16 +0000965ErrorOr<Status> VFSFromYAML::status(const Twine &Path) {
966 ErrorOr<Entry *> Result = lookupPath(Path);
967 if (!Result)
968 return Result.getError();
969 return status(Path, *Result);
970}
971
Rafael Espindola8e650d72014-06-12 20:37:59 +0000972std::error_code
973VFSFromYAML::openFileForRead(const Twine &Path,
974 std::unique_ptr<vfs::File> &Result) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000975 ErrorOr<Entry *> E = lookupPath(Path);
976 if (!E)
977 return E.getError();
978
979 FileEntry *F = dyn_cast<FileEntry>(*E);
980 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +0000981 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000982
Rafael Espindola8e650d72014-06-12 20:37:59 +0000983 if (std::error_code EC =
984 ExternalFS->openFileForRead(F->getExternalContentsPath(), Result))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000985 return EC;
986
987 if (!F->useExternalName(UseExternalNames))
988 Result->setName(Path.str());
989
Rafael Espindola8e650d72014-06-12 20:37:59 +0000990 return std::error_code();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000991}
992
993IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +0000994vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
995 SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000996 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Rafael Espindola04ab21d72014-08-17 22:12:58 +0000997 return VFSFromYAML::create(std::move(Buffer), DiagHandler, DiagContext,
998 ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000999}
1000
1001UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001002 static std::atomic<unsigned> UID;
1003 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001004 // The following assumes that uint64_t max will never collide with a real
1005 // dev_t value from the OS.
1006 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1007}
Justin Bogner9c785292014-05-20 21:43:27 +00001008
1009#ifndef NDEBUG
1010static bool pathHasTraversal(StringRef Path) {
1011 using namespace llvm::sys;
1012 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
1013 if (Comp == "." || Comp == "..")
1014 return true;
1015 return false;
1016}
1017#endif
1018
1019void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1020 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1021 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1022 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1023 Mappings.emplace_back(VirtualPath, RealPath);
1024}
1025
Justin Bogner44fa450342014-05-21 22:46:51 +00001026namespace {
1027class JSONWriter {
1028 llvm::raw_ostream &OS;
1029 SmallVector<StringRef, 16> DirStack;
1030 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
1031 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1032 bool containedIn(StringRef Parent, StringRef Path);
1033 StringRef containedPart(StringRef Parent, StringRef Path);
1034 void startDirectory(StringRef Path);
1035 void endDirectory();
1036 void writeEntry(StringRef VPath, StringRef RPath);
1037
1038public:
1039 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
1040 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive);
1041};
Justin Bogner9c785292014-05-20 21:43:27 +00001042}
1043
Justin Bogner44fa450342014-05-21 22:46:51 +00001044bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001045 using namespace llvm::sys;
1046 // Compare each path component.
1047 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1048 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1049 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1050 if (*IParent != *IChild)
1051 return false;
1052 }
1053 // Have we exhausted the parent path?
1054 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001055}
1056
Justin Bogner44fa450342014-05-21 22:46:51 +00001057StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1058 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001059 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001060 return Path.slice(Parent.size() + 1, StringRef::npos);
1061}
1062
Justin Bogner44fa450342014-05-21 22:46:51 +00001063void JSONWriter::startDirectory(StringRef Path) {
1064 StringRef Name =
1065 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1066 DirStack.push_back(Path);
1067 unsigned Indent = getDirIndent();
1068 OS.indent(Indent) << "{\n";
1069 OS.indent(Indent + 2) << "'type': 'directory',\n";
1070 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1071 OS.indent(Indent + 2) << "'contents': [\n";
1072}
1073
1074void JSONWriter::endDirectory() {
1075 unsigned Indent = getDirIndent();
1076 OS.indent(Indent + 2) << "]\n";
1077 OS.indent(Indent) << "}";
1078
1079 DirStack.pop_back();
1080}
1081
1082void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1083 unsigned Indent = getFileIndent();
1084 OS.indent(Indent) << "{\n";
1085 OS.indent(Indent + 2) << "'type': 'file',\n";
1086 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1087 OS.indent(Indent + 2) << "'external-contents': \""
1088 << llvm::yaml::escape(RPath) << "\"\n";
1089 OS.indent(Indent) << "}";
1090}
1091
1092void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
1093 Optional<bool> IsCaseSensitive) {
1094 using namespace llvm::sys;
1095
1096 OS << "{\n"
1097 " 'version': 0,\n";
1098 if (IsCaseSensitive.hasValue())
1099 OS << " 'case-sensitive': '"
1100 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
1101 OS << " 'roots': [\n";
1102
Justin Bogner73466402014-07-15 01:24:35 +00001103 if (!Entries.empty()) {
1104 const YAMLVFSEntry &Entry = Entries.front();
1105 startDirectory(path::parent_path(Entry.VPath));
Justin Bogner44fa450342014-05-21 22:46:51 +00001106 writeEntry(path::filename(Entry.VPath), Entry.RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001107
Justin Bogner73466402014-07-15 01:24:35 +00001108 for (const auto &Entry : Entries.slice(1)) {
1109 StringRef Dir = path::parent_path(Entry.VPath);
1110 if (Dir == DirStack.back())
1111 OS << ",\n";
1112 else {
1113 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1114 OS << "\n";
1115 endDirectory();
1116 }
1117 OS << ",\n";
1118 startDirectory(Dir);
1119 }
1120 writeEntry(path::filename(Entry.VPath), Entry.RPath);
1121 }
1122
1123 while (!DirStack.empty()) {
1124 OS << "\n";
1125 endDirectory();
1126 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001127 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001128 }
1129
Justin Bogner73466402014-07-15 01:24:35 +00001130 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001131 << "}\n";
1132}
1133
Justin Bogner9c785292014-05-20 21:43:27 +00001134void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1135 std::sort(Mappings.begin(), Mappings.end(),
Justin Bogner44fa450342014-05-21 22:46:51 +00001136 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001137 return LHS.VPath < RHS.VPath;
1138 });
1139
Justin Bogner44fa450342014-05-21 22:46:51 +00001140 JSONWriter(OS).write(Mappings, IsCaseSensitive);
Justin Bogner9c785292014-05-20 21:43:27 +00001141}
Ben Langmuir740812b2014-06-24 19:37:16 +00001142
1143VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(const Twine &_Path,
1144 VFSFromYAML &FS,
1145 DirectoryEntry::iterator Begin,
1146 DirectoryEntry::iterator End,
1147 std::error_code &EC)
1148 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
1149 if (Current != End) {
1150 SmallString<128> PathStr(Dir);
1151 llvm::sys::path::append(PathStr, (*Current)->getName());
1152 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr.str());
1153 if (S)
1154 CurrentEntry = *S;
1155 else
1156 EC = S.getError();
1157 }
1158}
1159
1160std::error_code VFSFromYamlDirIterImpl::increment() {
1161 assert(Current != End && "cannot iterate past end");
1162 if (++Current != End) {
1163 SmallString<128> PathStr(Dir);
1164 llvm::sys::path::append(PathStr, (*Current)->getName());
1165 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr.str());
1166 if (!S)
1167 return S.getError();
1168 CurrentEntry = *S;
1169 } else {
1170 CurrentEntry = Status();
1171 }
1172 return std::error_code();
1173}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001174
1175vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1176 const Twine &Path,
1177 std::error_code &EC)
1178 : FS(&FS_) {
1179 directory_iterator I = FS->dir_begin(Path, EC);
1180 if (!EC && I != directory_iterator()) {
1181 State = std::make_shared<IterState>();
1182 State->push(I);
1183 }
1184}
1185
1186vfs::recursive_directory_iterator &
1187recursive_directory_iterator::increment(std::error_code &EC) {
1188 assert(FS && State && !State->empty() && "incrementing past end");
1189 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1190 vfs::directory_iterator End;
1191 if (State->top()->isDirectory()) {
1192 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
1193 if (EC)
1194 return *this;
1195 if (I != End) {
1196 State->push(I);
1197 return *this;
1198 }
1199 }
1200
1201 while (!State->empty() && State->top().increment(EC) == End)
1202 State->pop();
1203
1204 if (State->empty())
1205 State.reset(); // end iterator
1206
1207 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001208}