VirtualFileSystem.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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. ///
  461. /// Takes ownership of \p Buffer.
  462. static VFSFromYAML *create(MemoryBuffer *Buffer,
  463. SourceMgr::DiagHandlerTy DiagHandler,
  464. void *DiagContext,
  465. IntrusiveRefCntPtr<FileSystem> ExternalFS);
  466. ErrorOr<Status> status(const Twine &Path) override;
  467. std::error_code openFileForRead(const Twine &Path,
  468. std::unique_ptr<File> &Result) override;
  469. directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
  470. ErrorOr<Entry *> E = lookupPath(Dir);
  471. if (!E) {
  472. EC = E.getError();
  473. return directory_iterator();
  474. }
  475. ErrorOr<Status> S = status(Dir, *E);
  476. if (!S) {
  477. EC = S.getError();
  478. return directory_iterator();
  479. }
  480. if (!S->isDirectory()) {
  481. EC = std::error_code(static_cast<int>(errc::not_a_directory),
  482. std::system_category());
  483. return directory_iterator();
  484. }
  485. DirectoryEntry *D = cast<DirectoryEntry>(*E);
  486. return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
  487. *this, D->contents_begin(), D->contents_end(), EC));
  488. }
  489. };
  490. /// \brief A helper class to hold the common YAML parsing state.
  491. class VFSFromYAMLParser {
  492. yaml::Stream &Stream;
  493. void error(yaml::Node *N, const Twine &Msg) {
  494. Stream.printError(N, Msg);
  495. }
  496. // false on error
  497. bool parseScalarString(yaml::Node *N, StringRef &Result,
  498. SmallVectorImpl<char> &Storage) {
  499. yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
  500. if (!S) {
  501. error(N, "expected string");
  502. return false;
  503. }
  504. Result = S->getValue(Storage);
  505. return true;
  506. }
  507. // false on error
  508. bool parseScalarBool(yaml::Node *N, bool &Result) {
  509. SmallString<5> Storage;
  510. StringRef Value;
  511. if (!parseScalarString(N, Value, Storage))
  512. return false;
  513. if (Value.equals_lower("true") || Value.equals_lower("on") ||
  514. Value.equals_lower("yes") || Value == "1") {
  515. Result = true;
  516. return true;
  517. } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
  518. Value.equals_lower("no") || Value == "0") {
  519. Result = false;
  520. return true;
  521. }
  522. error(N, "expected boolean value");
  523. return false;
  524. }
  525. struct KeyStatus {
  526. KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
  527. bool Required;
  528. bool Seen;
  529. };
  530. typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
  531. // false on error
  532. bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
  533. DenseMap<StringRef, KeyStatus> &Keys) {
  534. if (!Keys.count(Key)) {
  535. error(KeyNode, "unknown key");
  536. return false;
  537. }
  538. KeyStatus &S = Keys[Key];
  539. if (S.Seen) {
  540. error(KeyNode, Twine("duplicate key '") + Key + "'");
  541. return false;
  542. }
  543. S.Seen = true;
  544. return true;
  545. }
  546. // false on error
  547. bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
  548. for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
  549. E = Keys.end();
  550. I != E; ++I) {
  551. if (I->second.Required && !I->second.Seen) {
  552. error(Obj, Twine("missing key '") + I->first + "'");
  553. return false;
  554. }
  555. }
  556. return true;
  557. }
  558. Entry *parseEntry(yaml::Node *N) {
  559. yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
  560. if (!M) {
  561. error(N, "expected mapping node for file or directory entry");
  562. return nullptr;
  563. }
  564. KeyStatusPair Fields[] = {
  565. KeyStatusPair("name", true),
  566. KeyStatusPair("type", true),
  567. KeyStatusPair("contents", false),
  568. KeyStatusPair("external-contents", false),
  569. KeyStatusPair("use-external-name", false),
  570. };
  571. DenseMap<StringRef, KeyStatus> Keys(
  572. &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
  573. bool HasContents = false; // external or otherwise
  574. std::vector<Entry *> EntryArrayContents;
  575. std::string ExternalContentsPath;
  576. std::string Name;
  577. FileEntry::NameKind UseExternalName = FileEntry::NK_NotSet;
  578. EntryKind Kind;
  579. for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
  580. ++I) {
  581. StringRef Key;
  582. // Reuse the buffer for key and value, since we don't look at key after
  583. // parsing value.
  584. SmallString<256> Buffer;
  585. if (!parseScalarString(I->getKey(), Key, Buffer))
  586. return nullptr;
  587. if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
  588. return nullptr;
  589. StringRef Value;
  590. if (Key == "name") {
  591. if (!parseScalarString(I->getValue(), Value, Buffer))
  592. return nullptr;
  593. Name = Value;
  594. } else if (Key == "type") {
  595. if (!parseScalarString(I->getValue(), Value, Buffer))
  596. return nullptr;
  597. if (Value == "file")
  598. Kind = EK_File;
  599. else if (Value == "directory")
  600. Kind = EK_Directory;
  601. else {
  602. error(I->getValue(), "unknown value for 'type'");
  603. return nullptr;
  604. }
  605. } else if (Key == "contents") {
  606. if (HasContents) {
  607. error(I->getKey(),
  608. "entry already has 'contents' or 'external-contents'");
  609. return nullptr;
  610. }
  611. HasContents = true;
  612. yaml::SequenceNode *Contents =
  613. dyn_cast<yaml::SequenceNode>(I->getValue());
  614. if (!Contents) {
  615. // FIXME: this is only for directories, what about files?
  616. error(I->getValue(), "expected array");
  617. return nullptr;
  618. }
  619. for (yaml::SequenceNode::iterator I = Contents->begin(),
  620. E = Contents->end();
  621. I != E; ++I) {
  622. if (Entry *E = parseEntry(&*I))
  623. EntryArrayContents.push_back(E);
  624. else
  625. return nullptr;
  626. }
  627. } else if (Key == "external-contents") {
  628. if (HasContents) {
  629. error(I->getKey(),
  630. "entry already has 'contents' or 'external-contents'");
  631. return nullptr;
  632. }
  633. HasContents = true;
  634. if (!parseScalarString(I->getValue(), Value, Buffer))
  635. return nullptr;
  636. ExternalContentsPath = Value;
  637. } else if (Key == "use-external-name") {
  638. bool Val;
  639. if (!parseScalarBool(I->getValue(), Val))
  640. return nullptr;
  641. UseExternalName = Val ? FileEntry::NK_External : FileEntry::NK_Virtual;
  642. } else {
  643. llvm_unreachable("key missing from Keys");
  644. }
  645. }
  646. if (Stream.failed())
  647. return nullptr;
  648. // check for missing keys
  649. if (!HasContents) {
  650. error(N, "missing key 'contents' or 'external-contents'");
  651. return nullptr;
  652. }
  653. if (!checkMissingKeys(N, Keys))
  654. return nullptr;
  655. // check invalid configuration
  656. if (Kind == EK_Directory && UseExternalName != FileEntry::NK_NotSet) {
  657. error(N, "'use-external-name' is not supported for directories");
  658. return nullptr;
  659. }
  660. // Remove trailing slash(es), being careful not to remove the root path
  661. StringRef Trimmed(Name);
  662. size_t RootPathLen = sys::path::root_path(Trimmed).size();
  663. while (Trimmed.size() > RootPathLen &&
  664. sys::path::is_separator(Trimmed.back()))
  665. Trimmed = Trimmed.slice(0, Trimmed.size()-1);
  666. // Get the last component
  667. StringRef LastComponent = sys::path::filename(Trimmed);
  668. Entry *Result = nullptr;
  669. switch (Kind) {
  670. case EK_File:
  671. Result = new FileEntry(LastComponent, std::move(ExternalContentsPath),
  672. UseExternalName);
  673. break;
  674. case EK_Directory:
  675. Result = new DirectoryEntry(LastComponent, std::move(EntryArrayContents),
  676. Status("", "", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0,
  677. 0, file_type::directory_file, sys::fs::all_all));
  678. break;
  679. }
  680. StringRef Parent = sys::path::parent_path(Trimmed);
  681. if (Parent.empty())
  682. return Result;
  683. // if 'name' contains multiple components, create implicit directory entries
  684. for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
  685. E = sys::path::rend(Parent);
  686. I != E; ++I) {
  687. Result = new DirectoryEntry(*I, llvm::makeArrayRef(Result),
  688. Status("", "", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0,
  689. 0, file_type::directory_file, sys::fs::all_all));
  690. }
  691. return Result;
  692. }
  693. public:
  694. VFSFromYAMLParser(yaml::Stream &S) : Stream(S) {}
  695. // false on error
  696. bool parse(yaml::Node *Root, VFSFromYAML *FS) {
  697. yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
  698. if (!Top) {
  699. error(Root, "expected mapping node");
  700. return false;
  701. }
  702. KeyStatusPair Fields[] = {
  703. KeyStatusPair("version", true),
  704. KeyStatusPair("case-sensitive", false),
  705. KeyStatusPair("use-external-names", false),
  706. KeyStatusPair("roots", true),
  707. };
  708. DenseMap<StringRef, KeyStatus> Keys(
  709. &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
  710. // Parse configuration and 'roots'
  711. for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
  712. ++I) {
  713. SmallString<10> KeyBuffer;
  714. StringRef Key;
  715. if (!parseScalarString(I->getKey(), Key, KeyBuffer))
  716. return false;
  717. if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
  718. return false;
  719. if (Key == "roots") {
  720. yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
  721. if (!Roots) {
  722. error(I->getValue(), "expected array");
  723. return false;
  724. }
  725. for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
  726. I != E; ++I) {
  727. if (Entry *E = parseEntry(&*I))
  728. FS->Roots.push_back(E);
  729. else
  730. return false;
  731. }
  732. } else if (Key == "version") {
  733. StringRef VersionString;
  734. SmallString<4> Storage;
  735. if (!parseScalarString(I->getValue(), VersionString, Storage))
  736. return false;
  737. int Version;
  738. if (VersionString.getAsInteger<int>(10, Version)) {
  739. error(I->getValue(), "expected integer");
  740. return false;
  741. }
  742. if (Version < 0) {
  743. error(I->getValue(), "invalid version number");
  744. return false;
  745. }
  746. if (Version != 0) {
  747. error(I->getValue(), "version mismatch, expected 0");
  748. return false;
  749. }
  750. } else if (Key == "case-sensitive") {
  751. if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
  752. return false;
  753. } else if (Key == "use-external-names") {
  754. if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
  755. return false;
  756. } else {
  757. llvm_unreachable("key missing from Keys");
  758. }
  759. }
  760. if (Stream.failed())
  761. return false;
  762. if (!checkMissingKeys(Top, Keys))
  763. return false;
  764. return true;
  765. }
  766. };
  767. } // end of anonymous namespace
  768. Entry::~Entry() {}
  769. DirectoryEntry::~DirectoryEntry() { llvm::DeleteContainerPointers(Contents); }
  770. VFSFromYAML::~VFSFromYAML() { llvm::DeleteContainerPointers(Roots); }
  771. VFSFromYAML *VFSFromYAML::create(MemoryBuffer *Buffer,
  772. SourceMgr::DiagHandlerTy DiagHandler,
  773. void *DiagContext,
  774. IntrusiveRefCntPtr<FileSystem> ExternalFS) {
  775. SourceMgr SM;
  776. yaml::Stream Stream(Buffer, SM);
  777. SM.setDiagHandler(DiagHandler, DiagContext);
  778. yaml::document_iterator DI = Stream.begin();
  779. yaml::Node *Root = DI->getRoot();
  780. if (DI == Stream.end() || !Root) {
  781. SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
  782. return nullptr;
  783. }
  784. VFSFromYAMLParser P(Stream);
  785. std::unique_ptr<VFSFromYAML> FS(new VFSFromYAML(ExternalFS));
  786. if (!P.parse(Root, FS.get()))
  787. return nullptr;
  788. return FS.release();
  789. }
  790. ErrorOr<Entry *> VFSFromYAML::lookupPath(const Twine &Path_) {
  791. SmallString<256> Path;
  792. Path_.toVector(Path);
  793. // Handle relative paths
  794. if (std::error_code EC = sys::fs::make_absolute(Path))
  795. return EC;
  796. if (Path.empty())
  797. return make_error_code(llvm::errc::invalid_argument);
  798. sys::path::const_iterator Start = sys::path::begin(Path);
  799. sys::path::const_iterator End = sys::path::end(Path);
  800. for (std::vector<Entry *>::iterator I = Roots.begin(), E = Roots.end();
  801. I != E; ++I) {
  802. ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
  803. if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
  804. return Result;
  805. }
  806. return make_error_code(llvm::errc::no_such_file_or_directory);
  807. }
  808. ErrorOr<Entry *> VFSFromYAML::lookupPath(sys::path::const_iterator Start,
  809. sys::path::const_iterator End,
  810. Entry *From) {
  811. if (Start->equals("."))
  812. ++Start;
  813. // FIXME: handle ..
  814. if (CaseSensitive ? !Start->equals(From->getName())
  815. : !Start->equals_lower(From->getName()))
  816. // failure to match
  817. return make_error_code(llvm::errc::no_such_file_or_directory);
  818. ++Start;
  819. if (Start == End) {
  820. // Match!
  821. return From;
  822. }
  823. DirectoryEntry *DE = dyn_cast<DirectoryEntry>(From);
  824. if (!DE)
  825. return make_error_code(llvm::errc::not_a_directory);
  826. for (DirectoryEntry::iterator I = DE->contents_begin(),
  827. E = DE->contents_end();
  828. I != E; ++I) {
  829. ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
  830. if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
  831. return Result;
  832. }
  833. return make_error_code(llvm::errc::no_such_file_or_directory);
  834. }
  835. ErrorOr<Status> VFSFromYAML::status(const Twine &Path, Entry *E) {
  836. assert(E != nullptr);
  837. std::string PathStr(Path.str());
  838. if (FileEntry *F = dyn_cast<FileEntry>(E)) {
  839. ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
  840. assert(!S || S->getName() == F->getExternalContentsPath());
  841. if (S && !F->useExternalName(UseExternalNames))
  842. S->setName(PathStr);
  843. if (S)
  844. S->IsVFSMapped = true;
  845. return S;
  846. } else { // directory
  847. DirectoryEntry *DE = cast<DirectoryEntry>(E);
  848. Status S = DE->getStatus();
  849. S.setName(PathStr);
  850. return S;
  851. }
  852. }
  853. ErrorOr<Status> VFSFromYAML::status(const Twine &Path) {
  854. ErrorOr<Entry *> Result = lookupPath(Path);
  855. if (!Result)
  856. return Result.getError();
  857. return status(Path, *Result);
  858. }
  859. std::error_code
  860. VFSFromYAML::openFileForRead(const Twine &Path,
  861. std::unique_ptr<vfs::File> &Result) {
  862. ErrorOr<Entry *> E = lookupPath(Path);
  863. if (!E)
  864. return E.getError();
  865. FileEntry *F = dyn_cast<FileEntry>(*E);
  866. if (!F) // FIXME: errc::not_a_file?
  867. return make_error_code(llvm::errc::invalid_argument);
  868. if (std::error_code EC =
  869. ExternalFS->openFileForRead(F->getExternalContentsPath(), Result))
  870. return EC;
  871. if (!F->useExternalName(UseExternalNames))
  872. Result->setName(Path.str());
  873. return std::error_code();
  874. }
  875. IntrusiveRefCntPtr<FileSystem>
  876. vfs::getVFSFromYAML(MemoryBuffer *Buffer, SourceMgr::DiagHandlerTy DiagHandler,
  877. void *DiagContext,
  878. IntrusiveRefCntPtr<FileSystem> ExternalFS) {
  879. return VFSFromYAML::create(Buffer, DiagHandler, DiagContext, ExternalFS);
  880. }
  881. UniqueID vfs::getNextVirtualUniqueID() {
  882. static std::atomic<unsigned> UID;
  883. unsigned ID = ++UID;
  884. // The following assumes that uint64_t max will never collide with a real
  885. // dev_t value from the OS.
  886. return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
  887. }
  888. #ifndef NDEBUG
  889. static bool pathHasTraversal(StringRef Path) {
  890. using namespace llvm::sys;
  891. for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
  892. if (Comp == "." || Comp == "..")
  893. return true;
  894. return false;
  895. }
  896. #endif
  897. void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
  898. assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
  899. assert(sys::path::is_absolute(RealPath) && "real path not absolute");
  900. assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
  901. Mappings.emplace_back(VirtualPath, RealPath);
  902. }
  903. namespace {
  904. class JSONWriter {
  905. llvm::raw_ostream &OS;
  906. SmallVector<StringRef, 16> DirStack;
  907. inline unsigned getDirIndent() { return 4 * DirStack.size(); }
  908. inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
  909. bool containedIn(StringRef Parent, StringRef Path);
  910. StringRef containedPart(StringRef Parent, StringRef Path);
  911. void startDirectory(StringRef Path);
  912. void endDirectory();
  913. void writeEntry(StringRef VPath, StringRef RPath);
  914. public:
  915. JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
  916. void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive);
  917. };
  918. }
  919. bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
  920. using namespace llvm::sys;
  921. // Compare each path component.
  922. auto IParent = path::begin(Parent), EParent = path::end(Parent);
  923. for (auto IChild = path::begin(Path), EChild = path::end(Path);
  924. IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
  925. if (*IParent != *IChild)
  926. return false;
  927. }
  928. // Have we exhausted the parent path?
  929. return IParent == EParent;
  930. }
  931. StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
  932. assert(!Parent.empty());
  933. assert(containedIn(Parent, Path));
  934. return Path.slice(Parent.size() + 1, StringRef::npos);
  935. }
  936. void JSONWriter::startDirectory(StringRef Path) {
  937. StringRef Name =
  938. DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
  939. DirStack.push_back(Path);
  940. unsigned Indent = getDirIndent();
  941. OS.indent(Indent) << "{\n";
  942. OS.indent(Indent + 2) << "'type': 'directory',\n";
  943. OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
  944. OS.indent(Indent + 2) << "'contents': [\n";
  945. }
  946. void JSONWriter::endDirectory() {
  947. unsigned Indent = getDirIndent();
  948. OS.indent(Indent + 2) << "]\n";
  949. OS.indent(Indent) << "}";
  950. DirStack.pop_back();
  951. }
  952. void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
  953. unsigned Indent = getFileIndent();
  954. OS.indent(Indent) << "{\n";
  955. OS.indent(Indent + 2) << "'type': 'file',\n";
  956. OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
  957. OS.indent(Indent + 2) << "'external-contents': \""
  958. << llvm::yaml::escape(RPath) << "\"\n";
  959. OS.indent(Indent) << "}";
  960. }
  961. void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
  962. Optional<bool> IsCaseSensitive) {
  963. using namespace llvm::sys;
  964. OS << "{\n"
  965. " 'version': 0,\n";
  966. if (IsCaseSensitive.hasValue())
  967. OS << " 'case-sensitive': '"
  968. << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
  969. OS << " 'roots': [\n";
  970. if (Entries.empty())
  971. return;
  972. const YAMLVFSEntry &Entry = Entries.front();
  973. startDirectory(path::parent_path(Entry.VPath));
  974. writeEntry(path::filename(Entry.VPath), Entry.RPath);
  975. for (const auto &Entry : Entries.slice(1)) {
  976. StringRef Dir = path::parent_path(Entry.VPath);
  977. if (Dir == DirStack.back())
  978. OS << ",\n";
  979. else {
  980. while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
  981. OS << "\n";
  982. endDirectory();
  983. }
  984. OS << ",\n";
  985. startDirectory(Dir);
  986. }
  987. writeEntry(path::filename(Entry.VPath), Entry.RPath);
  988. }
  989. while (!DirStack.empty()) {
  990. OS << "\n";
  991. endDirectory();
  992. }
  993. OS << "\n"
  994. << " ]\n"
  995. << "}\n";
  996. }
  997. void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
  998. std::sort(Mappings.begin(), Mappings.end(),
  999. [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
  1000. return LHS.VPath < RHS.VPath;
  1001. });
  1002. JSONWriter(OS).write(Mappings, IsCaseSensitive);
  1003. }
  1004. VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(const Twine &_Path,
  1005. VFSFromYAML &FS,
  1006. DirectoryEntry::iterator Begin,
  1007. DirectoryEntry::iterator End,
  1008. std::error_code &EC)
  1009. : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
  1010. if (Current != End) {
  1011. SmallString<128> PathStr(Dir);
  1012. llvm::sys::path::append(PathStr, (*Current)->getName());
  1013. llvm::ErrorOr<vfs::Status> S = FS.status(PathStr.str());
  1014. if (S)
  1015. CurrentEntry = *S;
  1016. else
  1017. EC = S.getError();
  1018. }
  1019. }
  1020. std::error_code VFSFromYamlDirIterImpl::increment() {
  1021. assert(Current != End && "cannot iterate past end");
  1022. if (++Current != End) {
  1023. SmallString<128> PathStr(Dir);
  1024. llvm::sys::path::append(PathStr, (*Current)->getName());
  1025. llvm::ErrorOr<vfs::Status> S = FS.status(PathStr.str());
  1026. if (!S)
  1027. return S.getError();
  1028. CurrentEntry = *S;
  1029. } else {
  1030. CurrentEntry = Status();
  1031. }
  1032. return std::error_code();
  1033. }
  1034. vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
  1035. const Twine &Path,
  1036. std::error_code &EC)
  1037. : FS(&FS_) {
  1038. directory_iterator I = FS->dir_begin(Path, EC);
  1039. if (!EC && I != directory_iterator()) {
  1040. State = std::make_shared<IterState>();
  1041. State->push(I);
  1042. }
  1043. }
  1044. vfs::recursive_directory_iterator &
  1045. recursive_directory_iterator::increment(std::error_code &EC) {
  1046. assert(FS && State && !State->empty() && "incrementing past end");
  1047. assert(State->top()->isStatusKnown() && "non-canonical end iterator");
  1048. vfs::directory_iterator End;
  1049. if (State->top()->isDirectory()) {
  1050. vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
  1051. if (EC)
  1052. return *this;
  1053. if (I != End) {
  1054. State->push(I);
  1055. return *this;
  1056. }
  1057. }
  1058. while (!State->empty() && State->top().increment(EC) == End)
  1059. State->pop();
  1060. if (State->empty())
  1061. State.reset(); // end iterator
  1062. return *this;
  1063. }