VirtualFileSystem.cpp 70 KB

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