VirtualFileSystem.cpp 59 KB

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