VirtualFileSystem.cpp 38 KB

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