VirtualFileSystem.cpp 63 KB

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