VirtualFileSystem.cpp 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885
  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. assert(isStatusKnown() && Other.isStatusKnown());
  56. return getUniqueID() == Other.getUniqueID();
  57. }
  58. bool Status::isDirectory() const {
  59. return Type == file_type::directory_file;
  60. }
  61. bool Status::isRegularFile() const {
  62. return Type == file_type::regular_file;
  63. }
  64. bool Status::isOther() const {
  65. return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
  66. }
  67. bool Status::isSymlink() const {
  68. return Type == file_type::symlink_file;
  69. }
  70. bool Status::isStatusKnown() const {
  71. return Type != file_type::status_error;
  72. }
  73. bool Status::exists() const {
  74. return isStatusKnown() && Type != file_type::file_not_found;
  75. }
  76. File::~File() {}
  77. FileSystem::~FileSystem() {}
  78. ErrorOr<std::unique_ptr<MemoryBuffer>>
  79. FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
  80. bool RequiresNullTerminator, bool IsVolatile) {
  81. auto F = openFileForRead(Name);
  82. if (!F)
  83. return F.getError();
  84. return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
  85. }
  86. std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
  87. if (llvm::sys::path::is_absolute(Path))
  88. return std::error_code();
  89. auto WorkingDir = getCurrentWorkingDirectory();
  90. if (!WorkingDir)
  91. return WorkingDir.getError();
  92. return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
  93. }
  94. bool FileSystem::exists(const Twine &Path) {
  95. auto Status = status(Path);
  96. return Status && Status->exists();
  97. }
  98. #ifndef NDEBUG
  99. static bool isTraversalComponent(StringRef Component) {
  100. return Component.equals("..") || Component.equals(".");
  101. }
  102. static bool pathHasTraversal(StringRef Path) {
  103. using namespace llvm::sys;
  104. for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
  105. if (isTraversalComponent(Comp))
  106. return true;
  107. return false;
  108. }
  109. #endif
  110. //===-----------------------------------------------------------------------===/
  111. // RealFileSystem implementation
  112. //===-----------------------------------------------------------------------===/
  113. namespace {
  114. /// \brief Wrapper around a raw file descriptor.
  115. class RealFile : public File {
  116. int FD;
  117. Status S;
  118. std::string RealName;
  119. friend class RealFileSystem;
  120. RealFile(int FD, StringRef NewName, StringRef NewRealPathName)
  121. : FD(FD), S(NewName, {}, {}, {}, {}, {},
  122. llvm::sys::fs::file_type::status_error, {}),
  123. RealName(NewRealPathName.str()) {
  124. assert(FD >= 0 && "Invalid or inactive file descriptor");
  125. }
  126. public:
  127. ~RealFile() override;
  128. ErrorOr<Status> status() override;
  129. ErrorOr<std::string> getName() override;
  130. ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
  131. int64_t FileSize,
  132. bool RequiresNullTerminator,
  133. bool IsVolatile) override;
  134. std::error_code close() override;
  135. };
  136. } // end anonymous namespace
  137. RealFile::~RealFile() { close(); }
  138. ErrorOr<Status> RealFile::status() {
  139. assert(FD != -1 && "cannot stat closed file");
  140. if (!S.isStatusKnown()) {
  141. file_status RealStatus;
  142. if (std::error_code EC = sys::fs::status(FD, RealStatus))
  143. return EC;
  144. S = Status::copyWithNewName(RealStatus, S.getName());
  145. }
  146. return S;
  147. }
  148. ErrorOr<std::string> RealFile::getName() {
  149. return RealName.empty() ? S.getName().str() : RealName;
  150. }
  151. ErrorOr<std::unique_ptr<MemoryBuffer>>
  152. RealFile::getBuffer(const Twine &Name, int64_t FileSize,
  153. bool RequiresNullTerminator, bool IsVolatile) {
  154. assert(FD != -1 && "cannot get buffer for closed file");
  155. return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
  156. IsVolatile);
  157. }
  158. std::error_code RealFile::close() {
  159. std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD);
  160. FD = -1;
  161. return EC;
  162. }
  163. namespace {
  164. /// \brief The file system according to your operating system.
  165. class RealFileSystem : public FileSystem {
  166. public:
  167. ErrorOr<Status> status(const Twine &Path) override;
  168. ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
  169. directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
  170. llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
  171. std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
  172. };
  173. } // end anonymous namespace
  174. ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
  175. sys::fs::file_status RealStatus;
  176. if (std::error_code EC = sys::fs::status(Path, RealStatus))
  177. return EC;
  178. return Status::copyWithNewName(RealStatus, Path.str());
  179. }
  180. ErrorOr<std::unique_ptr<File>>
  181. RealFileSystem::openFileForRead(const Twine &Name) {
  182. int FD;
  183. SmallString<256> RealName;
  184. if (std::error_code EC = sys::fs::openFileForRead(Name, FD, &RealName))
  185. return EC;
  186. return std::unique_ptr<File>(new RealFile(FD, Name.str(), RealName.str()));
  187. }
  188. llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
  189. SmallString<256> Dir;
  190. if (std::error_code EC = llvm::sys::fs::current_path(Dir))
  191. return EC;
  192. return Dir.str().str();
  193. }
  194. std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
  195. // FIXME: chdir is thread hostile; on the other hand, creating the same
  196. // behavior as chdir is complex: chdir resolves the path once, thus
  197. // guaranteeing that all subsequent relative path operations work
  198. // on the same path the original chdir resulted in. This makes a
  199. // difference for example on network filesystems, where symlinks might be
  200. // switched during runtime of the tool. Fixing this depends on having a
  201. // file system abstraction that allows openat() style interactions.
  202. return llvm::sys::fs::set_current_path(Path);
  203. }
  204. IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
  205. static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
  206. return FS;
  207. }
  208. namespace {
  209. class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
  210. llvm::sys::fs::directory_iterator Iter;
  211. public:
  212. RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) {
  213. if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
  214. llvm::sys::fs::file_status S;
  215. EC = Iter->status(S);
  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 (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 (I != End) {
  1637. State->push(I);
  1638. return *this;
  1639. }
  1640. }
  1641. while (!State->empty() && State->top().increment(EC) == End)
  1642. State->pop();
  1643. if (State->empty())
  1644. State.reset(); // end iterator
  1645. return *this;
  1646. }