blob: a469c9abc392d7155395d783c91833610b094a41 [file] [log] [blame]
Stephen Hines651f13c2014-04-23 16:59:28 -07001//===- 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"
13#include "llvm/ADT/DenseMap.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070014#include "llvm/ADT/iterator_range.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070015#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/Support/MemoryBuffer.h"
18#include "llvm/Support/Path.h"
19#include "llvm/Support/YAMLParser.h"
20#include <atomic>
21#include <memory>
22
23using namespace clang;
24using namespace clang::vfs;
25using namespace llvm;
26using llvm::sys::fs::file_status;
27using llvm::sys::fs::file_type;
28using llvm::sys::fs::perms;
29using llvm::sys::fs::UniqueID;
30
31Status::Status(const file_status &Status)
32 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
33 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
Stephen Hines6bcf27b2014-05-29 04:14:42 -070034 Type(Status.type()), Perms(Status.permissions()), IsVFSMapped(false) {}
Stephen Hines651f13c2014-04-23 16:59:28 -070035
36Status::Status(StringRef Name, StringRef ExternalName, UniqueID UID,
37 sys::TimeValue MTime, uint32_t User, uint32_t Group,
38 uint64_t Size, file_type Type, perms Perms)
39 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
Stephen Hines6bcf27b2014-05-29 04:14:42 -070040 Type(Type), Perms(Perms), IsVFSMapped(false) {}
Stephen Hines651f13c2014-04-23 16:59:28 -070041
42bool Status::equivalent(const Status &Other) const {
43 return getUniqueID() == Other.getUniqueID();
44}
45bool Status::isDirectory() const {
46 return Type == file_type::directory_file;
47}
48bool Status::isRegularFile() const {
49 return Type == file_type::regular_file;
50}
51bool Status::isOther() const {
52 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
53}
54bool Status::isSymlink() const {
55 return Type == file_type::symlink_file;
56}
57bool Status::isStatusKnown() const {
58 return Type != file_type::status_error;
59}
60bool Status::exists() const {
61 return isStatusKnown() && Type != file_type::file_not_found;
62}
63
64File::~File() {}
65
66FileSystem::~FileSystem() {}
67
68error_code FileSystem::getBufferForFile(const llvm::Twine &Name,
69 std::unique_ptr<MemoryBuffer> &Result,
70 int64_t FileSize,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070071 bool RequiresNullTerminator,
72 bool IsVolatile) {
Stephen Hines651f13c2014-04-23 16:59:28 -070073 std::unique_ptr<File> F;
74 if (error_code EC = openFileForRead(Name, F))
75 return EC;
76
Stephen Hines6bcf27b2014-05-29 04:14:42 -070077 error_code EC = F->getBuffer(Name, Result, FileSize, RequiresNullTerminator,
78 IsVolatile);
Stephen Hines651f13c2014-04-23 16:59:28 -070079 return EC;
80}
81
82//===-----------------------------------------------------------------------===/
83// RealFileSystem implementation
84//===-----------------------------------------------------------------------===/
85
86namespace {
87/// \brief Wrapper around a raw file descriptor.
88class RealFile : public File {
89 int FD;
90 Status S;
91 friend class RealFileSystem;
92 RealFile(int FD) : FD(FD) {
93 assert(FD >= 0 && "Invalid or inactive file descriptor");
94 }
95
96public:
97 ~RealFile();
98 ErrorOr<Status> status() override;
99 error_code getBuffer(const Twine &Name, std::unique_ptr<MemoryBuffer> &Result,
100 int64_t FileSize = -1,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700101 bool RequiresNullTerminator = true,
102 bool IsVolatile = false) override;
Stephen Hines651f13c2014-04-23 16:59:28 -0700103 error_code close() override;
104 void setName(StringRef Name) override;
105};
106} // end anonymous namespace
107RealFile::~RealFile() { close(); }
108
109ErrorOr<Status> RealFile::status() {
110 assert(FD != -1 && "cannot stat closed file");
111 if (!S.isStatusKnown()) {
112 file_status RealStatus;
113 if (error_code EC = sys::fs::status(FD, RealStatus))
114 return EC;
115 Status NewS(RealStatus);
116 NewS.setName(S.getName());
117 S = std::move(NewS);
118 }
119 return S;
120}
121
122error_code RealFile::getBuffer(const Twine &Name,
123 std::unique_ptr<MemoryBuffer> &Result,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700124 int64_t FileSize, bool RequiresNullTerminator,
125 bool IsVolatile) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700126 assert(FD != -1 && "cannot get buffer for closed file");
127 return MemoryBuffer::getOpenFile(FD, Name.str().c_str(), Result, FileSize,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700128 RequiresNullTerminator, IsVolatile);
Stephen Hines651f13c2014-04-23 16:59:28 -0700129}
130
131// FIXME: This is terrible, we need this for ::close.
132#if !defined(_MSC_VER) && !defined(__MINGW32__)
133#include <unistd.h>
134#include <sys/uio.h>
135#else
136#include <io.h>
137#ifndef S_ISFIFO
138#define S_ISFIFO(x) (0)
139#endif
140#endif
141error_code RealFile::close() {
142 if (::close(FD))
143 return error_code(errno, system_category());
144 FD = -1;
145 return error_code::success();
146}
147
148void RealFile::setName(StringRef Name) {
149 S.setName(Name);
150}
151
152namespace {
153/// \brief The file system according to your operating system.
154class RealFileSystem : public FileSystem {
155public:
156 ErrorOr<Status> status(const Twine &Path) override;
157 error_code openFileForRead(const Twine &Path,
158 std::unique_ptr<File> &Result) override;
159};
160} // end anonymous namespace
161
162ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
163 sys::fs::file_status RealStatus;
164 if (error_code EC = sys::fs::status(Path, RealStatus))
165 return EC;
166 Status Result(RealStatus);
167 Result.setName(Path.str());
168 return Result;
169}
170
171error_code RealFileSystem::openFileForRead(const Twine &Name,
172 std::unique_ptr<File> &Result) {
173 int FD;
174 if (error_code EC = sys::fs::openFileForRead(Name, FD))
175 return EC;
176 Result.reset(new RealFile(FD));
177 Result->setName(Name.str());
178 return error_code::success();
179}
180
181IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
182 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
183 return FS;
184}
185
186//===-----------------------------------------------------------------------===/
187// OverlayFileSystem implementation
188//===-----------------------------------------------------------------------===/
189OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
190 pushOverlay(BaseFS);
191}
192
193void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
194 FSList.push_back(FS);
195}
196
197ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
198 // FIXME: handle symlinks that cross file systems
199 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
200 ErrorOr<Status> Status = (*I)->status(Path);
201 if (Status || Status.getError() != errc::no_such_file_or_directory)
202 return Status;
203 }
204 return error_code(errc::no_such_file_or_directory, system_category());
205}
206
207error_code OverlayFileSystem::openFileForRead(const llvm::Twine &Path,
208 std::unique_ptr<File> &Result) {
209 // FIXME: handle symlinks that cross file systems
210 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
211 error_code EC = (*I)->openFileForRead(Path, Result);
212 if (!EC || EC != errc::no_such_file_or_directory)
213 return EC;
214 }
215 return error_code(errc::no_such_file_or_directory, system_category());
216}
217
218//===-----------------------------------------------------------------------===/
219// VFSFromYAML implementation
220//===-----------------------------------------------------------------------===/
221
222// Allow DenseMap<StringRef, ...>. This is useful below because we know all the
223// strings are literals and will outlive the map, and there is no reason to
224// store them.
225namespace llvm {
226 template<>
227 struct DenseMapInfo<StringRef> {
228 // This assumes that "" will never be a valid key.
229 static inline StringRef getEmptyKey() { return StringRef(""); }
230 static inline StringRef getTombstoneKey() { return StringRef(); }
231 static unsigned getHashValue(StringRef Val) { return HashString(Val); }
232 static bool isEqual(StringRef LHS, StringRef RHS) { return LHS == RHS; }
233 };
234}
235
236namespace {
237
238enum EntryKind {
239 EK_Directory,
240 EK_File
241};
242
243/// \brief A single file or directory in the VFS.
244class Entry {
245 EntryKind Kind;
246 std::string Name;
247
248public:
249 virtual ~Entry();
250 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
251 StringRef getName() const { return Name; }
252 EntryKind getKind() const { return Kind; }
253};
254
255class DirectoryEntry : public Entry {
256 std::vector<Entry *> Contents;
257 Status S;
258
259public:
260 virtual ~DirectoryEntry();
261 DirectoryEntry(StringRef Name, std::vector<Entry *> Contents, Status S)
262 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
263 S(std::move(S)) {}
264 Status getStatus() { return S; }
265 typedef std::vector<Entry *>::iterator iterator;
266 iterator contents_begin() { return Contents.begin(); }
267 iterator contents_end() { return Contents.end(); }
268 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
269};
270
271class FileEntry : public Entry {
272public:
273 enum NameKind {
274 NK_NotSet,
275 NK_External,
276 NK_Virtual
277 };
278private:
279 std::string ExternalContentsPath;
280 NameKind UseName;
281public:
282 FileEntry(StringRef Name, StringRef ExternalContentsPath, NameKind UseName)
283 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
284 UseName(UseName) {}
285 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
286 /// \brief whether to use the external path as the name for this file.
287 bool useExternalName(bool GlobalUseExternalName) const {
288 return UseName == NK_NotSet ? GlobalUseExternalName
289 : (UseName == NK_External);
290 }
291 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
292};
293
294/// \brief A virtual file system parsed from a YAML file.
295///
296/// Currently, this class allows creating virtual directories and mapping
297/// virtual file paths to existing external files, available in \c ExternalFS.
298///
299/// The basic structure of the parsed file is:
300/// \verbatim
301/// {
302/// 'version': <version number>,
303/// <optional configuration>
304/// 'roots': [
305/// <directory entries>
306/// ]
307/// }
308/// \endverbatim
309///
310/// All configuration options are optional.
311/// 'case-sensitive': <boolean, default=true>
312/// 'use-external-names': <boolean, default=true>
313///
314/// Virtual directories are represented as
315/// \verbatim
316/// {
317/// 'type': 'directory',
318/// 'name': <string>,
319/// 'contents': [ <file or directory entries> ]
320/// }
321/// \endverbatim
322///
323/// The default attributes for virtual directories are:
324/// \verbatim
325/// MTime = now() when created
326/// Perms = 0777
327/// User = Group = 0
328/// Size = 0
329/// UniqueID = unspecified unique value
330/// \endverbatim
331///
332/// Re-mapped files are represented as
333/// \verbatim
334/// {
335/// 'type': 'file',
336/// 'name': <string>,
337/// 'use-external-name': <boolean> # Optional
338/// 'external-contents': <path to external file>)
339/// }
340/// \endverbatim
341///
342/// and inherit their attributes from the external contents.
343///
344/// In both cases, the 'name' field may contain multiple path components (e.g.
345/// /path/to/file). However, any directory that contains more than one child
346/// must be uniquely represented by a directory entry.
347class VFSFromYAML : public vfs::FileSystem {
348 std::vector<Entry *> Roots; ///< The root(s) of the virtual file system.
349 /// \brief The file system to use for external references.
350 IntrusiveRefCntPtr<FileSystem> ExternalFS;
351
352 /// @name Configuration
353 /// @{
354
355 /// \brief Whether to perform case-sensitive comparisons.
356 ///
357 /// Currently, case-insensitive matching only works correctly with ASCII.
358 bool CaseSensitive;
359
360 /// \brief Whether to use to use the value of 'external-contents' for the
361 /// names of files. This global value is overridable on a per-file basis.
362 bool UseExternalNames;
363 /// @}
364
365 friend class VFSFromYAMLParser;
366
367private:
368 VFSFromYAML(IntrusiveRefCntPtr<FileSystem> ExternalFS)
369 : ExternalFS(ExternalFS), CaseSensitive(true), UseExternalNames(true) {}
370
371 /// \brief Looks up \p Path in \c Roots.
372 ErrorOr<Entry *> lookupPath(const Twine &Path);
373
374 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
375 /// recursing into the contents of \p From if it is a directory.
376 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
377 sys::path::const_iterator End, Entry *From);
378
379public:
380 ~VFSFromYAML();
381
382 /// \brief Parses \p Buffer, which is expected to be in YAML format and
383 /// returns a virtual file system representing its contents.
384 ///
385 /// Takes ownership of \p Buffer.
386 static VFSFromYAML *create(MemoryBuffer *Buffer,
387 SourceMgr::DiagHandlerTy DiagHandler,
388 void *DiagContext,
389 IntrusiveRefCntPtr<FileSystem> ExternalFS);
390
391 ErrorOr<Status> status(const Twine &Path) override;
392 error_code openFileForRead(const Twine &Path,
393 std::unique_ptr<File> &Result) override;
394};
395
396/// \brief A helper class to hold the common YAML parsing state.
397class VFSFromYAMLParser {
398 yaml::Stream &Stream;
399
400 void error(yaml::Node *N, const Twine &Msg) {
401 Stream.printError(N, Msg);
402 }
403
404 // false on error
405 bool parseScalarString(yaml::Node *N, StringRef &Result,
406 SmallVectorImpl<char> &Storage) {
407 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
408 if (!S) {
409 error(N, "expected string");
410 return false;
411 }
412 Result = S->getValue(Storage);
413 return true;
414 }
415
416 // false on error
417 bool parseScalarBool(yaml::Node *N, bool &Result) {
418 SmallString<5> Storage;
419 StringRef Value;
420 if (!parseScalarString(N, Value, Storage))
421 return false;
422
423 if (Value.equals_lower("true") || Value.equals_lower("on") ||
424 Value.equals_lower("yes") || Value == "1") {
425 Result = true;
426 return true;
427 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
428 Value.equals_lower("no") || Value == "0") {
429 Result = false;
430 return true;
431 }
432
433 error(N, "expected boolean value");
434 return false;
435 }
436
437 struct KeyStatus {
438 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
439 bool Required;
440 bool Seen;
441 };
442 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
443
444 // false on error
445 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
446 DenseMap<StringRef, KeyStatus> &Keys) {
447 if (!Keys.count(Key)) {
448 error(KeyNode, "unknown key");
449 return false;
450 }
451 KeyStatus &S = Keys[Key];
452 if (S.Seen) {
453 error(KeyNode, Twine("duplicate key '") + Key + "'");
454 return false;
455 }
456 S.Seen = true;
457 return true;
458 }
459
460 // false on error
461 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
462 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
463 E = Keys.end();
464 I != E; ++I) {
465 if (I->second.Required && !I->second.Seen) {
466 error(Obj, Twine("missing key '") + I->first + "'");
467 return false;
468 }
469 }
470 return true;
471 }
472
473 Entry *parseEntry(yaml::Node *N) {
474 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
475 if (!M) {
476 error(N, "expected mapping node for file or directory entry");
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700477 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700478 }
479
480 KeyStatusPair Fields[] = {
481 KeyStatusPair("name", true),
482 KeyStatusPair("type", true),
483 KeyStatusPair("contents", false),
484 KeyStatusPair("external-contents", false),
485 KeyStatusPair("use-external-name", false),
486 };
487
488 DenseMap<StringRef, KeyStatus> Keys(
489 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
490
491 bool HasContents = false; // external or otherwise
492 std::vector<Entry *> EntryArrayContents;
493 std::string ExternalContentsPath;
494 std::string Name;
495 FileEntry::NameKind UseExternalName = FileEntry::NK_NotSet;
496 EntryKind Kind;
497
498 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
499 ++I) {
500 StringRef Key;
501 // Reuse the buffer for key and value, since we don't look at key after
502 // parsing value.
503 SmallString<256> Buffer;
504 if (!parseScalarString(I->getKey(), Key, Buffer))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700505 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700506
507 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700508 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700509
510 StringRef Value;
511 if (Key == "name") {
512 if (!parseScalarString(I->getValue(), Value, Buffer))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700513 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700514 Name = Value;
515 } else if (Key == "type") {
516 if (!parseScalarString(I->getValue(), Value, Buffer))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700517 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700518 if (Value == "file")
519 Kind = EK_File;
520 else if (Value == "directory")
521 Kind = EK_Directory;
522 else {
523 error(I->getValue(), "unknown value for 'type'");
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700524 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700525 }
526 } else if (Key == "contents") {
527 if (HasContents) {
528 error(I->getKey(),
529 "entry already has 'contents' or 'external-contents'");
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700530 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700531 }
532 HasContents = true;
533 yaml::SequenceNode *Contents =
534 dyn_cast<yaml::SequenceNode>(I->getValue());
535 if (!Contents) {
536 // FIXME: this is only for directories, what about files?
537 error(I->getValue(), "expected array");
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700538 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700539 }
540
541 for (yaml::SequenceNode::iterator I = Contents->begin(),
542 E = Contents->end();
543 I != E; ++I) {
544 if (Entry *E = parseEntry(&*I))
545 EntryArrayContents.push_back(E);
546 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700547 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700548 }
549 } else if (Key == "external-contents") {
550 if (HasContents) {
551 error(I->getKey(),
552 "entry already has 'contents' or 'external-contents'");
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700553 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700554 }
555 HasContents = true;
556 if (!parseScalarString(I->getValue(), Value, Buffer))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700557 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700558 ExternalContentsPath = Value;
559 } else if (Key == "use-external-name") {
560 bool Val;
561 if (!parseScalarBool(I->getValue(), Val))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700562 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700563 UseExternalName = Val ? FileEntry::NK_External : FileEntry::NK_Virtual;
564 } else {
565 llvm_unreachable("key missing from Keys");
566 }
567 }
568
569 if (Stream.failed())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700570 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700571
572 // check for missing keys
573 if (!HasContents) {
574 error(N, "missing key 'contents' or 'external-contents'");
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700575 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700576 }
577 if (!checkMissingKeys(N, Keys))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700578 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700579
580 // check invalid configuration
581 if (Kind == EK_Directory && UseExternalName != FileEntry::NK_NotSet) {
582 error(N, "'use-external-name' is not supported for directories");
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700583 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700584 }
585
586 // Remove trailing slash(es), being careful not to remove the root path
587 StringRef Trimmed(Name);
588 size_t RootPathLen = sys::path::root_path(Trimmed).size();
589 while (Trimmed.size() > RootPathLen &&
590 sys::path::is_separator(Trimmed.back()))
591 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
592 // Get the last component
593 StringRef LastComponent = sys::path::filename(Trimmed);
594
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700595 Entry *Result = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700596 switch (Kind) {
597 case EK_File:
598 Result = new FileEntry(LastComponent, std::move(ExternalContentsPath),
599 UseExternalName);
600 break;
601 case EK_Directory:
602 Result = new DirectoryEntry(LastComponent, std::move(EntryArrayContents),
603 Status("", "", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0,
604 0, file_type::directory_file, sys::fs::all_all));
605 break;
606 }
607
608 StringRef Parent = sys::path::parent_path(Trimmed);
609 if (Parent.empty())
610 return Result;
611
612 // if 'name' contains multiple components, create implicit directory entries
613 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
614 E = sys::path::rend(Parent);
615 I != E; ++I) {
616 Result = new DirectoryEntry(*I, llvm::makeArrayRef(Result),
617 Status("", "", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0,
618 0, file_type::directory_file, sys::fs::all_all));
619 }
620 return Result;
621 }
622
623public:
624 VFSFromYAMLParser(yaml::Stream &S) : Stream(S) {}
625
626 // false on error
627 bool parse(yaml::Node *Root, VFSFromYAML *FS) {
628 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
629 if (!Top) {
630 error(Root, "expected mapping node");
631 return false;
632 }
633
634 KeyStatusPair Fields[] = {
635 KeyStatusPair("version", true),
636 KeyStatusPair("case-sensitive", false),
637 KeyStatusPair("use-external-names", false),
638 KeyStatusPair("roots", true),
639 };
640
641 DenseMap<StringRef, KeyStatus> Keys(
642 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
643
644 // Parse configuration and 'roots'
645 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
646 ++I) {
647 SmallString<10> KeyBuffer;
648 StringRef Key;
649 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
650 return false;
651
652 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
653 return false;
654
655 if (Key == "roots") {
656 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
657 if (!Roots) {
658 error(I->getValue(), "expected array");
659 return false;
660 }
661
662 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
663 I != E; ++I) {
664 if (Entry *E = parseEntry(&*I))
665 FS->Roots.push_back(E);
666 else
667 return false;
668 }
669 } else if (Key == "version") {
670 StringRef VersionString;
671 SmallString<4> Storage;
672 if (!parseScalarString(I->getValue(), VersionString, Storage))
673 return false;
674 int Version;
675 if (VersionString.getAsInteger<int>(10, Version)) {
676 error(I->getValue(), "expected integer");
677 return false;
678 }
679 if (Version < 0) {
680 error(I->getValue(), "invalid version number");
681 return false;
682 }
683 if (Version != 0) {
684 error(I->getValue(), "version mismatch, expected 0");
685 return false;
686 }
687 } else if (Key == "case-sensitive") {
688 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
689 return false;
690 } else if (Key == "use-external-names") {
691 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
692 return false;
693 } else {
694 llvm_unreachable("key missing from Keys");
695 }
696 }
697
698 if (Stream.failed())
699 return false;
700
701 if (!checkMissingKeys(Top, Keys))
702 return false;
703 return true;
704 }
705};
706} // end of anonymous namespace
707
708Entry::~Entry() {}
709DirectoryEntry::~DirectoryEntry() { llvm::DeleteContainerPointers(Contents); }
710
711VFSFromYAML::~VFSFromYAML() { llvm::DeleteContainerPointers(Roots); }
712
713VFSFromYAML *VFSFromYAML::create(MemoryBuffer *Buffer,
714 SourceMgr::DiagHandlerTy DiagHandler,
715 void *DiagContext,
716 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
717
718 SourceMgr SM;
719 yaml::Stream Stream(Buffer, SM);
720
721 SM.setDiagHandler(DiagHandler, DiagContext);
722 yaml::document_iterator DI = Stream.begin();
723 yaml::Node *Root = DI->getRoot();
724 if (DI == Stream.end() || !Root) {
725 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700726 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700727 }
728
729 VFSFromYAMLParser P(Stream);
730
731 std::unique_ptr<VFSFromYAML> FS(new VFSFromYAML(ExternalFS));
732 if (!P.parse(Root, FS.get()))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700733 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700734
735 return FS.release();
736}
737
738ErrorOr<Entry *> VFSFromYAML::lookupPath(const Twine &Path_) {
739 SmallString<256> Path;
740 Path_.toVector(Path);
741
742 // Handle relative paths
743 if (error_code EC = sys::fs::make_absolute(Path))
744 return EC;
745
746 if (Path.empty())
747 return error_code(errc::invalid_argument, system_category());
748
749 sys::path::const_iterator Start = sys::path::begin(Path);
750 sys::path::const_iterator End = sys::path::end(Path);
751 for (std::vector<Entry *>::iterator I = Roots.begin(), E = Roots.end();
752 I != E; ++I) {
753 ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
754 if (Result || Result.getError() != errc::no_such_file_or_directory)
755 return Result;
756 }
757 return error_code(errc::no_such_file_or_directory, system_category());
758}
759
760ErrorOr<Entry *> VFSFromYAML::lookupPath(sys::path::const_iterator Start,
761 sys::path::const_iterator End,
762 Entry *From) {
763 if (Start->equals("."))
764 ++Start;
765
766 // FIXME: handle ..
767 if (CaseSensitive ? !Start->equals(From->getName())
768 : !Start->equals_lower(From->getName()))
769 // failure to match
770 return error_code(errc::no_such_file_or_directory, system_category());
771
772 ++Start;
773
774 if (Start == End) {
775 // Match!
776 return From;
777 }
778
779 DirectoryEntry *DE = dyn_cast<DirectoryEntry>(From);
780 if (!DE)
781 return error_code(errc::not_a_directory, system_category());
782
783 for (DirectoryEntry::iterator I = DE->contents_begin(),
784 E = DE->contents_end();
785 I != E; ++I) {
786 ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
787 if (Result || Result.getError() != errc::no_such_file_or_directory)
788 return Result;
789 }
790 return error_code(errc::no_such_file_or_directory, system_category());
791}
792
793ErrorOr<Status> VFSFromYAML::status(const Twine &Path) {
794 ErrorOr<Entry *> Result = lookupPath(Path);
795 if (!Result)
796 return Result.getError();
797
798 std::string PathStr(Path.str());
799 if (FileEntry *F = dyn_cast<FileEntry>(*Result)) {
800 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
801 assert(!S || S->getName() == F->getExternalContentsPath());
802 if (S && !F->useExternalName(UseExternalNames))
803 S->setName(PathStr);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700804 if (S)
805 S->IsVFSMapped = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700806 return S;
807 } else { // directory
808 DirectoryEntry *DE = cast<DirectoryEntry>(*Result);
809 Status S = DE->getStatus();
810 S.setName(PathStr);
811 return S;
812 }
813}
814
815error_code VFSFromYAML::openFileForRead(const Twine &Path,
816 std::unique_ptr<vfs::File> &Result) {
817 ErrorOr<Entry *> E = lookupPath(Path);
818 if (!E)
819 return E.getError();
820
821 FileEntry *F = dyn_cast<FileEntry>(*E);
822 if (!F) // FIXME: errc::not_a_file?
823 return error_code(errc::invalid_argument, system_category());
824
825 if (error_code EC = ExternalFS->openFileForRead(F->getExternalContentsPath(),
826 Result))
827 return EC;
828
829 if (!F->useExternalName(UseExternalNames))
830 Result->setName(Path.str());
831
832 return error_code::success();
833}
834
835IntrusiveRefCntPtr<FileSystem>
836vfs::getVFSFromYAML(MemoryBuffer *Buffer, SourceMgr::DiagHandlerTy DiagHandler,
837 void *DiagContext,
838 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
839 return VFSFromYAML::create(Buffer, DiagHandler, DiagContext, ExternalFS);
840}
841
842UniqueID vfs::getNextVirtualUniqueID() {
843 static std::atomic<unsigned> UID;
844 unsigned ID = ++UID;
845 // The following assumes that uint64_t max will never collide with a real
846 // dev_t value from the OS.
847 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
848}
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700849
850#ifndef NDEBUG
851static bool pathHasTraversal(StringRef Path) {
852 using namespace llvm::sys;
853 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
854 if (Comp == "." || Comp == "..")
855 return true;
856 return false;
857}
858#endif
859
860void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
861 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
862 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
863 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
864 Mappings.emplace_back(VirtualPath, RealPath);
865}
866
867namespace {
868class JSONWriter {
869 llvm::raw_ostream &OS;
870 SmallVector<StringRef, 16> DirStack;
871 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
872 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
873 bool containedIn(StringRef Parent, StringRef Path);
874 StringRef containedPart(StringRef Parent, StringRef Path);
875 void startDirectory(StringRef Path);
876 void endDirectory();
877 void writeEntry(StringRef VPath, StringRef RPath);
878
879public:
880 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
881 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive);
882};
883}
884
885bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
886 using namespace llvm::sys;
887 // Compare each path component.
888 auto IParent = path::begin(Parent), EParent = path::end(Parent);
889 for (auto IChild = path::begin(Path), EChild = path::end(Path);
890 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
891 if (*IParent != *IChild)
892 return false;
893 }
894 // Have we exhausted the parent path?
895 return IParent == EParent;
896}
897
898StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
899 assert(!Parent.empty());
900 assert(containedIn(Parent, Path));
901 return Path.slice(Parent.size() + 1, StringRef::npos);
902}
903
904void JSONWriter::startDirectory(StringRef Path) {
905 StringRef Name =
906 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
907 DirStack.push_back(Path);
908 unsigned Indent = getDirIndent();
909 OS.indent(Indent) << "{\n";
910 OS.indent(Indent + 2) << "'type': 'directory',\n";
911 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
912 OS.indent(Indent + 2) << "'contents': [\n";
913}
914
915void JSONWriter::endDirectory() {
916 unsigned Indent = getDirIndent();
917 OS.indent(Indent + 2) << "]\n";
918 OS.indent(Indent) << "}";
919
920 DirStack.pop_back();
921}
922
923void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
924 unsigned Indent = getFileIndent();
925 OS.indent(Indent) << "{\n";
926 OS.indent(Indent + 2) << "'type': 'file',\n";
927 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
928 OS.indent(Indent + 2) << "'external-contents': \""
929 << llvm::yaml::escape(RPath) << "\"\n";
930 OS.indent(Indent) << "}";
931}
932
933void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
934 Optional<bool> IsCaseSensitive) {
935 using namespace llvm::sys;
936
937 OS << "{\n"
938 " 'version': 0,\n";
939 if (IsCaseSensitive.hasValue())
940 OS << " 'case-sensitive': '"
941 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
942 OS << " 'roots': [\n";
943
944 if (Entries.empty())
945 return;
946
947 const YAMLVFSEntry &Entry = Entries.front();
948 startDirectory(path::parent_path(Entry.VPath));
949 writeEntry(path::filename(Entry.VPath), Entry.RPath);
950
951 for (const auto &Entry : Entries.slice(1)) {
952 StringRef Dir = path::parent_path(Entry.VPath);
953 if (Dir == DirStack.back())
954 OS << ",\n";
955 else {
956 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
957 OS << "\n";
958 endDirectory();
959 }
960 OS << ",\n";
961 startDirectory(Dir);
962 }
963 writeEntry(path::filename(Entry.VPath), Entry.RPath);
964 }
965
966 while (!DirStack.empty()) {
967 OS << "\n";
968 endDirectory();
969 }
970
971 OS << "\n"
972 << " ]\n"
973 << "}\n";
974}
975
976void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
977 std::sort(Mappings.begin(), Mappings.end(),
978 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
979 return LHS.VPath < RHS.VPath;
980 });
981
982 JSONWriter(OS).write(Mappings, IsCaseSensitive);
983}