VirtualFileSystem.cpp 65 KB

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