VirtualFileSystem.cpp 38 KB

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