VirtualFileSystem.cpp 61 KB

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