VirtualFileSystem.cpp 55 KB

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