VirtualFileSystem.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818
  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 "clang/Basic/FileManager.h"
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/StringExtras.h"
  16. #include "llvm/ADT/StringSet.h"
  17. #include "llvm/ADT/iterator_range.h"
  18. #include "llvm/Config/llvm-config.h"
  19. #include "llvm/Support/Debug.h"
  20. #include "llvm/Support/Errc.h"
  21. #include "llvm/Support/MemoryBuffer.h"
  22. #include "llvm/Support/Path.h"
  23. #include "llvm/Support/Process.h"
  24. #include "llvm/Support/YAMLParser.h"
  25. #include <atomic>
  26. #include <memory>
  27. #include <utility>
  28. // For chdir.
  29. #ifdef LLVM_ON_WIN32
  30. # include <direct.h>
  31. #else
  32. # include <unistd.h>
  33. #endif
  34. using namespace clang;
  35. using namespace clang::vfs;
  36. using namespace llvm;
  37. using llvm::sys::fs::file_status;
  38. using llvm::sys::fs::file_type;
  39. using llvm::sys::fs::perms;
  40. using llvm::sys::fs::UniqueID;
  41. Status::Status(const file_status &Status)
  42. : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
  43. User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
  44. Type(Status.type()), Perms(Status.permissions()), IsVFSMapped(false) {}
  45. Status::Status(StringRef Name, UniqueID UID, sys::TimeValue MTime,
  46. uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
  47. perms Perms)
  48. : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
  49. Type(Type), Perms(Perms), IsVFSMapped(false) {}
  50. Status Status::copyWithNewName(const Status &In, StringRef NewName) {
  51. return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
  52. In.getUser(), In.getGroup(), In.getSize(), In.getType(),
  53. In.getPermissions());
  54. }
  55. Status Status::copyWithNewName(const file_status &In, StringRef NewName) {
  56. return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
  57. In.getUser(), In.getGroup(), In.getSize(), In.type(),
  58. In.permissions());
  59. }
  60. bool Status::equivalent(const Status &Other) const {
  61. return getUniqueID() == Other.getUniqueID();
  62. }
  63. bool Status::isDirectory() const {
  64. return Type == file_type::directory_file;
  65. }
  66. bool Status::isRegularFile() const {
  67. return Type == file_type::regular_file;
  68. }
  69. bool Status::isOther() const {
  70. return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
  71. }
  72. bool Status::isSymlink() const {
  73. return Type == file_type::symlink_file;
  74. }
  75. bool Status::isStatusKnown() const {
  76. return Type != file_type::status_error;
  77. }
  78. bool Status::exists() const {
  79. return isStatusKnown() && Type != file_type::file_not_found;
  80. }
  81. File::~File() {}
  82. FileSystem::~FileSystem() {}
  83. ErrorOr<std::unique_ptr<MemoryBuffer>>
  84. FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
  85. bool RequiresNullTerminator, bool IsVolatile) {
  86. auto F = openFileForRead(Name);
  87. if (!F)
  88. return F.getError();
  89. return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
  90. }
  91. std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
  92. if (llvm::sys::path::is_absolute(Path))
  93. return std::error_code();
  94. auto WorkingDir = getCurrentWorkingDirectory();
  95. if (!WorkingDir)
  96. return WorkingDir.getError();
  97. return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
  98. }
  99. bool FileSystem::exists(const Twine &Path) {
  100. auto Status = status(Path);
  101. return Status && Status->exists();
  102. }
  103. #ifndef NDEBUG
  104. static bool isTraversalComponent(StringRef Component) {
  105. return Component.equals("..") || Component.equals(".");
  106. }
  107. static bool pathHasTraversal(StringRef Path) {
  108. using namespace llvm::sys;
  109. for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
  110. if (isTraversalComponent(Comp))
  111. return true;
  112. return false;
  113. }
  114. #endif
  115. //===-----------------------------------------------------------------------===/
  116. // RealFileSystem implementation
  117. //===-----------------------------------------------------------------------===/
  118. namespace {
  119. /// \brief Wrapper around a raw file descriptor.
  120. class RealFile : public File {
  121. int FD;
  122. Status S;
  123. std::string RealName;
  124. friend class RealFileSystem;
  125. RealFile(int FD, StringRef NewName, StringRef NewRealPathName)
  126. : FD(FD), S(NewName, {}, {}, {}, {}, {},
  127. llvm::sys::fs::file_type::status_error, {}),
  128. RealName(NewRealPathName.str()) {
  129. assert(FD >= 0 && "Invalid or inactive file descriptor");
  130. }
  131. public:
  132. ~RealFile() override;
  133. ErrorOr<Status> status() override;
  134. ErrorOr<std::string> getName() override;
  135. ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
  136. int64_t FileSize,
  137. bool RequiresNullTerminator,
  138. bool IsVolatile) override;
  139. std::error_code close() override;
  140. };
  141. } // end anonymous namespace
  142. RealFile::~RealFile() { close(); }
  143. ErrorOr<Status> RealFile::status() {
  144. assert(FD != -1 && "cannot stat closed file");
  145. if (!S.isStatusKnown()) {
  146. file_status RealStatus;
  147. if (std::error_code EC = sys::fs::status(FD, RealStatus))
  148. return EC;
  149. S = Status::copyWithNewName(RealStatus, S.getName());
  150. }
  151. return S;
  152. }
  153. ErrorOr<std::string> RealFile::getName() {
  154. return RealName.empty() ? S.getName().str() : RealName;
  155. }
  156. ErrorOr<std::unique_ptr<MemoryBuffer>>
  157. RealFile::getBuffer(const Twine &Name, int64_t FileSize,
  158. bool RequiresNullTerminator, bool IsVolatile) {
  159. assert(FD != -1 && "cannot get buffer for closed file");
  160. return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
  161. IsVolatile);
  162. }
  163. std::error_code RealFile::close() {
  164. std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD);
  165. FD = -1;
  166. return EC;
  167. }
  168. namespace {
  169. /// \brief The file system according to your operating system.
  170. class RealFileSystem : public FileSystem {
  171. public:
  172. ErrorOr<Status> status(const Twine &Path) override;
  173. ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
  174. directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
  175. llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
  176. std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
  177. };
  178. } // end anonymous namespace
  179. ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
  180. sys::fs::file_status RealStatus;
  181. if (std::error_code EC = sys::fs::status(Path, RealStatus))
  182. return EC;
  183. return Status::copyWithNewName(RealStatus, Path.str());
  184. }
  185. ErrorOr<std::unique_ptr<File>>
  186. RealFileSystem::openFileForRead(const Twine &Name) {
  187. int FD;
  188. SmallString<256> RealName;
  189. if (std::error_code EC = sys::fs::openFileForRead(Name, FD, &RealName))
  190. return EC;
  191. return std::unique_ptr<File>(new RealFile(FD, Name.str(), RealName.str()));
  192. }
  193. llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
  194. SmallString<256> Dir;
  195. if (std::error_code EC = llvm::sys::fs::current_path(Dir))
  196. return EC;
  197. return Dir.str().str();
  198. }
  199. std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
  200. // FIXME: chdir is thread hostile; on the other hand, creating the same
  201. // behavior as chdir is complex: chdir resolves the path once, thus
  202. // guaranteeing that all subsequent relative path operations work
  203. // on the same path the original chdir resulted in. This makes a
  204. // difference for example on network filesystems, where symlinks might be
  205. // switched during runtime of the tool. Fixing this depends on having a
  206. // file system abstraction that allows openat() style interactions.
  207. SmallString<256> Storage;
  208. StringRef Dir = Path.toNullTerminatedStringRef(Storage);
  209. if (int Err = ::chdir(Dir.data()))
  210. return std::error_code(Err, std::generic_category());
  211. return std::error_code();
  212. }
  213. IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
  214. static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
  215. return FS;
  216. }
  217. namespace {
  218. class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
  219. std::string Path;
  220. llvm::sys::fs::directory_iterator Iter;
  221. public:
  222. RealFSDirIter(const Twine &_Path, std::error_code &EC)
  223. : Path(_Path.str()), Iter(Path, EC) {
  224. if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
  225. llvm::sys::fs::file_status S;
  226. EC = Iter->status(S);
  227. if (!EC)
  228. CurrentEntry = Status::copyWithNewName(S, Iter->path());
  229. }
  230. }
  231. std::error_code increment() override {
  232. std::error_code EC;
  233. Iter.increment(EC);
  234. if (EC) {
  235. return EC;
  236. } else if (Iter == llvm::sys::fs::directory_iterator()) {
  237. CurrentEntry = Status();
  238. } else {
  239. llvm::sys::fs::file_status S;
  240. EC = Iter->status(S);
  241. CurrentEntry = Status::copyWithNewName(S, Iter->path());
  242. }
  243. return EC;
  244. }
  245. };
  246. }
  247. directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
  248. std::error_code &EC) {
  249. return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
  250. }
  251. //===-----------------------------------------------------------------------===/
  252. // OverlayFileSystem implementation
  253. //===-----------------------------------------------------------------------===/
  254. OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
  255. FSList.push_back(std::move(BaseFS));
  256. }
  257. void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
  258. FSList.push_back(FS);
  259. // Synchronize added file systems by duplicating the working directory from
  260. // the first one in the list.
  261. FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
  262. }
  263. ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
  264. // FIXME: handle symlinks that cross file systems
  265. for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
  266. ErrorOr<Status> Status = (*I)->status(Path);
  267. if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
  268. return Status;
  269. }
  270. return make_error_code(llvm::errc::no_such_file_or_directory);
  271. }
  272. ErrorOr<std::unique_ptr<File>>
  273. OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
  274. // FIXME: handle symlinks that cross file systems
  275. for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
  276. auto Result = (*I)->openFileForRead(Path);
  277. if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
  278. return Result;
  279. }
  280. return make_error_code(llvm::errc::no_such_file_or_directory);
  281. }
  282. llvm::ErrorOr<std::string>
  283. OverlayFileSystem::getCurrentWorkingDirectory() const {
  284. // All file systems are synchronized, just take the first working directory.
  285. return FSList.front()->getCurrentWorkingDirectory();
  286. }
  287. std::error_code
  288. OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
  289. for (auto &FS : FSList)
  290. if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
  291. return EC;
  292. return std::error_code();
  293. }
  294. clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
  295. namespace {
  296. class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
  297. OverlayFileSystem &Overlays;
  298. std::string Path;
  299. OverlayFileSystem::iterator CurrentFS;
  300. directory_iterator CurrentDirIter;
  301. llvm::StringSet<> SeenNames;
  302. std::error_code incrementFS() {
  303. assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
  304. ++CurrentFS;
  305. for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
  306. std::error_code EC;
  307. CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
  308. if (EC && EC != errc::no_such_file_or_directory)
  309. return EC;
  310. if (CurrentDirIter != directory_iterator())
  311. break; // found
  312. }
  313. return std::error_code();
  314. }
  315. std::error_code incrementDirIter(bool IsFirstTime) {
  316. assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
  317. "incrementing past end");
  318. std::error_code EC;
  319. if (!IsFirstTime)
  320. CurrentDirIter.increment(EC);
  321. if (!EC && CurrentDirIter == directory_iterator())
  322. EC = incrementFS();
  323. return EC;
  324. }
  325. std::error_code incrementImpl(bool IsFirstTime) {
  326. while (true) {
  327. std::error_code EC = incrementDirIter(IsFirstTime);
  328. if (EC || CurrentDirIter == directory_iterator()) {
  329. CurrentEntry = Status();
  330. return EC;
  331. }
  332. CurrentEntry = *CurrentDirIter;
  333. StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
  334. if (SeenNames.insert(Name).second)
  335. return EC; // name not seen before
  336. }
  337. llvm_unreachable("returned above");
  338. }
  339. public:
  340. OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
  341. std::error_code &EC)
  342. : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
  343. CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
  344. EC = incrementImpl(true);
  345. }
  346. std::error_code increment() override { return incrementImpl(false); }
  347. };
  348. } // end anonymous namespace
  349. directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
  350. std::error_code &EC) {
  351. return directory_iterator(
  352. std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
  353. }
  354. namespace clang {
  355. namespace vfs {
  356. namespace detail {
  357. enum InMemoryNodeKind { IME_File, IME_Directory };
  358. /// The in memory file system is a tree of Nodes. Every node can either be a
  359. /// file or a directory.
  360. class InMemoryNode {
  361. Status Stat;
  362. InMemoryNodeKind Kind;
  363. public:
  364. InMemoryNode(Status Stat, InMemoryNodeKind Kind)
  365. : Stat(std::move(Stat)), Kind(Kind) {}
  366. virtual ~InMemoryNode() {}
  367. const Status &getStatus() const { return Stat; }
  368. InMemoryNodeKind getKind() const { return Kind; }
  369. virtual std::string toString(unsigned Indent) const = 0;
  370. };
  371. namespace {
  372. class InMemoryFile : public InMemoryNode {
  373. std::unique_ptr<llvm::MemoryBuffer> Buffer;
  374. public:
  375. InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
  376. : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
  377. llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
  378. std::string toString(unsigned Indent) const override {
  379. return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
  380. }
  381. static bool classof(const InMemoryNode *N) {
  382. return N->getKind() == IME_File;
  383. }
  384. };
  385. /// Adapt a InMemoryFile for VFS' File interface.
  386. class InMemoryFileAdaptor : public File {
  387. InMemoryFile &Node;
  388. public:
  389. explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
  390. llvm::ErrorOr<Status> status() override { return Node.getStatus(); }
  391. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
  392. getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
  393. bool IsVolatile) override {
  394. llvm::MemoryBuffer *Buf = Node.getBuffer();
  395. return llvm::MemoryBuffer::getMemBuffer(
  396. Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
  397. }
  398. std::error_code close() override { return std::error_code(); }
  399. };
  400. } // end anonymous namespace
  401. class InMemoryDirectory : public InMemoryNode {
  402. std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
  403. public:
  404. InMemoryDirectory(Status Stat)
  405. : InMemoryNode(std::move(Stat), IME_Directory) {}
  406. InMemoryNode *getChild(StringRef Name) {
  407. auto I = Entries.find(Name);
  408. if (I != Entries.end())
  409. return I->second.get();
  410. return nullptr;
  411. }
  412. InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
  413. return Entries.insert(make_pair(Name, std::move(Child)))
  414. .first->second.get();
  415. }
  416. typedef decltype(Entries)::const_iterator const_iterator;
  417. const_iterator begin() const { return Entries.begin(); }
  418. const_iterator end() const { return Entries.end(); }
  419. std::string toString(unsigned Indent) const override {
  420. std::string Result =
  421. (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
  422. for (const auto &Entry : Entries) {
  423. Result += Entry.second->toString(Indent + 2);
  424. }
  425. return Result;
  426. }
  427. static bool classof(const InMemoryNode *N) {
  428. return N->getKind() == IME_Directory;
  429. }
  430. };
  431. }
  432. InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
  433. : Root(new detail::InMemoryDirectory(
  434. Status("", getNextVirtualUniqueID(), llvm::sys::TimeValue::MinTime(),
  435. 0, 0, 0, llvm::sys::fs::file_type::directory_file,
  436. llvm::sys::fs::perms::all_all))),
  437. UseNormalizedPaths(UseNormalizedPaths) {}
  438. InMemoryFileSystem::~InMemoryFileSystem() {}
  439. std::string InMemoryFileSystem::toString() const {
  440. return Root->toString(/*Indent=*/0);
  441. }
  442. bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
  443. std::unique_ptr<llvm::MemoryBuffer> Buffer) {
  444. SmallString<128> Path;
  445. P.toVector(Path);
  446. // Fix up relative paths. This just prepends the current working directory.
  447. std::error_code EC = makeAbsolute(Path);
  448. assert(!EC);
  449. (void)EC;
  450. if (useNormalizedPaths())
  451. llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
  452. if (Path.empty())
  453. return false;
  454. detail::InMemoryDirectory *Dir = Root.get();
  455. auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
  456. while (true) {
  457. StringRef Name = *I;
  458. detail::InMemoryNode *Node = Dir->getChild(Name);
  459. ++I;
  460. if (!Node) {
  461. if (I == E) {
  462. // End of the path, create a new file.
  463. // FIXME: expose the status details in the interface.
  464. Status Stat(P.str(), getNextVirtualUniqueID(),
  465. llvm::sys::TimeValue(ModificationTime, 0), 0, 0,
  466. Buffer->getBufferSize(),
  467. llvm::sys::fs::file_type::regular_file,
  468. llvm::sys::fs::all_all);
  469. Dir->addChild(Name, llvm::make_unique<detail::InMemoryFile>(
  470. std::move(Stat), std::move(Buffer)));
  471. return true;
  472. }
  473. // Create a new directory. Use the path up to here.
  474. // FIXME: expose the status details in the interface.
  475. Status Stat(
  476. StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
  477. getNextVirtualUniqueID(), llvm::sys::TimeValue(ModificationTime, 0),
  478. 0, 0, Buffer->getBufferSize(),
  479. llvm::sys::fs::file_type::directory_file, llvm::sys::fs::all_all);
  480. Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
  481. Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
  482. continue;
  483. }
  484. if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
  485. Dir = NewDir;
  486. } else {
  487. assert(isa<detail::InMemoryFile>(Node) &&
  488. "Must be either file or directory!");
  489. // Trying to insert a directory in place of a file.
  490. if (I != E)
  491. return false;
  492. // Return false only if the new file is different from the existing one.
  493. return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
  494. Buffer->getBuffer();
  495. }
  496. }
  497. }
  498. bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
  499. llvm::MemoryBuffer *Buffer) {
  500. return addFile(P, ModificationTime,
  501. llvm::MemoryBuffer::getMemBuffer(
  502. Buffer->getBuffer(), Buffer->getBufferIdentifier()));
  503. }
  504. static ErrorOr<detail::InMemoryNode *>
  505. lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
  506. const Twine &P) {
  507. SmallString<128> Path;
  508. P.toVector(Path);
  509. // Fix up relative paths. This just prepends the current working directory.
  510. std::error_code EC = FS.makeAbsolute(Path);
  511. assert(!EC);
  512. (void)EC;
  513. if (FS.useNormalizedPaths())
  514. llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
  515. if (Path.empty())
  516. return Dir;
  517. auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
  518. while (true) {
  519. detail::InMemoryNode *Node = Dir->getChild(*I);
  520. ++I;
  521. if (!Node)
  522. return errc::no_such_file_or_directory;
  523. // Return the file if it's at the end of the path.
  524. if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
  525. if (I == E)
  526. return File;
  527. return errc::no_such_file_or_directory;
  528. }
  529. // Traverse directories.
  530. Dir = cast<detail::InMemoryDirectory>(Node);
  531. if (I == E)
  532. return Dir;
  533. }
  534. }
  535. llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
  536. auto Node = lookupInMemoryNode(*this, Root.get(), Path);
  537. if (Node)
  538. return (*Node)->getStatus();
  539. return Node.getError();
  540. }
  541. llvm::ErrorOr<std::unique_ptr<File>>
  542. InMemoryFileSystem::openFileForRead(const Twine &Path) {
  543. auto Node = lookupInMemoryNode(*this, Root.get(), Path);
  544. if (!Node)
  545. return Node.getError();
  546. // When we have a file provide a heap-allocated wrapper for the memory buffer
  547. // to match the ownership semantics for File.
  548. if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
  549. return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
  550. // FIXME: errc::not_a_file?
  551. return make_error_code(llvm::errc::invalid_argument);
  552. }
  553. namespace {
  554. /// Adaptor from InMemoryDir::iterator to directory_iterator.
  555. class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
  556. detail::InMemoryDirectory::const_iterator I;
  557. detail::InMemoryDirectory::const_iterator E;
  558. public:
  559. InMemoryDirIterator() {}
  560. explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
  561. : I(Dir.begin()), E(Dir.end()) {
  562. if (I != E)
  563. CurrentEntry = I->second->getStatus();
  564. }
  565. std::error_code increment() override {
  566. ++I;
  567. // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
  568. // the rest.
  569. CurrentEntry = I != E ? I->second->getStatus() : Status();
  570. return std::error_code();
  571. }
  572. };
  573. } // end anonymous namespace
  574. directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
  575. std::error_code &EC) {
  576. auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
  577. if (!Node) {
  578. EC = Node.getError();
  579. return directory_iterator(std::make_shared<InMemoryDirIterator>());
  580. }
  581. if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
  582. return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
  583. EC = make_error_code(llvm::errc::not_a_directory);
  584. return directory_iterator(std::make_shared<InMemoryDirIterator>());
  585. }
  586. std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
  587. SmallString<128> Path;
  588. P.toVector(Path);
  589. // Fix up relative paths. This just prepends the current working directory.
  590. std::error_code EC = makeAbsolute(Path);
  591. assert(!EC);
  592. (void)EC;
  593. if (useNormalizedPaths())
  594. llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
  595. if (!Path.empty())
  596. WorkingDirectory = Path.str();
  597. return std::error_code();
  598. }
  599. }
  600. }
  601. //===-----------------------------------------------------------------------===/
  602. // RedirectingFileSystem implementation
  603. //===-----------------------------------------------------------------------===/
  604. namespace {
  605. enum EntryKind {
  606. EK_Directory,
  607. EK_File
  608. };
  609. /// \brief A single file or directory in the VFS.
  610. class Entry {
  611. EntryKind Kind;
  612. std::string Name;
  613. public:
  614. virtual ~Entry();
  615. Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
  616. StringRef getName() const { return Name; }
  617. EntryKind getKind() const { return Kind; }
  618. };
  619. class RedirectingDirectoryEntry : public Entry {
  620. std::vector<std::unique_ptr<Entry>> Contents;
  621. Status S;
  622. public:
  623. RedirectingDirectoryEntry(StringRef Name,
  624. std::vector<std::unique_ptr<Entry>> Contents,
  625. Status S)
  626. : Entry(EK_Directory, Name), Contents(std::move(Contents)),
  627. S(std::move(S)) {}
  628. RedirectingDirectoryEntry(StringRef Name, Status S)
  629. : Entry(EK_Directory, Name), S(std::move(S)) {}
  630. Status getStatus() { return S; }
  631. void addContent(std::unique_ptr<Entry> Content) {
  632. Contents.push_back(std::move(Content));
  633. }
  634. Entry *getLastContent() const { return Contents.back().get(); }
  635. typedef decltype(Contents)::iterator iterator;
  636. iterator contents_begin() { return Contents.begin(); }
  637. iterator contents_end() { return Contents.end(); }
  638. static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
  639. };
  640. class RedirectingFileEntry : public Entry {
  641. public:
  642. enum NameKind {
  643. NK_NotSet,
  644. NK_External,
  645. NK_Virtual
  646. };
  647. private:
  648. std::string ExternalContentsPath;
  649. NameKind UseName;
  650. public:
  651. RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
  652. NameKind UseName)
  653. : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
  654. UseName(UseName) {}
  655. StringRef getExternalContentsPath() const { return ExternalContentsPath; }
  656. /// \brief whether to use the external path as the name for this file.
  657. bool useExternalName(bool GlobalUseExternalName) const {
  658. return UseName == NK_NotSet ? GlobalUseExternalName
  659. : (UseName == NK_External);
  660. }
  661. NameKind getUseName() const { return UseName; }
  662. static bool classof(const Entry *E) { return E->getKind() == EK_File; }
  663. };
  664. class RedirectingFileSystem;
  665. class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
  666. std::string Dir;
  667. RedirectingFileSystem &FS;
  668. RedirectingDirectoryEntry::iterator Current, End;
  669. public:
  670. VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
  671. RedirectingDirectoryEntry::iterator Begin,
  672. RedirectingDirectoryEntry::iterator End,
  673. std::error_code &EC);
  674. std::error_code increment() override;
  675. };
  676. /// \brief A virtual file system parsed from a YAML file.
  677. ///
  678. /// Currently, this class allows creating virtual directories and mapping
  679. /// virtual file paths to existing external files, available in \c ExternalFS.
  680. ///
  681. /// The basic structure of the parsed file is:
  682. /// \verbatim
  683. /// {
  684. /// 'version': <version number>,
  685. /// <optional configuration>
  686. /// 'roots': [
  687. /// <directory entries>
  688. /// ]
  689. /// }
  690. /// \endverbatim
  691. ///
  692. /// All configuration options are optional.
  693. /// 'case-sensitive': <boolean, default=true>
  694. /// 'use-external-names': <boolean, default=true>
  695. /// 'overlay-relative': <boolean, default=false>
  696. ///
  697. /// Virtual directories are represented as
  698. /// \verbatim
  699. /// {
  700. /// 'type': 'directory',
  701. /// 'name': <string>,
  702. /// 'contents': [ <file or directory entries> ]
  703. /// }
  704. /// \endverbatim
  705. ///
  706. /// The default attributes for virtual directories are:
  707. /// \verbatim
  708. /// MTime = now() when created
  709. /// Perms = 0777
  710. /// User = Group = 0
  711. /// Size = 0
  712. /// UniqueID = unspecified unique value
  713. /// \endverbatim
  714. ///
  715. /// Re-mapped files are represented as
  716. /// \verbatim
  717. /// {
  718. /// 'type': 'file',
  719. /// 'name': <string>,
  720. /// 'use-external-name': <boolean> # Optional
  721. /// 'external-contents': <path to external file>)
  722. /// }
  723. /// \endverbatim
  724. ///
  725. /// and inherit their attributes from the external contents.
  726. ///
  727. /// In both cases, the 'name' field may contain multiple path components (e.g.
  728. /// /path/to/file). However, any directory that contains more than one child
  729. /// must be uniquely represented by a directory entry.
  730. class RedirectingFileSystem : public vfs::FileSystem {
  731. /// The root(s) of the virtual file system.
  732. std::vector<std::unique_ptr<Entry>> Roots;
  733. /// \brief The file system to use for external references.
  734. IntrusiveRefCntPtr<FileSystem> ExternalFS;
  735. /// If IsRelativeOverlay is set, this represents the directory
  736. /// path that should be prefixed to each 'external-contents' entry
  737. /// when reading from YAML files.
  738. std::string ExternalContentsPrefixDir;
  739. /// @name Configuration
  740. /// @{
  741. /// \brief Whether to perform case-sensitive comparisons.
  742. ///
  743. /// Currently, case-insensitive matching only works correctly with ASCII.
  744. bool CaseSensitive = true;
  745. /// IsRelativeOverlay marks whether a IsExternalContentsPrefixDir path must
  746. /// be prefixed in every 'external-contents' when reading from YAML files.
  747. bool IsRelativeOverlay = false;
  748. /// \brief Whether to use to use the value of 'external-contents' for the
  749. /// names of files. This global value is overridable on a per-file basis.
  750. bool UseExternalNames = true;
  751. /// @}
  752. /// Virtual file paths and external files could be canonicalized without "..",
  753. /// "." and "./" in their paths. FIXME: some unittests currently fail on
  754. /// win32 when using remove_dots and remove_leading_dotslash on paths.
  755. bool UseCanonicalizedPaths =
  756. #ifdef LLVM_ON_WIN32
  757. false;
  758. #else
  759. true;
  760. #endif
  761. friend class RedirectingFileSystemParser;
  762. private:
  763. RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
  764. : ExternalFS(std::move(ExternalFS)) {}
  765. /// \brief Looks up \p Path in \c Roots.
  766. ErrorOr<Entry *> lookupPath(const Twine &Path);
  767. /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
  768. /// recursing into the contents of \p From if it is a directory.
  769. ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
  770. sys::path::const_iterator End, Entry *From);
  771. /// \brief Get the status of a given an \c Entry.
  772. ErrorOr<Status> status(const Twine &Path, Entry *E);
  773. public:
  774. /// \brief Parses \p Buffer, which is expected to be in YAML format and
  775. /// returns a virtual file system representing its contents.
  776. static RedirectingFileSystem *
  777. create(std::unique_ptr<MemoryBuffer> Buffer,
  778. SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
  779. void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
  780. ErrorOr<Status> status(const Twine &Path) override;
  781. ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
  782. llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
  783. return ExternalFS->getCurrentWorkingDirectory();
  784. }
  785. std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
  786. return ExternalFS->setCurrentWorkingDirectory(Path);
  787. }
  788. directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
  789. ErrorOr<Entry *> E = lookupPath(Dir);
  790. if (!E) {
  791. EC = E.getError();
  792. return directory_iterator();
  793. }
  794. ErrorOr<Status> S = status(Dir, *E);
  795. if (!S) {
  796. EC = S.getError();
  797. return directory_iterator();
  798. }
  799. if (!S->isDirectory()) {
  800. EC = std::error_code(static_cast<int>(errc::not_a_directory),
  801. std::system_category());
  802. return directory_iterator();
  803. }
  804. auto *D = cast<RedirectingDirectoryEntry>(*E);
  805. return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
  806. *this, D->contents_begin(), D->contents_end(), EC));
  807. }
  808. void setExternalContentsPrefixDir(StringRef PrefixDir) {
  809. ExternalContentsPrefixDir = PrefixDir.str();
  810. }
  811. StringRef getExternalContentsPrefixDir() const {
  812. return ExternalContentsPrefixDir;
  813. }
  814. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  815. LLVM_DUMP_METHOD void dump() const {
  816. for (const std::unique_ptr<Entry> &Root : Roots)
  817. dumpEntry(Root.get());
  818. }
  819. LLVM_DUMP_METHOD void dumpEntry(Entry *E, int NumSpaces = 0) const {
  820. StringRef Name = E->getName();
  821. for (int i = 0, e = NumSpaces; i < e; ++i)
  822. dbgs() << " ";
  823. dbgs() << "'" << Name.str().c_str() << "'" << "\n";
  824. if (E->getKind() == EK_Directory) {
  825. auto *DE = dyn_cast<RedirectingDirectoryEntry>(E);
  826. assert(DE && "Should be a directory");
  827. for (std::unique_ptr<Entry> &SubEntry :
  828. llvm::make_range(DE->contents_begin(), DE->contents_end()))
  829. dumpEntry(SubEntry.get(), NumSpaces+2);
  830. }
  831. }
  832. #endif
  833. };
  834. /// \brief A helper class to hold the common YAML parsing state.
  835. class RedirectingFileSystemParser {
  836. yaml::Stream &Stream;
  837. void error(yaml::Node *N, const Twine &Msg) {
  838. Stream.printError(N, Msg);
  839. }
  840. // false on error
  841. bool parseScalarString(yaml::Node *N, StringRef &Result,
  842. SmallVectorImpl<char> &Storage) {
  843. yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
  844. if (!S) {
  845. error(N, "expected string");
  846. return false;
  847. }
  848. Result = S->getValue(Storage);
  849. return true;
  850. }
  851. // false on error
  852. bool parseScalarBool(yaml::Node *N, bool &Result) {
  853. SmallString<5> Storage;
  854. StringRef Value;
  855. if (!parseScalarString(N, Value, Storage))
  856. return false;
  857. if (Value.equals_lower("true") || Value.equals_lower("on") ||
  858. Value.equals_lower("yes") || Value == "1") {
  859. Result = true;
  860. return true;
  861. } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
  862. Value.equals_lower("no") || Value == "0") {
  863. Result = false;
  864. return true;
  865. }
  866. error(N, "expected boolean value");
  867. return false;
  868. }
  869. struct KeyStatus {
  870. KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
  871. bool Required;
  872. bool Seen;
  873. };
  874. typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
  875. // false on error
  876. bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
  877. DenseMap<StringRef, KeyStatus> &Keys) {
  878. if (!Keys.count(Key)) {
  879. error(KeyNode, "unknown key");
  880. return false;
  881. }
  882. KeyStatus &S = Keys[Key];
  883. if (S.Seen) {
  884. error(KeyNode, Twine("duplicate key '") + Key + "'");
  885. return false;
  886. }
  887. S.Seen = true;
  888. return true;
  889. }
  890. // false on error
  891. bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
  892. for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
  893. E = Keys.end();
  894. I != E; ++I) {
  895. if (I->second.Required && !I->second.Seen) {
  896. error(Obj, Twine("missing key '") + I->first + "'");
  897. return false;
  898. }
  899. }
  900. return true;
  901. }
  902. Entry *lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
  903. Entry *ParentEntry = nullptr) {
  904. if (!ParentEntry) { // Look for a existent root
  905. for (const std::unique_ptr<Entry> &Root : FS->Roots) {
  906. if (Name.equals(Root->getName())) {
  907. ParentEntry = Root.get();
  908. return ParentEntry;
  909. }
  910. }
  911. } else { // Advance to the next component
  912. auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
  913. for (std::unique_ptr<Entry> &Content :
  914. llvm::make_range(DE->contents_begin(), DE->contents_end())) {
  915. auto *DirContent = dyn_cast<RedirectingDirectoryEntry>(Content.get());
  916. if (DirContent && Name.equals(Content->getName()))
  917. return DirContent;
  918. }
  919. }
  920. // ... or create a new one
  921. std::unique_ptr<Entry> E = llvm::make_unique<RedirectingDirectoryEntry>(
  922. Name, Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0,
  923. 0, file_type::directory_file, sys::fs::all_all));
  924. if (!ParentEntry) { // Add a new root to the overlay
  925. FS->Roots.push_back(std::move(E));
  926. ParentEntry = FS->Roots.back().get();
  927. return ParentEntry;
  928. }
  929. auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
  930. DE->addContent(std::move(E));
  931. return DE->getLastContent();
  932. }
  933. void uniqueOverlayTree(RedirectingFileSystem *FS, Entry *SrcE,
  934. Entry *NewParentE = nullptr) {
  935. StringRef Name = SrcE->getName();
  936. switch (SrcE->getKind()) {
  937. case EK_Directory: {
  938. auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
  939. assert(DE && "Must be a directory");
  940. // Empty directories could be present in the YAML as a way to
  941. // describe a file for a current directory after some of its subdir
  942. // is parsed. This only leads to redundant walks, ignore it.
  943. if (!Name.empty())
  944. NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
  945. for (std::unique_ptr<Entry> &SubEntry :
  946. llvm::make_range(DE->contents_begin(), DE->contents_end()))
  947. uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
  948. break;
  949. }
  950. case EK_File: {
  951. auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
  952. assert(FE && "Must be a file");
  953. assert(NewParentE && "Parent entry must exist");
  954. auto *DE = dyn_cast<RedirectingDirectoryEntry>(NewParentE);
  955. DE->addContent(llvm::make_unique<RedirectingFileEntry>(
  956. Name, FE->getExternalContentsPath(), FE->getUseName()));
  957. break;
  958. }
  959. }
  960. }
  961. std::unique_ptr<Entry> parseEntry(yaml::Node *N, RedirectingFileSystem *FS) {
  962. yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
  963. if (!M) {
  964. error(N, "expected mapping node for file or directory entry");
  965. return nullptr;
  966. }
  967. KeyStatusPair Fields[] = {
  968. KeyStatusPair("name", true),
  969. KeyStatusPair("type", true),
  970. KeyStatusPair("contents", false),
  971. KeyStatusPair("external-contents", false),
  972. KeyStatusPair("use-external-name", false),
  973. };
  974. DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
  975. bool HasContents = false; // external or otherwise
  976. std::vector<std::unique_ptr<Entry>> EntryArrayContents;
  977. std::string ExternalContentsPath;
  978. std::string Name;
  979. auto UseExternalName = RedirectingFileEntry::NK_NotSet;
  980. EntryKind Kind;
  981. for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
  982. ++I) {
  983. StringRef Key;
  984. // Reuse the buffer for key and value, since we don't look at key after
  985. // parsing value.
  986. SmallString<256> Buffer;
  987. if (!parseScalarString(I->getKey(), Key, Buffer))
  988. return nullptr;
  989. if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
  990. return nullptr;
  991. StringRef Value;
  992. if (Key == "name") {
  993. if (!parseScalarString(I->getValue(), Value, Buffer))
  994. return nullptr;
  995. if (FS->UseCanonicalizedPaths) {
  996. SmallString<256> Path(Value);
  997. // Guarantee that old YAML files containing paths with ".." and "."
  998. // are properly canonicalized before read into the VFS.
  999. Path = sys::path::remove_leading_dotslash(Path);
  1000. sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
  1001. Name = Path.str();
  1002. } else {
  1003. Name = Value;
  1004. }
  1005. } else if (Key == "type") {
  1006. if (!parseScalarString(I->getValue(), Value, Buffer))
  1007. return nullptr;
  1008. if (Value == "file")
  1009. Kind = EK_File;
  1010. else if (Value == "directory")
  1011. Kind = EK_Directory;
  1012. else {
  1013. error(I->getValue(), "unknown value for 'type'");
  1014. return nullptr;
  1015. }
  1016. } else if (Key == "contents") {
  1017. if (HasContents) {
  1018. error(I->getKey(),
  1019. "entry already has 'contents' or 'external-contents'");
  1020. return nullptr;
  1021. }
  1022. HasContents = true;
  1023. yaml::SequenceNode *Contents =
  1024. dyn_cast<yaml::SequenceNode>(I->getValue());
  1025. if (!Contents) {
  1026. // FIXME: this is only for directories, what about files?
  1027. error(I->getValue(), "expected array");
  1028. return nullptr;
  1029. }
  1030. for (yaml::SequenceNode::iterator I = Contents->begin(),
  1031. E = Contents->end();
  1032. I != E; ++I) {
  1033. if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
  1034. EntryArrayContents.push_back(std::move(E));
  1035. else
  1036. return nullptr;
  1037. }
  1038. } else if (Key == "external-contents") {
  1039. if (HasContents) {
  1040. error(I->getKey(),
  1041. "entry already has 'contents' or 'external-contents'");
  1042. return nullptr;
  1043. }
  1044. HasContents = true;
  1045. if (!parseScalarString(I->getValue(), Value, Buffer))
  1046. return nullptr;
  1047. SmallString<256> FullPath;
  1048. if (FS->IsRelativeOverlay) {
  1049. FullPath = FS->getExternalContentsPrefixDir();
  1050. assert(!FullPath.empty() &&
  1051. "External contents prefix directory must exist");
  1052. llvm::sys::path::append(FullPath, Value);
  1053. } else {
  1054. FullPath = Value;
  1055. }
  1056. if (FS->UseCanonicalizedPaths) {
  1057. // Guarantee that old YAML files containing paths with ".." and "."
  1058. // are properly canonicalized before read into the VFS.
  1059. FullPath = sys::path::remove_leading_dotslash(FullPath);
  1060. sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
  1061. }
  1062. ExternalContentsPath = FullPath.str();
  1063. } else if (Key == "use-external-name") {
  1064. bool Val;
  1065. if (!parseScalarBool(I->getValue(), Val))
  1066. return nullptr;
  1067. UseExternalName = Val ? RedirectingFileEntry::NK_External
  1068. : RedirectingFileEntry::NK_Virtual;
  1069. } else {
  1070. llvm_unreachable("key missing from Keys");
  1071. }
  1072. }
  1073. if (Stream.failed())
  1074. return nullptr;
  1075. // check for missing keys
  1076. if (!HasContents) {
  1077. error(N, "missing key 'contents' or 'external-contents'");
  1078. return nullptr;
  1079. }
  1080. if (!checkMissingKeys(N, Keys))
  1081. return nullptr;
  1082. // check invalid configuration
  1083. if (Kind == EK_Directory &&
  1084. UseExternalName != RedirectingFileEntry::NK_NotSet) {
  1085. error(N, "'use-external-name' is not supported for directories");
  1086. return nullptr;
  1087. }
  1088. // Remove trailing slash(es), being careful not to remove the root path
  1089. StringRef Trimmed(Name);
  1090. size_t RootPathLen = sys::path::root_path(Trimmed).size();
  1091. while (Trimmed.size() > RootPathLen &&
  1092. sys::path::is_separator(Trimmed.back()))
  1093. Trimmed = Trimmed.slice(0, Trimmed.size()-1);
  1094. // Get the last component
  1095. StringRef LastComponent = sys::path::filename(Trimmed);
  1096. std::unique_ptr<Entry> Result;
  1097. switch (Kind) {
  1098. case EK_File:
  1099. Result = llvm::make_unique<RedirectingFileEntry>(
  1100. LastComponent, std::move(ExternalContentsPath), UseExternalName);
  1101. break;
  1102. case EK_Directory:
  1103. Result = llvm::make_unique<RedirectingDirectoryEntry>(
  1104. LastComponent, std::move(EntryArrayContents),
  1105. Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
  1106. file_type::directory_file, sys::fs::all_all));
  1107. break;
  1108. }
  1109. StringRef Parent = sys::path::parent_path(Trimmed);
  1110. if (Parent.empty())
  1111. return Result;
  1112. // if 'name' contains multiple components, create implicit directory entries
  1113. for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
  1114. E = sys::path::rend(Parent);
  1115. I != E; ++I) {
  1116. std::vector<std::unique_ptr<Entry>> Entries;
  1117. Entries.push_back(std::move(Result));
  1118. Result = llvm::make_unique<RedirectingDirectoryEntry>(
  1119. *I, std::move(Entries),
  1120. Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
  1121. file_type::directory_file, sys::fs::all_all));
  1122. }
  1123. return Result;
  1124. }
  1125. public:
  1126. RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
  1127. // false on error
  1128. bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
  1129. yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
  1130. if (!Top) {
  1131. error(Root, "expected mapping node");
  1132. return false;
  1133. }
  1134. KeyStatusPair Fields[] = {
  1135. KeyStatusPair("version", true),
  1136. KeyStatusPair("case-sensitive", false),
  1137. KeyStatusPair("use-external-names", false),
  1138. KeyStatusPair("overlay-relative", false),
  1139. KeyStatusPair("roots", true),
  1140. };
  1141. DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
  1142. std::vector<std::unique_ptr<Entry>> RootEntries;
  1143. // Parse configuration and 'roots'
  1144. for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
  1145. ++I) {
  1146. SmallString<10> KeyBuffer;
  1147. StringRef Key;
  1148. if (!parseScalarString(I->getKey(), Key, KeyBuffer))
  1149. return false;
  1150. if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
  1151. return false;
  1152. if (Key == "roots") {
  1153. yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
  1154. if (!Roots) {
  1155. error(I->getValue(), "expected array");
  1156. return false;
  1157. }
  1158. for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
  1159. I != E; ++I) {
  1160. if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
  1161. RootEntries.push_back(std::move(E));
  1162. else
  1163. return false;
  1164. }
  1165. } else if (Key == "version") {
  1166. StringRef VersionString;
  1167. SmallString<4> Storage;
  1168. if (!parseScalarString(I->getValue(), VersionString, Storage))
  1169. return false;
  1170. int Version;
  1171. if (VersionString.getAsInteger<int>(10, Version)) {
  1172. error(I->getValue(), "expected integer");
  1173. return false;
  1174. }
  1175. if (Version < 0) {
  1176. error(I->getValue(), "invalid version number");
  1177. return false;
  1178. }
  1179. if (Version != 0) {
  1180. error(I->getValue(), "version mismatch, expected 0");
  1181. return false;
  1182. }
  1183. } else if (Key == "case-sensitive") {
  1184. if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
  1185. return false;
  1186. } else if (Key == "overlay-relative") {
  1187. if (!parseScalarBool(I->getValue(), FS->IsRelativeOverlay))
  1188. return false;
  1189. } else if (Key == "use-external-names") {
  1190. if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
  1191. return false;
  1192. } else {
  1193. llvm_unreachable("key missing from Keys");
  1194. }
  1195. }
  1196. if (Stream.failed())
  1197. return false;
  1198. if (!checkMissingKeys(Top, Keys))
  1199. return false;
  1200. // Now that we sucessefully parsed the YAML file, canonicalize the internal
  1201. // representation to a proper directory tree so that we can search faster
  1202. // inside the VFS.
  1203. for (std::unique_ptr<Entry> &E : RootEntries)
  1204. uniqueOverlayTree(FS, E.get());
  1205. return true;
  1206. }
  1207. };
  1208. } // end of anonymous namespace
  1209. Entry::~Entry() = default;
  1210. RedirectingFileSystem *
  1211. RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
  1212. SourceMgr::DiagHandlerTy DiagHandler,
  1213. StringRef YAMLFilePath, void *DiagContext,
  1214. IntrusiveRefCntPtr<FileSystem> ExternalFS) {
  1215. SourceMgr SM;
  1216. yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
  1217. SM.setDiagHandler(DiagHandler, DiagContext);
  1218. yaml::document_iterator DI = Stream.begin();
  1219. yaml::Node *Root = DI->getRoot();
  1220. if (DI == Stream.end() || !Root) {
  1221. SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
  1222. return nullptr;
  1223. }
  1224. RedirectingFileSystemParser P(Stream);
  1225. std::unique_ptr<RedirectingFileSystem> FS(
  1226. new RedirectingFileSystem(std::move(ExternalFS)));
  1227. if (!YAMLFilePath.empty()) {
  1228. // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
  1229. // to each 'external-contents' path.
  1230. //
  1231. // Example:
  1232. // -ivfsoverlay dummy.cache/vfs/vfs.yaml
  1233. // yields:
  1234. // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
  1235. //
  1236. SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
  1237. std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
  1238. assert(!EC && "Overlay dir final path must be absolute");
  1239. (void)EC;
  1240. FS->setExternalContentsPrefixDir(OverlayAbsDir);
  1241. }
  1242. if (!P.parse(Root, FS.get()))
  1243. return nullptr;
  1244. return FS.release();
  1245. }
  1246. ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
  1247. SmallString<256> Path;
  1248. Path_.toVector(Path);
  1249. // Handle relative paths
  1250. if (std::error_code EC = makeAbsolute(Path))
  1251. return EC;
  1252. // Canonicalize path by removing ".", "..", "./", etc components. This is
  1253. // a VFS request, do bot bother about symlinks in the path components
  1254. // but canonicalize in order to perform the correct entry search.
  1255. if (UseCanonicalizedPaths) {
  1256. Path = sys::path::remove_leading_dotslash(Path);
  1257. sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
  1258. }
  1259. if (Path.empty())
  1260. return make_error_code(llvm::errc::invalid_argument);
  1261. sys::path::const_iterator Start = sys::path::begin(Path);
  1262. sys::path::const_iterator End = sys::path::end(Path);
  1263. for (const std::unique_ptr<Entry> &Root : Roots) {
  1264. ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
  1265. if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
  1266. return Result;
  1267. }
  1268. return make_error_code(llvm::errc::no_such_file_or_directory);
  1269. }
  1270. ErrorOr<Entry *>
  1271. RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
  1272. sys::path::const_iterator End, Entry *From) {
  1273. #ifndef LLVM_ON_WIN32
  1274. assert(!isTraversalComponent(*Start) &&
  1275. !isTraversalComponent(From->getName()) &&
  1276. "Paths should not contain traversal components");
  1277. #else
  1278. // FIXME: this is here to support windows, remove it once canonicalized
  1279. // paths become globally default.
  1280. if (Start->equals("."))
  1281. ++Start;
  1282. #endif
  1283. StringRef FromName = From->getName();
  1284. // Forward the search to the next component in case this is an empty one.
  1285. if (!FromName.empty()) {
  1286. if (CaseSensitive ? !Start->equals(FromName)
  1287. : !Start->equals_lower(FromName))
  1288. // failure to match
  1289. return make_error_code(llvm::errc::no_such_file_or_directory);
  1290. ++Start;
  1291. if (Start == End) {
  1292. // Match!
  1293. return From;
  1294. }
  1295. }
  1296. auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
  1297. if (!DE)
  1298. return make_error_code(llvm::errc::not_a_directory);
  1299. for (const std::unique_ptr<Entry> &DirEntry :
  1300. llvm::make_range(DE->contents_begin(), DE->contents_end())) {
  1301. ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
  1302. if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
  1303. return Result;
  1304. }
  1305. return make_error_code(llvm::errc::no_such_file_or_directory);
  1306. }
  1307. static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
  1308. Status ExternalStatus) {
  1309. Status S = ExternalStatus;
  1310. if (!UseExternalNames)
  1311. S = Status::copyWithNewName(S, Path.str());
  1312. S.IsVFSMapped = true;
  1313. return S;
  1314. }
  1315. ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
  1316. assert(E != nullptr);
  1317. if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
  1318. ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
  1319. assert(!S || S->getName() == F->getExternalContentsPath());
  1320. if (S)
  1321. return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
  1322. *S);
  1323. return S;
  1324. } else { // directory
  1325. auto *DE = cast<RedirectingDirectoryEntry>(E);
  1326. return Status::copyWithNewName(DE->getStatus(), Path.str());
  1327. }
  1328. }
  1329. ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
  1330. ErrorOr<Entry *> Result = lookupPath(Path);
  1331. if (!Result)
  1332. return Result.getError();
  1333. return status(Path, *Result);
  1334. }
  1335. namespace {
  1336. /// Provide a file wrapper with an overriden status.
  1337. class FileWithFixedStatus : public File {
  1338. std::unique_ptr<File> InnerFile;
  1339. Status S;
  1340. public:
  1341. FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
  1342. : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
  1343. ErrorOr<Status> status() override { return S; }
  1344. ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
  1345. getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
  1346. bool IsVolatile) override {
  1347. return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
  1348. IsVolatile);
  1349. }
  1350. std::error_code close() override { return InnerFile->close(); }
  1351. };
  1352. } // end anonymous namespace
  1353. ErrorOr<std::unique_ptr<File>>
  1354. RedirectingFileSystem::openFileForRead(const Twine &Path) {
  1355. ErrorOr<Entry *> E = lookupPath(Path);
  1356. if (!E)
  1357. return E.getError();
  1358. auto *F = dyn_cast<RedirectingFileEntry>(*E);
  1359. if (!F) // FIXME: errc::not_a_file?
  1360. return make_error_code(llvm::errc::invalid_argument);
  1361. auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
  1362. if (!Result)
  1363. return Result;
  1364. auto ExternalStatus = (*Result)->status();
  1365. if (!ExternalStatus)
  1366. return ExternalStatus.getError();
  1367. // FIXME: Update the status with the name and VFSMapped.
  1368. Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
  1369. *ExternalStatus);
  1370. return std::unique_ptr<File>(
  1371. llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
  1372. }
  1373. IntrusiveRefCntPtr<FileSystem>
  1374. vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
  1375. SourceMgr::DiagHandlerTy DiagHandler,
  1376. StringRef YAMLFilePath,
  1377. void *DiagContext,
  1378. IntrusiveRefCntPtr<FileSystem> ExternalFS) {
  1379. return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
  1380. YAMLFilePath, DiagContext,
  1381. std::move(ExternalFS));
  1382. }
  1383. UniqueID vfs::getNextVirtualUniqueID() {
  1384. static std::atomic<unsigned> UID;
  1385. unsigned ID = ++UID;
  1386. // The following assumes that uint64_t max will never collide with a real
  1387. // dev_t value from the OS.
  1388. return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
  1389. }
  1390. void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
  1391. assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
  1392. assert(sys::path::is_absolute(RealPath) && "real path not absolute");
  1393. assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
  1394. Mappings.emplace_back(VirtualPath, RealPath);
  1395. }
  1396. namespace {
  1397. class JSONWriter {
  1398. llvm::raw_ostream &OS;
  1399. SmallVector<StringRef, 16> DirStack;
  1400. inline unsigned getDirIndent() { return 4 * DirStack.size(); }
  1401. inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
  1402. bool containedIn(StringRef Parent, StringRef Path);
  1403. StringRef containedPart(StringRef Parent, StringRef Path);
  1404. void startDirectory(StringRef Path);
  1405. void endDirectory();
  1406. void writeEntry(StringRef VPath, StringRef RPath);
  1407. public:
  1408. JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
  1409. void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
  1410. Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
  1411. StringRef OverlayDir);
  1412. };
  1413. }
  1414. bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
  1415. using namespace llvm::sys;
  1416. // Compare each path component.
  1417. auto IParent = path::begin(Parent), EParent = path::end(Parent);
  1418. for (auto IChild = path::begin(Path), EChild = path::end(Path);
  1419. IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
  1420. if (*IParent != *IChild)
  1421. return false;
  1422. }
  1423. // Have we exhausted the parent path?
  1424. return IParent == EParent;
  1425. }
  1426. StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
  1427. assert(!Parent.empty());
  1428. assert(containedIn(Parent, Path));
  1429. return Path.slice(Parent.size() + 1, StringRef::npos);
  1430. }
  1431. void JSONWriter::startDirectory(StringRef Path) {
  1432. StringRef Name =
  1433. DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
  1434. DirStack.push_back(Path);
  1435. unsigned Indent = getDirIndent();
  1436. OS.indent(Indent) << "{\n";
  1437. OS.indent(Indent + 2) << "'type': 'directory',\n";
  1438. OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
  1439. OS.indent(Indent + 2) << "'contents': [\n";
  1440. }
  1441. void JSONWriter::endDirectory() {
  1442. unsigned Indent = getDirIndent();
  1443. OS.indent(Indent + 2) << "]\n";
  1444. OS.indent(Indent) << "}";
  1445. DirStack.pop_back();
  1446. }
  1447. void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
  1448. unsigned Indent = getFileIndent();
  1449. OS.indent(Indent) << "{\n";
  1450. OS.indent(Indent + 2) << "'type': 'file',\n";
  1451. OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
  1452. OS.indent(Indent + 2) << "'external-contents': \""
  1453. << llvm::yaml::escape(RPath) << "\"\n";
  1454. OS.indent(Indent) << "}";
  1455. }
  1456. void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
  1457. Optional<bool> UseExternalNames,
  1458. Optional<bool> IsCaseSensitive,
  1459. Optional<bool> IsOverlayRelative,
  1460. StringRef OverlayDir) {
  1461. using namespace llvm::sys;
  1462. OS << "{\n"
  1463. " 'version': 0,\n";
  1464. if (IsCaseSensitive.hasValue())
  1465. OS << " 'case-sensitive': '"
  1466. << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
  1467. if (UseExternalNames.hasValue())
  1468. OS << " 'use-external-names': '"
  1469. << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
  1470. bool UseOverlayRelative = false;
  1471. if (IsOverlayRelative.hasValue()) {
  1472. UseOverlayRelative = IsOverlayRelative.getValue();
  1473. OS << " 'overlay-relative': '"
  1474. << (UseOverlayRelative ? "true" : "false") << "',\n";
  1475. }
  1476. OS << " 'roots': [\n";
  1477. if (!Entries.empty()) {
  1478. const YAMLVFSEntry &Entry = Entries.front();
  1479. startDirectory(path::parent_path(Entry.VPath));
  1480. StringRef RPath = Entry.RPath;
  1481. if (UseOverlayRelative) {
  1482. unsigned OverlayDirLen = OverlayDir.size();
  1483. assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
  1484. "Overlay dir must be contained in RPath");
  1485. RPath = RPath.slice(OverlayDirLen, RPath.size());
  1486. }
  1487. writeEntry(path::filename(Entry.VPath), RPath);
  1488. for (const auto &Entry : Entries.slice(1)) {
  1489. StringRef Dir = path::parent_path(Entry.VPath);
  1490. if (Dir == DirStack.back())
  1491. OS << ",\n";
  1492. else {
  1493. while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
  1494. OS << "\n";
  1495. endDirectory();
  1496. }
  1497. OS << ",\n";
  1498. startDirectory(Dir);
  1499. }
  1500. StringRef RPath = Entry.RPath;
  1501. if (UseOverlayRelative) {
  1502. unsigned OverlayDirLen = OverlayDir.size();
  1503. assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
  1504. "Overlay dir must be contained in RPath");
  1505. RPath = RPath.slice(OverlayDirLen, RPath.size());
  1506. }
  1507. writeEntry(path::filename(Entry.VPath), RPath);
  1508. }
  1509. while (!DirStack.empty()) {
  1510. OS << "\n";
  1511. endDirectory();
  1512. }
  1513. OS << "\n";
  1514. }
  1515. OS << " ]\n"
  1516. << "}\n";
  1517. }
  1518. void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
  1519. std::sort(Mappings.begin(), Mappings.end(),
  1520. [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
  1521. return LHS.VPath < RHS.VPath;
  1522. });
  1523. JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
  1524. IsOverlayRelative, OverlayDir);
  1525. }
  1526. VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
  1527. const Twine &_Path, RedirectingFileSystem &FS,
  1528. RedirectingDirectoryEntry::iterator Begin,
  1529. RedirectingDirectoryEntry::iterator End, std::error_code &EC)
  1530. : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
  1531. if (Current != End) {
  1532. SmallString<128> PathStr(Dir);
  1533. llvm::sys::path::append(PathStr, (*Current)->getName());
  1534. llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
  1535. if (S)
  1536. CurrentEntry = *S;
  1537. else
  1538. EC = S.getError();
  1539. }
  1540. }
  1541. std::error_code VFSFromYamlDirIterImpl::increment() {
  1542. assert(Current != End && "cannot iterate past end");
  1543. if (++Current != End) {
  1544. SmallString<128> PathStr(Dir);
  1545. llvm::sys::path::append(PathStr, (*Current)->getName());
  1546. llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
  1547. if (!S)
  1548. return S.getError();
  1549. CurrentEntry = *S;
  1550. } else {
  1551. CurrentEntry = Status();
  1552. }
  1553. return std::error_code();
  1554. }
  1555. vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
  1556. const Twine &Path,
  1557. std::error_code &EC)
  1558. : FS(&FS_) {
  1559. directory_iterator I = FS->dir_begin(Path, EC);
  1560. if (!EC && I != directory_iterator()) {
  1561. State = std::make_shared<IterState>();
  1562. State->push(I);
  1563. }
  1564. }
  1565. vfs::recursive_directory_iterator &
  1566. recursive_directory_iterator::increment(std::error_code &EC) {
  1567. assert(FS && State && !State->empty() && "incrementing past end");
  1568. assert(State->top()->isStatusKnown() && "non-canonical end iterator");
  1569. vfs::directory_iterator End;
  1570. if (State->top()->isDirectory()) {
  1571. vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
  1572. if (EC)
  1573. return *this;
  1574. if (I != End) {
  1575. State->push(I);
  1576. return *this;
  1577. }
  1578. }
  1579. while (!State->empty() && State->top().increment(EC) == End)
  1580. State->pop();
  1581. if (State->empty())
  1582. State.reset(); // end iterator
  1583. return *this;
  1584. }