blob: 32e485f6c2ea693157d6e5109c230f240566b89a [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"
Ben Langmuird51ba0b2014-02-21 23:39:37 +000014#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/StringExtras.h"
Ben Langmuir740812b2014-06-24 19:37:16 +000016#include "llvm/ADT/StringSet.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000017#include "llvm/ADT/iterator_range.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
Benjamin Kramer268b51a2015-10-05 13:15:33 +000038Status::Status(StringRef Name, UniqueID UID, sys::TimeValue MTime,
39 uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
40 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
Benjamin Kramer268b51a2015-10-05 13:15:33 +000044Status Status::copyWithNewName(const Status &In, StringRef NewName) {
45 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
46 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
47 In.getPermissions());
48}
49
50Status Status::copyWithNewName(const file_status &In, StringRef NewName) {
51 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
52 In.getUser(), In.getGroup(), In.getSize(), In.type(),
53 In.permissions());
54}
55
Ben Langmuirc8130a72014-02-20 21:59:23 +000056bool Status::equivalent(const Status &Other) const {
57 return getUniqueID() == Other.getUniqueID();
58}
59bool Status::isDirectory() const {
60 return Type == file_type::directory_file;
61}
62bool Status::isRegularFile() const {
63 return Type == file_type::regular_file;
64}
65bool Status::isOther() const {
66 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
67}
68bool Status::isSymlink() const {
69 return Type == file_type::symlink_file;
70}
71bool Status::isStatusKnown() const {
72 return Type != file_type::status_error;
73}
74bool Status::exists() const {
75 return isStatusKnown() && Type != file_type::file_not_found;
76}
77
78File::~File() {}
79
80FileSystem::~FileSystem() {}
81
Benjamin Kramera8857962014-10-26 22:44:13 +000082ErrorOr<std::unique_ptr<MemoryBuffer>>
83FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
84 bool RequiresNullTerminator, bool IsVolatile) {
85 auto F = openFileForRead(Name);
86 if (!F)
87 return F.getError();
Ben Langmuirc8130a72014-02-20 21:59:23 +000088
Benjamin Kramera8857962014-10-26 22:44:13 +000089 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +000090}
91
92//===-----------------------------------------------------------------------===/
93// RealFileSystem implementation
94//===-----------------------------------------------------------------------===/
95
Benjamin Kramer3d6220d2014-03-01 17:21:22 +000096namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +000097/// \brief Wrapper around a raw file descriptor.
98class RealFile : public File {
99 int FD;
Ben Langmuird066d4c2014-02-28 21:16:07 +0000100 Status S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000101 friend class RealFileSystem;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000102 RealFile(int FD, StringRef NewName)
103 : FD(FD), S(NewName, {}, {}, {}, {}, {},
104 llvm::sys::fs::file_type::status_error, {}) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000105 assert(FD >= 0 && "Invalid or inactive file descriptor");
106 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000107
Ben Langmuirc8130a72014-02-20 21:59:23 +0000108public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000109 ~RealFile() override;
Craig Toppera798a9d2014-03-02 09:32:10 +0000110 ErrorOr<Status> status() override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000111 ErrorOr<std::unique_ptr<MemoryBuffer>>
112 getBuffer(const Twine &Name, int64_t FileSize = -1,
113 bool RequiresNullTerminator = true,
114 bool IsVolatile = false) override;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000115 std::error_code close() override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000116};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000117} // end anonymous namespace
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000118RealFile::~RealFile() { close(); }
Ben Langmuirc8130a72014-02-20 21:59:23 +0000119
120ErrorOr<Status> RealFile::status() {
121 assert(FD != -1 && "cannot stat closed file");
Ben Langmuird066d4c2014-02-28 21:16:07 +0000122 if (!S.isStatusKnown()) {
123 file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000124 if (std::error_code EC = sys::fs::status(FD, RealStatus))
Ben Langmuird066d4c2014-02-28 21:16:07 +0000125 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000126 S = Status::copyWithNewName(RealStatus, S.getName());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000127 }
128 return S;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000129}
130
Benjamin Kramera8857962014-10-26 22:44:13 +0000131ErrorOr<std::unique_ptr<MemoryBuffer>>
132RealFile::getBuffer(const Twine &Name, int64_t FileSize,
133 bool RequiresNullTerminator, bool IsVolatile) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000134 assert(FD != -1 && "cannot get buffer for closed file");
Benjamin Kramera8857962014-10-26 22:44:13 +0000135 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
136 IsVolatile);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000137}
138
139// FIXME: This is terrible, we need this for ::close.
140#if !defined(_MSC_VER) && !defined(__MINGW32__)
141#include <unistd.h>
142#include <sys/uio.h>
143#else
144#include <io.h>
145#ifndef S_ISFIFO
146#define S_ISFIFO(x) (0)
147#endif
148#endif
Rafael Espindola8e650d72014-06-12 20:37:59 +0000149std::error_code RealFile::close() {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000150 if (::close(FD))
Rafael Espindola8e650d72014-06-12 20:37:59 +0000151 return std::error_code(errno, std::generic_category());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000152 FD = -1;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000153 return std::error_code();
Ben Langmuirc8130a72014-02-20 21:59:23 +0000154}
155
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000156namespace {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000157/// \brief The file system according to your operating system.
158class RealFileSystem : public FileSystem {
159public:
Craig Toppera798a9d2014-03-02 09:32:10 +0000160 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000161 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000162 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000163};
Benjamin Kramer3d6220d2014-03-01 17:21:22 +0000164} // end anonymous namespace
Ben Langmuirc8130a72014-02-20 21:59:23 +0000165
166ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
167 sys::fs::file_status RealStatus;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000168 if (std::error_code EC = sys::fs::status(Path, RealStatus))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000169 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000170 return Status::copyWithNewName(RealStatus, Path.str());
Ben Langmuirc8130a72014-02-20 21:59:23 +0000171}
172
Benjamin Kramera8857962014-10-26 22:44:13 +0000173ErrorOr<std::unique_ptr<File>>
174RealFileSystem::openFileForRead(const Twine &Name) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000175 int FD;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000176 if (std::error_code EC = sys::fs::openFileForRead(Name, FD))
Ben Langmuirc8130a72014-02-20 21:59:23 +0000177 return EC;
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000178 return std::unique_ptr<File>(new RealFile(FD, Name.str()));
Ben Langmuirc8130a72014-02-20 21:59:23 +0000179}
180
181IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
182 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
183 return FS;
184}
185
Ben Langmuir740812b2014-06-24 19:37:16 +0000186namespace {
187class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
188 std::string Path;
189 llvm::sys::fs::directory_iterator Iter;
190public:
191 RealFSDirIter(const Twine &_Path, std::error_code &EC)
192 : Path(_Path.str()), Iter(Path, EC) {
193 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
194 llvm::sys::fs::file_status S;
195 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000196 if (!EC)
197 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000198 }
199 }
200
201 std::error_code increment() override {
202 std::error_code EC;
203 Iter.increment(EC);
204 if (EC) {
205 return EC;
206 } else if (Iter == llvm::sys::fs::directory_iterator()) {
207 CurrentEntry = Status();
208 } else {
209 llvm::sys::fs::file_status S;
210 EC = Iter->status(S);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000211 CurrentEntry = Status::copyWithNewName(S, Iter->path());
Ben Langmuir740812b2014-06-24 19:37:16 +0000212 }
213 return EC;
214 }
215};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000216}
Ben Langmuir740812b2014-06-24 19:37:16 +0000217
218directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
219 std::error_code &EC) {
220 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
221}
222
Ben Langmuirc8130a72014-02-20 21:59:23 +0000223//===-----------------------------------------------------------------------===/
224// OverlayFileSystem implementation
225//===-----------------------------------------------------------------------===/
226OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
227 pushOverlay(BaseFS);
228}
229
230void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
231 FSList.push_back(FS);
232}
233
234ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
235 // FIXME: handle symlinks that cross file systems
236 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
237 ErrorOr<Status> Status = (*I)->status(Path);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000238 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuirc8130a72014-02-20 21:59:23 +0000239 return Status;
240 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000241 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuirc8130a72014-02-20 21:59:23 +0000242}
243
Benjamin Kramera8857962014-10-26 22:44:13 +0000244ErrorOr<std::unique_ptr<File>>
245OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000246 // FIXME: handle symlinks that cross file systems
247 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000248 auto Result = (*I)->openFileForRead(Path);
249 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
250 return Result;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000251 }
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}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000254
Ben Langmuir740812b2014-06-24 19:37:16 +0000255clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
256
257namespace {
258class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
259 OverlayFileSystem &Overlays;
260 std::string Path;
261 OverlayFileSystem::iterator CurrentFS;
262 directory_iterator CurrentDirIter;
263 llvm::StringSet<> SeenNames;
264
265 std::error_code incrementFS() {
266 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
267 ++CurrentFS;
268 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
269 std::error_code EC;
270 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
271 if (EC && EC != errc::no_such_file_or_directory)
272 return EC;
273 if (CurrentDirIter != directory_iterator())
274 break; // found
275 }
276 return std::error_code();
277 }
278
279 std::error_code incrementDirIter(bool IsFirstTime) {
280 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
281 "incrementing past end");
282 std::error_code EC;
283 if (!IsFirstTime)
284 CurrentDirIter.increment(EC);
285 if (!EC && CurrentDirIter == directory_iterator())
286 EC = incrementFS();
287 return EC;
288 }
289
290 std::error_code incrementImpl(bool IsFirstTime) {
291 while (true) {
292 std::error_code EC = incrementDirIter(IsFirstTime);
293 if (EC || CurrentDirIter == directory_iterator()) {
294 CurrentEntry = Status();
295 return EC;
296 }
297 CurrentEntry = *CurrentDirIter;
298 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
David Blaikie61b86d42014-11-19 02:56:13 +0000299 if (SeenNames.insert(Name).second)
Ben Langmuir740812b2014-06-24 19:37:16 +0000300 return EC; // name not seen before
301 }
302 llvm_unreachable("returned above");
303 }
304
305public:
306 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
307 std::error_code &EC)
308 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
309 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
310 EC = incrementImpl(true);
311 }
312
313 std::error_code increment() override { return incrementImpl(false); }
314};
315} // end anonymous namespace
316
317directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
318 std::error_code &EC) {
319 return directory_iterator(
320 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
321}
322
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000323//===-----------------------------------------------------------------------===/
324// VFSFromYAML implementation
325//===-----------------------------------------------------------------------===/
326
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000327namespace {
328
329enum EntryKind {
330 EK_Directory,
331 EK_File
332};
333
334/// \brief A single file or directory in the VFS.
335class Entry {
336 EntryKind Kind;
337 std::string Name;
338
339public:
340 virtual ~Entry();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000341 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
342 StringRef getName() const { return Name; }
343 EntryKind getKind() const { return Kind; }
344};
345
346class DirectoryEntry : public Entry {
347 std::vector<Entry *> Contents;
348 Status S;
349
350public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000351 ~DirectoryEntry() override;
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000352 DirectoryEntry(StringRef Name, std::vector<Entry *> Contents, Status S)
353 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000354 S(std::move(S)) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000355 Status getStatus() { return S; }
356 typedef std::vector<Entry *>::iterator iterator;
357 iterator contents_begin() { return Contents.begin(); }
358 iterator contents_end() { return Contents.end(); }
359 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
360};
361
362class FileEntry : public Entry {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000363public:
Ben Langmuirb59cf672014-02-27 00:25:12 +0000364 enum NameKind {
365 NK_NotSet,
366 NK_External,
367 NK_Virtual
368 };
369private:
370 std::string ExternalContentsPath;
371 NameKind UseName;
372public:
373 FileEntry(StringRef Name, StringRef ExternalContentsPath, NameKind UseName)
374 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
375 UseName(UseName) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000376 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
Ben Langmuirb59cf672014-02-27 00:25:12 +0000377 /// \brief whether to use the external path as the name for this file.
Ben Langmuird066d4c2014-02-28 21:16:07 +0000378 bool useExternalName(bool GlobalUseExternalName) const {
379 return UseName == NK_NotSet ? GlobalUseExternalName
380 : (UseName == NK_External);
381 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000382 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
383};
384
Ben Langmuir740812b2014-06-24 19:37:16 +0000385class VFSFromYAML;
386
387class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
388 std::string Dir;
389 VFSFromYAML &FS;
390 DirectoryEntry::iterator Current, End;
391public:
392 VFSFromYamlDirIterImpl(const Twine &Path, VFSFromYAML &FS,
393 DirectoryEntry::iterator Begin,
394 DirectoryEntry::iterator End, std::error_code &EC);
395 std::error_code increment() override;
396};
397
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000398/// \brief A virtual file system parsed from a YAML file.
399///
400/// Currently, this class allows creating virtual directories and mapping
401/// virtual file paths to existing external files, available in \c ExternalFS.
402///
403/// The basic structure of the parsed file is:
404/// \verbatim
405/// {
406/// 'version': <version number>,
407/// <optional configuration>
408/// 'roots': [
409/// <directory entries>
410/// ]
411/// }
412/// \endverbatim
413///
414/// All configuration options are optional.
415/// 'case-sensitive': <boolean, default=true>
Ben Langmuirb59cf672014-02-27 00:25:12 +0000416/// 'use-external-names': <boolean, default=true>
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000417///
418/// Virtual directories are represented as
419/// \verbatim
420/// {
421/// 'type': 'directory',
422/// 'name': <string>,
423/// 'contents': [ <file or directory entries> ]
424/// }
425/// \endverbatim
426///
427/// The default attributes for virtual directories are:
428/// \verbatim
429/// MTime = now() when created
430/// Perms = 0777
431/// User = Group = 0
432/// Size = 0
433/// UniqueID = unspecified unique value
434/// \endverbatim
435///
436/// Re-mapped files are represented as
437/// \verbatim
438/// {
439/// 'type': 'file',
440/// 'name': <string>,
Ben Langmuirb59cf672014-02-27 00:25:12 +0000441/// 'use-external-name': <boolean> # Optional
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000442/// 'external-contents': <path to external file>)
443/// }
444/// \endverbatim
445///
446/// and inherit their attributes from the external contents.
447///
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000448/// In both cases, the 'name' field may contain multiple path components (e.g.
449/// /path/to/file). However, any directory that contains more than one child
450/// must be uniquely represented by a directory entry.
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000451class VFSFromYAML : public vfs::FileSystem {
452 std::vector<Entry *> Roots; ///< The root(s) of the virtual file system.
453 /// \brief The file system to use for external references.
454 IntrusiveRefCntPtr<FileSystem> ExternalFS;
455
456 /// @name Configuration
457 /// @{
458
459 /// \brief Whether to perform case-sensitive comparisons.
460 ///
461 /// Currently, case-insensitive matching only works correctly with ASCII.
Ben Langmuirb59cf672014-02-27 00:25:12 +0000462 bool CaseSensitive;
463
464 /// \brief Whether to use to use the value of 'external-contents' for the
465 /// names of files. This global value is overridable on a per-file basis.
466 bool UseExternalNames;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000467 /// @}
468
469 friend class VFSFromYAMLParser;
470
471private:
472 VFSFromYAML(IntrusiveRefCntPtr<FileSystem> ExternalFS)
Ben Langmuirb59cf672014-02-27 00:25:12 +0000473 : ExternalFS(ExternalFS), CaseSensitive(true), UseExternalNames(true) {}
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000474
475 /// \brief Looks up \p Path in \c Roots.
476 ErrorOr<Entry *> lookupPath(const Twine &Path);
477
478 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
479 /// recursing into the contents of \p From if it is a directory.
480 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
481 sys::path::const_iterator End, Entry *From);
482
Ben Langmuir740812b2014-06-24 19:37:16 +0000483 /// \brief Get the status of a given an \c Entry.
484 ErrorOr<Status> status(const Twine &Path, Entry *E);
485
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000486public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000487 ~VFSFromYAML() override;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000488
489 /// \brief Parses \p Buffer, which is expected to be in YAML format and
490 /// returns a virtual file system representing its contents.
Rafael Espindola04ab21d72014-08-17 22:12:58 +0000491 static VFSFromYAML *create(std::unique_ptr<MemoryBuffer> Buffer,
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000492 SourceMgr::DiagHandlerTy DiagHandler,
Ben Langmuir97882e72014-02-24 20:56:37 +0000493 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000494 IntrusiveRefCntPtr<FileSystem> ExternalFS);
495
Craig Toppera798a9d2014-03-02 09:32:10 +0000496 ErrorOr<Status> status(const Twine &Path) override;
Benjamin Kramera8857962014-10-26 22:44:13 +0000497 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
Ben Langmuir740812b2014-06-24 19:37:16 +0000498
499 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
500 ErrorOr<Entry *> E = lookupPath(Dir);
501 if (!E) {
502 EC = E.getError();
503 return directory_iterator();
504 }
505 ErrorOr<Status> S = status(Dir, *E);
506 if (!S) {
507 EC = S.getError();
508 return directory_iterator();
509 }
510 if (!S->isDirectory()) {
511 EC = std::error_code(static_cast<int>(errc::not_a_directory),
512 std::system_category());
513 return directory_iterator();
514 }
515
516 DirectoryEntry *D = cast<DirectoryEntry>(*E);
517 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
518 *this, D->contents_begin(), D->contents_end(), EC));
519 }
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000520};
521
522/// \brief A helper class to hold the common YAML parsing state.
523class VFSFromYAMLParser {
524 yaml::Stream &Stream;
525
526 void error(yaml::Node *N, const Twine &Msg) {
527 Stream.printError(N, Msg);
528 }
529
530 // false on error
531 bool parseScalarString(yaml::Node *N, StringRef &Result,
532 SmallVectorImpl<char> &Storage) {
533 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
534 if (!S) {
535 error(N, "expected string");
536 return false;
537 }
538 Result = S->getValue(Storage);
539 return true;
540 }
541
542 // false on error
543 bool parseScalarBool(yaml::Node *N, bool &Result) {
544 SmallString<5> Storage;
545 StringRef Value;
546 if (!parseScalarString(N, Value, Storage))
547 return false;
548
549 if (Value.equals_lower("true") || Value.equals_lower("on") ||
550 Value.equals_lower("yes") || Value == "1") {
551 Result = true;
552 return true;
553 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
554 Value.equals_lower("no") || Value == "0") {
555 Result = false;
556 return true;
557 }
558
559 error(N, "expected boolean value");
560 return false;
561 }
562
563 struct KeyStatus {
564 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
565 bool Required;
566 bool Seen;
567 };
568 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
569
570 // false on error
571 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
572 DenseMap<StringRef, KeyStatus> &Keys) {
573 if (!Keys.count(Key)) {
574 error(KeyNode, "unknown key");
575 return false;
576 }
577 KeyStatus &S = Keys[Key];
578 if (S.Seen) {
579 error(KeyNode, Twine("duplicate key '") + Key + "'");
580 return false;
581 }
582 S.Seen = true;
583 return true;
584 }
585
586 // false on error
587 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
588 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
589 E = Keys.end();
590 I != E; ++I) {
591 if (I->second.Required && !I->second.Seen) {
592 error(Obj, Twine("missing key '") + I->first + "'");
593 return false;
594 }
595 }
596 return true;
597 }
598
599 Entry *parseEntry(yaml::Node *N) {
600 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
601 if (!M) {
602 error(N, "expected mapping node for file or directory entry");
Craig Topperf1186c52014-05-08 06:41:40 +0000603 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000604 }
605
606 KeyStatusPair Fields[] = {
607 KeyStatusPair("name", true),
608 KeyStatusPair("type", true),
609 KeyStatusPair("contents", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +0000610 KeyStatusPair("external-contents", false),
611 KeyStatusPair("use-external-name", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000612 };
613
614 DenseMap<StringRef, KeyStatus> Keys(
615 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
616
617 bool HasContents = false; // external or otherwise
618 std::vector<Entry *> EntryArrayContents;
619 std::string ExternalContentsPath;
620 std::string Name;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000621 FileEntry::NameKind UseExternalName = FileEntry::NK_NotSet;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000622 EntryKind Kind;
623
624 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
625 ++I) {
626 StringRef Key;
627 // Reuse the buffer for key and value, since we don't look at key after
628 // parsing value.
629 SmallString<256> Buffer;
630 if (!parseScalarString(I->getKey(), Key, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000631 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000632
633 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +0000634 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000635
636 StringRef Value;
637 if (Key == "name") {
638 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000639 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000640 Name = Value;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000641 } else if (Key == "type") {
642 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000643 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000644 if (Value == "file")
645 Kind = EK_File;
646 else if (Value == "directory")
647 Kind = EK_Directory;
648 else {
649 error(I->getValue(), "unknown value for 'type'");
Craig Topperf1186c52014-05-08 06:41:40 +0000650 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000651 }
652 } else if (Key == "contents") {
653 if (HasContents) {
654 error(I->getKey(),
655 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +0000656 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000657 }
658 HasContents = true;
659 yaml::SequenceNode *Contents =
660 dyn_cast<yaml::SequenceNode>(I->getValue());
661 if (!Contents) {
662 // FIXME: this is only for directories, what about files?
663 error(I->getValue(), "expected array");
Craig Topperf1186c52014-05-08 06:41:40 +0000664 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000665 }
666
667 for (yaml::SequenceNode::iterator I = Contents->begin(),
668 E = Contents->end();
669 I != E; ++I) {
670 if (Entry *E = parseEntry(&*I))
671 EntryArrayContents.push_back(E);
672 else
Craig Topperf1186c52014-05-08 06:41:40 +0000673 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000674 }
675 } else if (Key == "external-contents") {
676 if (HasContents) {
677 error(I->getKey(),
678 "entry already has 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +0000679 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000680 }
681 HasContents = true;
682 if (!parseScalarString(I->getValue(), Value, Buffer))
Craig Topperf1186c52014-05-08 06:41:40 +0000683 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000684 ExternalContentsPath = Value;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000685 } else if (Key == "use-external-name") {
686 bool Val;
687 if (!parseScalarBool(I->getValue(), Val))
Craig Topperf1186c52014-05-08 06:41:40 +0000688 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000689 UseExternalName = Val ? FileEntry::NK_External : FileEntry::NK_Virtual;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000690 } else {
691 llvm_unreachable("key missing from Keys");
692 }
693 }
694
695 if (Stream.failed())
Craig Topperf1186c52014-05-08 06:41:40 +0000696 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000697
698 // check for missing keys
699 if (!HasContents) {
700 error(N, "missing key 'contents' or 'external-contents'");
Craig Topperf1186c52014-05-08 06:41:40 +0000701 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000702 }
703 if (!checkMissingKeys(N, Keys))
Craig Topperf1186c52014-05-08 06:41:40 +0000704 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000705
Ben Langmuirb59cf672014-02-27 00:25:12 +0000706 // check invalid configuration
707 if (Kind == EK_Directory && UseExternalName != FileEntry::NK_NotSet) {
708 error(N, "'use-external-name' is not supported for directories");
Craig Topperf1186c52014-05-08 06:41:40 +0000709 return nullptr;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000710 }
711
Ben Langmuir93853232014-03-05 21:32:20 +0000712 // Remove trailing slash(es), being careful not to remove the root path
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000713 StringRef Trimmed(Name);
Ben Langmuir93853232014-03-05 21:32:20 +0000714 size_t RootPathLen = sys::path::root_path(Trimmed).size();
715 while (Trimmed.size() > RootPathLen &&
716 sys::path::is_separator(Trimmed.back()))
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000717 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
718 // Get the last component
719 StringRef LastComponent = sys::path::filename(Trimmed);
720
Craig Topperf1186c52014-05-08 06:41:40 +0000721 Entry *Result = nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000722 switch (Kind) {
723 case EK_File:
Chandler Carruthc72d9b32014-03-02 04:02:40 +0000724 Result = new FileEntry(LastComponent, std::move(ExternalContentsPath),
Ben Langmuirb59cf672014-02-27 00:25:12 +0000725 UseExternalName);
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000726 break;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000727 case EK_Directory:
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000728 Result = new DirectoryEntry(
729 LastComponent, std::move(EntryArrayContents),
730 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
731 file_type::directory_file, sys::fs::all_all));
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000732 break;
733 }
734
735 StringRef Parent = sys::path::parent_path(Trimmed);
736 if (Parent.empty())
737 return Result;
738
739 // if 'name' contains multiple components, create implicit directory entries
740 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
741 E = sys::path::rend(Parent);
742 I != E; ++I) {
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000743 Result = new DirectoryEntry(
744 *I, llvm::makeArrayRef(Result),
745 Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
746 file_type::directory_file, sys::fs::all_all));
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000747 }
Ben Langmuir47ff9ab2014-02-25 04:34:14 +0000748 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000749 }
750
751public:
752 VFSFromYAMLParser(yaml::Stream &S) : Stream(S) {}
753
754 // false on error
755 bool parse(yaml::Node *Root, VFSFromYAML *FS) {
756 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
757 if (!Top) {
758 error(Root, "expected mapping node");
759 return false;
760 }
761
762 KeyStatusPair Fields[] = {
763 KeyStatusPair("version", true),
764 KeyStatusPair("case-sensitive", false),
Ben Langmuirb59cf672014-02-27 00:25:12 +0000765 KeyStatusPair("use-external-names", false),
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000766 KeyStatusPair("roots", true),
767 };
768
769 DenseMap<StringRef, KeyStatus> Keys(
770 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
771
772 // Parse configuration and 'roots'
773 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
774 ++I) {
775 SmallString<10> KeyBuffer;
776 StringRef Key;
777 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
778 return false;
779
780 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
781 return false;
782
783 if (Key == "roots") {
784 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
785 if (!Roots) {
786 error(I->getValue(), "expected array");
787 return false;
788 }
789
790 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
791 I != E; ++I) {
792 if (Entry *E = parseEntry(&*I))
793 FS->Roots.push_back(E);
794 else
795 return false;
796 }
797 } else if (Key == "version") {
798 StringRef VersionString;
799 SmallString<4> Storage;
800 if (!parseScalarString(I->getValue(), VersionString, Storage))
801 return false;
802 int Version;
803 if (VersionString.getAsInteger<int>(10, Version)) {
804 error(I->getValue(), "expected integer");
805 return false;
806 }
807 if (Version < 0) {
808 error(I->getValue(), "invalid version number");
809 return false;
810 }
811 if (Version != 0) {
812 error(I->getValue(), "version mismatch, expected 0");
813 return false;
814 }
815 } else if (Key == "case-sensitive") {
816 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
817 return false;
Ben Langmuirb59cf672014-02-27 00:25:12 +0000818 } else if (Key == "use-external-names") {
819 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
820 return false;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000821 } else {
822 llvm_unreachable("key missing from Keys");
823 }
824 }
825
826 if (Stream.failed())
827 return false;
828
829 if (!checkMissingKeys(Top, Keys))
830 return false;
831 return true;
832 }
833};
834} // end of anonymous namespace
835
836Entry::~Entry() {}
837DirectoryEntry::~DirectoryEntry() { llvm::DeleteContainerPointers(Contents); }
838
839VFSFromYAML::~VFSFromYAML() { llvm::DeleteContainerPointers(Roots); }
840
Rafael Espindola04ab21d72014-08-17 22:12:58 +0000841VFSFromYAML *VFSFromYAML::create(std::unique_ptr<MemoryBuffer> Buffer,
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000842 SourceMgr::DiagHandlerTy DiagHandler,
Ben Langmuir97882e72014-02-24 20:56:37 +0000843 void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000844 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
845
846 SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +0000847 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000848
Ben Langmuir97882e72014-02-24 20:56:37 +0000849 SM.setDiagHandler(DiagHandler, DiagContext);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000850 yaml::document_iterator DI = Stream.begin();
851 yaml::Node *Root = DI->getRoot();
852 if (DI == Stream.end() || !Root) {
853 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Craig Topperf1186c52014-05-08 06:41:40 +0000854 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000855 }
856
857 VFSFromYAMLParser P(Stream);
858
Ahmed Charlesb8984322014-03-07 20:03:18 +0000859 std::unique_ptr<VFSFromYAML> FS(new VFSFromYAML(ExternalFS));
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000860 if (!P.parse(Root, FS.get()))
Craig Topperf1186c52014-05-08 06:41:40 +0000861 return nullptr;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000862
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000863 return FS.release();
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000864}
865
866ErrorOr<Entry *> VFSFromYAML::lookupPath(const Twine &Path_) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +0000867 SmallString<256> Path;
868 Path_.toVector(Path);
869
870 // Handle relative paths
Rafael Espindola8e650d72014-06-12 20:37:59 +0000871 if (std::error_code EC = sys::fs::make_absolute(Path))
Ben Langmuira6f8ca82014-03-04 22:34:50 +0000872 return EC;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000873
874 if (Path.empty())
Rafael Espindola71de0b62014-06-13 17:20:50 +0000875 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000876
877 sys::path::const_iterator Start = sys::path::begin(Path);
878 sys::path::const_iterator End = sys::path::end(Path);
879 for (std::vector<Entry *>::iterator I = Roots.begin(), E = Roots.end();
880 I != E; ++I) {
881 ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000882 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000883 return Result;
884 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000885 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000886}
887
888ErrorOr<Entry *> VFSFromYAML::lookupPath(sys::path::const_iterator Start,
889 sys::path::const_iterator End,
890 Entry *From) {
Ben Langmuira6f8ca82014-03-04 22:34:50 +0000891 if (Start->equals("."))
892 ++Start;
893
894 // FIXME: handle ..
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000895 if (CaseSensitive ? !Start->equals(From->getName())
896 : !Start->equals_lower(From->getName()))
897 // failure to match
Rafael Espindola71de0b62014-06-13 17:20:50 +0000898 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000899
900 ++Start;
901
902 if (Start == End) {
903 // Match!
904 return From;
905 }
906
907 DirectoryEntry *DE = dyn_cast<DirectoryEntry>(From);
908 if (!DE)
Rafael Espindola71de0b62014-06-13 17:20:50 +0000909 return make_error_code(llvm::errc::not_a_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000910
911 for (DirectoryEntry::iterator I = DE->contents_begin(),
912 E = DE->contents_end();
913 I != E; ++I) {
914 ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
Rafael Espindola71de0b62014-06-13 17:20:50 +0000915 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000916 return Result;
917 }
Rafael Espindola71de0b62014-06-13 17:20:50 +0000918 return make_error_code(llvm::errc::no_such_file_or_directory);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000919}
920
Ben Langmuir740812b2014-06-24 19:37:16 +0000921ErrorOr<Status> VFSFromYAML::status(const Twine &Path, Entry *E) {
922 assert(E != nullptr);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000923 std::string PathStr(Path.str());
Ben Langmuir740812b2014-06-24 19:37:16 +0000924 if (FileEntry *F = dyn_cast<FileEntry>(E)) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000925 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
Ben Langmuirb59cf672014-02-27 00:25:12 +0000926 assert(!S || S->getName() == F->getExternalContentsPath());
Ben Langmuird066d4c2014-02-28 21:16:07 +0000927 if (S && !F->useExternalName(UseExternalNames))
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000928 *S = Status::copyWithNewName(*S, PathStr);
Ben Langmuir5de00f32014-05-23 18:15:47 +0000929 if (S)
930 S->IsVFSMapped = true;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000931 return S;
932 } else { // directory
Ben Langmuir740812b2014-06-24 19:37:16 +0000933 DirectoryEntry *DE = cast<DirectoryEntry>(E);
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000934 return Status::copyWithNewName(DE->getStatus(), PathStr);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000935 }
936}
937
Ben Langmuir740812b2014-06-24 19:37:16 +0000938ErrorOr<Status> VFSFromYAML::status(const Twine &Path) {
939 ErrorOr<Entry *> Result = lookupPath(Path);
940 if (!Result)
941 return Result.getError();
942 return status(Path, *Result);
943}
944
Benjamin Kramer5532ef12015-10-05 13:55:09 +0000945namespace {
946/// Provide a file wrapper that returns the external name when asked.
947class NamedFileAdaptor : public File {
948 std::unique_ptr<File> InnerFile;
949 std::string NewName;
950
951public:
952 NamedFileAdaptor(std::unique_ptr<File> InnerFile, std::string NewName)
953 : InnerFile(std::move(InnerFile)), NewName(std::move(NewName)) {}
954
955 llvm::ErrorOr<Status> status() override {
956 auto InnerStatus = InnerFile->status();
957 if (InnerStatus)
958 return Status::copyWithNewName(*InnerStatus, NewName);
959 return InnerStatus.getError();
960 }
961 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
962 getBuffer(const Twine &Name, int64_t FileSize = -1,
963 bool RequiresNullTerminator = true,
964 bool IsVolatile = false) override {
965 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
966 IsVolatile);
967 }
968 std::error_code close() override { return InnerFile->close(); }
969};
970} // end anonymous namespace
971
Benjamin Kramera8857962014-10-26 22:44:13 +0000972ErrorOr<std::unique_ptr<File>> VFSFromYAML::openFileForRead(const Twine &Path) {
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000973 ErrorOr<Entry *> E = lookupPath(Path);
974 if (!E)
975 return E.getError();
976
977 FileEntry *F = dyn_cast<FileEntry>(*E);
978 if (!F) // FIXME: errc::not_a_file?
Rafael Espindola71de0b62014-06-13 17:20:50 +0000979 return make_error_code(llvm::errc::invalid_argument);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000980
Benjamin Kramera8857962014-10-26 22:44:13 +0000981 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
982 if (!Result)
983 return Result;
Ben Langmuird066d4c2014-02-28 21:16:07 +0000984
Benjamin Kramer5532ef12015-10-05 13:55:09 +0000985 if (!F->useExternalName(UseExternalNames))
Benjamin Kramer268b51a2015-10-05 13:15:33 +0000986 return std::unique_ptr<File>(
987 new NamedFileAdaptor(std::move(*Result), Path.str()));
Ben Langmuird066d4c2014-02-28 21:16:07 +0000988
Benjamin Kramera8857962014-10-26 22:44:13 +0000989 return Result;
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000990}
991
992IntrusiveRefCntPtr<FileSystem>
Rafael Espindola04ab21d72014-08-17 22:12:58 +0000993vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
994 SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext,
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000995 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
Rafael Espindola04ab21d72014-08-17 22:12:58 +0000996 return VFSFromYAML::create(std::move(Buffer), DiagHandler, DiagContext,
997 ExternalFS);
Ben Langmuird51ba0b2014-02-21 23:39:37 +0000998}
999
1000UniqueID vfs::getNextVirtualUniqueID() {
Benjamin Kramer4527fb22014-03-02 17:08:31 +00001001 static std::atomic<unsigned> UID;
1002 unsigned ID = ++UID;
Ben Langmuird51ba0b2014-02-21 23:39:37 +00001003 // The following assumes that uint64_t max will never collide with a real
1004 // dev_t value from the OS.
1005 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1006}
Justin Bogner9c785292014-05-20 21:43:27 +00001007
1008#ifndef NDEBUG
1009static bool pathHasTraversal(StringRef Path) {
1010 using namespace llvm::sys;
1011 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
1012 if (Comp == "." || Comp == "..")
1013 return true;
1014 return false;
1015}
1016#endif
1017
1018void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1019 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1020 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1021 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1022 Mappings.emplace_back(VirtualPath, RealPath);
1023}
1024
Justin Bogner44fa450342014-05-21 22:46:51 +00001025namespace {
1026class JSONWriter {
1027 llvm::raw_ostream &OS;
1028 SmallVector<StringRef, 16> DirStack;
1029 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
1030 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1031 bool containedIn(StringRef Parent, StringRef Path);
1032 StringRef containedPart(StringRef Parent, StringRef Path);
1033 void startDirectory(StringRef Path);
1034 void endDirectory();
1035 void writeEntry(StringRef VPath, StringRef RPath);
1036
1037public:
1038 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
1039 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive);
1040};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001041}
Justin Bogner9c785292014-05-20 21:43:27 +00001042
Justin Bogner44fa450342014-05-21 22:46:51 +00001043bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
Justin Bogner1c078f22014-05-20 22:12:58 +00001044 using namespace llvm::sys;
1045 // Compare each path component.
1046 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1047 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1048 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1049 if (*IParent != *IChild)
1050 return false;
1051 }
1052 // Have we exhausted the parent path?
1053 return IParent == EParent;
Justin Bogner9c785292014-05-20 21:43:27 +00001054}
1055
Justin Bogner44fa450342014-05-21 22:46:51 +00001056StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1057 assert(!Parent.empty());
Justin Bogner9c785292014-05-20 21:43:27 +00001058 assert(containedIn(Parent, Path));
Justin Bogner9c785292014-05-20 21:43:27 +00001059 return Path.slice(Parent.size() + 1, StringRef::npos);
1060}
1061
Justin Bogner44fa450342014-05-21 22:46:51 +00001062void JSONWriter::startDirectory(StringRef Path) {
1063 StringRef Name =
1064 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1065 DirStack.push_back(Path);
1066 unsigned Indent = getDirIndent();
1067 OS.indent(Indent) << "{\n";
1068 OS.indent(Indent + 2) << "'type': 'directory',\n";
1069 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1070 OS.indent(Indent + 2) << "'contents': [\n";
1071}
1072
1073void JSONWriter::endDirectory() {
1074 unsigned Indent = getDirIndent();
1075 OS.indent(Indent + 2) << "]\n";
1076 OS.indent(Indent) << "}";
1077
1078 DirStack.pop_back();
1079}
1080
1081void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1082 unsigned Indent = getFileIndent();
1083 OS.indent(Indent) << "{\n";
1084 OS.indent(Indent + 2) << "'type': 'file',\n";
1085 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1086 OS.indent(Indent + 2) << "'external-contents': \""
1087 << llvm::yaml::escape(RPath) << "\"\n";
1088 OS.indent(Indent) << "}";
1089}
1090
1091void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
1092 Optional<bool> IsCaseSensitive) {
1093 using namespace llvm::sys;
1094
1095 OS << "{\n"
1096 " 'version': 0,\n";
1097 if (IsCaseSensitive.hasValue())
1098 OS << " 'case-sensitive': '"
1099 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
1100 OS << " 'roots': [\n";
1101
Justin Bogner73466402014-07-15 01:24:35 +00001102 if (!Entries.empty()) {
1103 const YAMLVFSEntry &Entry = Entries.front();
1104 startDirectory(path::parent_path(Entry.VPath));
Justin Bogner44fa450342014-05-21 22:46:51 +00001105 writeEntry(path::filename(Entry.VPath), Entry.RPath);
Justin Bogner44fa450342014-05-21 22:46:51 +00001106
Justin Bogner73466402014-07-15 01:24:35 +00001107 for (const auto &Entry : Entries.slice(1)) {
1108 StringRef Dir = path::parent_path(Entry.VPath);
1109 if (Dir == DirStack.back())
1110 OS << ",\n";
1111 else {
1112 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1113 OS << "\n";
1114 endDirectory();
1115 }
1116 OS << ",\n";
1117 startDirectory(Dir);
1118 }
1119 writeEntry(path::filename(Entry.VPath), Entry.RPath);
1120 }
1121
1122 while (!DirStack.empty()) {
1123 OS << "\n";
1124 endDirectory();
1125 }
Justin Bogner44fa450342014-05-21 22:46:51 +00001126 OS << "\n";
Justin Bogner44fa450342014-05-21 22:46:51 +00001127 }
1128
Justin Bogner73466402014-07-15 01:24:35 +00001129 OS << " ]\n"
Justin Bogner44fa450342014-05-21 22:46:51 +00001130 << "}\n";
1131}
1132
Justin Bogner9c785292014-05-20 21:43:27 +00001133void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1134 std::sort(Mappings.begin(), Mappings.end(),
Justin Bogner44fa450342014-05-21 22:46:51 +00001135 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
Justin Bogner9c785292014-05-20 21:43:27 +00001136 return LHS.VPath < RHS.VPath;
1137 });
1138
Justin Bogner44fa450342014-05-21 22:46:51 +00001139 JSONWriter(OS).write(Mappings, IsCaseSensitive);
Justin Bogner9c785292014-05-20 21:43:27 +00001140}
Ben Langmuir740812b2014-06-24 19:37:16 +00001141
1142VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(const Twine &_Path,
1143 VFSFromYAML &FS,
1144 DirectoryEntry::iterator Begin,
1145 DirectoryEntry::iterator End,
1146 std::error_code &EC)
1147 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
1148 if (Current != End) {
1149 SmallString<128> PathStr(Dir);
1150 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001151 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001152 if (S)
1153 CurrentEntry = *S;
1154 else
1155 EC = S.getError();
1156 }
1157}
1158
1159std::error_code VFSFromYamlDirIterImpl::increment() {
1160 assert(Current != End && "cannot iterate past end");
1161 if (++Current != End) {
1162 SmallString<128> PathStr(Dir);
1163 llvm::sys::path::append(PathStr, (*Current)->getName());
Yaron Keren92e1b622015-03-18 10:17:07 +00001164 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
Ben Langmuir740812b2014-06-24 19:37:16 +00001165 if (!S)
1166 return S.getError();
1167 CurrentEntry = *S;
1168 } else {
1169 CurrentEntry = Status();
1170 }
1171 return std::error_code();
1172}
Ben Langmuir7c9f6c82014-06-25 20:25:40 +00001173
1174vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1175 const Twine &Path,
1176 std::error_code &EC)
1177 : FS(&FS_) {
1178 directory_iterator I = FS->dir_begin(Path, EC);
1179 if (!EC && I != directory_iterator()) {
1180 State = std::make_shared<IterState>();
1181 State->push(I);
1182 }
1183}
1184
1185vfs::recursive_directory_iterator &
1186recursive_directory_iterator::increment(std::error_code &EC) {
1187 assert(FS && State && !State->empty() && "incrementing past end");
1188 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1189 vfs::directory_iterator End;
1190 if (State->top()->isDirectory()) {
1191 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
1192 if (EC)
1193 return *this;
1194 if (I != End) {
1195 State->push(I);
1196 return *this;
1197 }
1198 }
1199
1200 while (!State->empty() && State->top().increment(EC) == End)
1201 State->pop();
1202
1203 if (State->empty())
1204 State.reset(); // end iterator
1205
1206 return *this;
Rafael Espindola2d2b4202014-07-06 17:43:24 +00001207}