VirtualFileSystem.cpp 64 KB

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