VirtualFileSystem.cpp 55 KB

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