VirtualFileSystem.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  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. ///
  678. /// Virtual directories are represented as
  679. /// \verbatim
  680. /// {
  681. /// 'type': 'directory',
  682. /// 'name': <string>,
  683. /// 'contents': [ <file or directory entries> ]
  684. /// }
  685. /// \endverbatim
  686. ///
  687. /// The default attributes for virtual directories are:
  688. /// \verbatim
  689. /// MTime = now() when created
  690. /// Perms = 0777
  691. /// User = Group = 0
  692. /// Size = 0
  693. /// UniqueID = unspecified unique value
  694. /// \endverbatim
  695. ///
  696. /// Re-mapped files are represented as
  697. /// \verbatim
  698. /// {
  699. /// 'type': 'file',
  700. /// 'name': <string>,
  701. /// 'use-external-name': <boolean> # Optional
  702. /// 'external-contents': <path to external file>)
  703. /// }
  704. /// \endverbatim
  705. ///
  706. /// and inherit their attributes from the external contents.
  707. ///
  708. /// In both cases, the 'name' field may contain multiple path components (e.g.
  709. /// /path/to/file). However, any directory that contains more than one child
  710. /// must be uniquely represented by a directory entry.
  711. class RedirectingFileSystem : public vfs::FileSystem {
  712. /// The root(s) of the virtual file system.
  713. std::vector<std::unique_ptr<Entry>> Roots;
  714. /// \brief The file system to use for external references.
  715. IntrusiveRefCntPtr<FileSystem> ExternalFS;
  716. /// @name Configuration
  717. /// @{
  718. /// \brief Whether to perform case-sensitive comparisons.
  719. ///
  720. /// Currently, case-insensitive matching only works correctly with ASCII.
  721. bool CaseSensitive;
  722. /// \brief Whether to use to use the value of 'external-contents' for the
  723. /// names of files. This global value is overridable on a per-file basis.
  724. bool UseExternalNames;
  725. /// @}
  726. /// Virtual file paths and external files could be canonicalized without "..",
  727. /// "." and "./" in their paths. FIXME: some unittests currently fail on
  728. /// win32 when using remove_dots and remove_leading_dotslash on paths.
  729. bool UseCanonicalizedPaths =
  730. #ifdef LLVM_ON_WIN32
  731. false;
  732. #else
  733. true;
  734. #endif
  735. friend class RedirectingFileSystemParser;
  736. private:
  737. RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
  738. : ExternalFS(ExternalFS), CaseSensitive(true), UseExternalNames(true) {}
  739. /// \brief Looks up \p Path in \c Roots.
  740. ErrorOr<Entry *> lookupPath(const Twine &Path);
  741. /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
  742. /// recursing into the contents of \p From if it is a directory.
  743. ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
  744. sys::path::const_iterator End, Entry *From);
  745. /// \brief Get the status of a given an \c Entry.
  746. ErrorOr<Status> status(const Twine &Path, Entry *E);
  747. public:
  748. /// \brief Parses \p Buffer, which is expected to be in YAML format and
  749. /// returns a virtual file system representing its contents.
  750. static RedirectingFileSystem *
  751. create(std::unique_ptr<MemoryBuffer> Buffer,
  752. SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext,
  753. IntrusiveRefCntPtr<FileSystem> ExternalFS);
  754. ErrorOr<Status> status(const Twine &Path) override;
  755. ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
  756. llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
  757. return ExternalFS->getCurrentWorkingDirectory();
  758. }
  759. std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
  760. return ExternalFS->setCurrentWorkingDirectory(Path);
  761. }
  762. directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
  763. ErrorOr<Entry *> E = lookupPath(Dir);
  764. if (!E) {
  765. EC = E.getError();
  766. return directory_iterator();
  767. }
  768. ErrorOr<Status> S = status(Dir, *E);
  769. if (!S) {
  770. EC = S.getError();
  771. return directory_iterator();
  772. }
  773. if (!S->isDirectory()) {
  774. EC = std::error_code(static_cast<int>(errc::not_a_directory),
  775. std::system_category());
  776. return directory_iterator();
  777. }
  778. auto *D = cast<RedirectingDirectoryEntry>(*E);
  779. return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
  780. *this, D->contents_begin(), D->contents_end(), EC));
  781. }
  782. };
  783. /// \brief A helper class to hold the common YAML parsing state.
  784. class RedirectingFileSystemParser {
  785. yaml::Stream &Stream;
  786. void error(yaml::Node *N, const Twine &Msg) {
  787. Stream.printError(N, Msg);
  788. }
  789. // false on error
  790. bool parseScalarString(yaml::Node *N, StringRef &Result,
  791. SmallVectorImpl<char> &Storage) {
  792. yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
  793. if (!S) {
  794. error(N, "expected string");
  795. return false;
  796. }
  797. Result = S->getValue(Storage);
  798. return true;
  799. }
  800. // false on error
  801. bool parseScalarBool(yaml::Node *N, bool &Result) {
  802. SmallString<5> Storage;
  803. StringRef Value;
  804. if (!parseScalarString(N, Value, Storage))
  805. return false;
  806. if (Value.equals_lower("true") || Value.equals_lower("on") ||
  807. Value.equals_lower("yes") || Value == "1") {
  808. Result = true;
  809. return true;
  810. } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
  811. Value.equals_lower("no") || Value == "0") {
  812. Result = false;
  813. return true;
  814. }
  815. error(N, "expected boolean value");
  816. return false;
  817. }
  818. struct KeyStatus {
  819. KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
  820. bool Required;
  821. bool Seen;
  822. };
  823. typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
  824. // false on error
  825. bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
  826. DenseMap<StringRef, KeyStatus> &Keys) {
  827. if (!Keys.count(Key)) {
  828. error(KeyNode, "unknown key");
  829. return false;
  830. }
  831. KeyStatus &S = Keys[Key];
  832. if (S.Seen) {
  833. error(KeyNode, Twine("duplicate key '") + Key + "'");
  834. return false;
  835. }
  836. S.Seen = true;
  837. return true;
  838. }
  839. // false on error
  840. bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
  841. for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
  842. E = Keys.end();
  843. I != E; ++I) {
  844. if (I->second.Required && !I->second.Seen) {
  845. error(Obj, Twine("missing key '") + I->first + "'");
  846. return false;
  847. }
  848. }
  849. return true;
  850. }
  851. std::unique_ptr<Entry> parseEntry(yaml::Node *N, RedirectingFileSystem *FS) {
  852. yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
  853. if (!M) {
  854. error(N, "expected mapping node for file or directory entry");
  855. return nullptr;
  856. }
  857. KeyStatusPair Fields[] = {
  858. KeyStatusPair("name", true),
  859. KeyStatusPair("type", true),
  860. KeyStatusPair("contents", false),
  861. KeyStatusPair("external-contents", false),
  862. KeyStatusPair("use-external-name", false),
  863. };
  864. DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
  865. bool HasContents = false; // external or otherwise
  866. std::vector<std::unique_ptr<Entry>> EntryArrayContents;
  867. std::string ExternalContentsPath;
  868. std::string Name;
  869. auto UseExternalName = RedirectingFileEntry::NK_NotSet;
  870. EntryKind Kind;
  871. for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
  872. ++I) {
  873. StringRef Key;
  874. // Reuse the buffer for key and value, since we don't look at key after
  875. // parsing value.
  876. SmallString<256> Buffer;
  877. if (!parseScalarString(I->getKey(), Key, Buffer))
  878. return nullptr;
  879. if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
  880. return nullptr;
  881. StringRef Value;
  882. if (Key == "name") {
  883. if (!parseScalarString(I->getValue(), Value, Buffer))
  884. return nullptr;
  885. if (FS->UseCanonicalizedPaths) {
  886. SmallString<256> Path(Value);
  887. // Guarantee that old YAML files containing paths with ".." and "."
  888. // are properly canonicalized before read into the VFS.
  889. Path = sys::path::remove_leading_dotslash(Path);
  890. sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
  891. Name = Path.str();
  892. } else {
  893. Name = Value;
  894. }
  895. } else if (Key == "type") {
  896. if (!parseScalarString(I->getValue(), Value, Buffer))
  897. return nullptr;
  898. if (Value == "file")
  899. Kind = EK_File;
  900. else if (Value == "directory")
  901. Kind = EK_Directory;
  902. else {
  903. error(I->getValue(), "unknown value for 'type'");
  904. return nullptr;
  905. }
  906. } else if (Key == "contents") {
  907. if (HasContents) {
  908. error(I->getKey(),
  909. "entry already has 'contents' or 'external-contents'");
  910. return nullptr;
  911. }
  912. HasContents = true;
  913. yaml::SequenceNode *Contents =
  914. dyn_cast<yaml::SequenceNode>(I->getValue());
  915. if (!Contents) {
  916. // FIXME: this is only for directories, what about files?
  917. error(I->getValue(), "expected array");
  918. return nullptr;
  919. }
  920. for (yaml::SequenceNode::iterator I = Contents->begin(),
  921. E = Contents->end();
  922. I != E; ++I) {
  923. if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
  924. EntryArrayContents.push_back(std::move(E));
  925. else
  926. return nullptr;
  927. }
  928. } else if (Key == "external-contents") {
  929. if (HasContents) {
  930. error(I->getKey(),
  931. "entry already has 'contents' or 'external-contents'");
  932. return nullptr;
  933. }
  934. HasContents = true;
  935. if (!parseScalarString(I->getValue(), Value, Buffer))
  936. return nullptr;
  937. if (FS->UseCanonicalizedPaths) {
  938. SmallString<256> Path(Value);
  939. // Guarantee that old YAML files containing paths with ".." and "."
  940. // are properly canonicalized before read into the VFS.
  941. Path = sys::path::remove_leading_dotslash(Path);
  942. sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
  943. ExternalContentsPath = Path.str();
  944. } else {
  945. ExternalContentsPath = Value;
  946. }
  947. } else if (Key == "use-external-name") {
  948. bool Val;
  949. if (!parseScalarBool(I->getValue(), Val))
  950. return nullptr;
  951. UseExternalName = Val ? RedirectingFileEntry::NK_External
  952. : RedirectingFileEntry::NK_Virtual;
  953. } else {
  954. llvm_unreachable("key missing from Keys");
  955. }
  956. }
  957. if (Stream.failed())
  958. return nullptr;
  959. // check for missing keys
  960. if (!HasContents) {
  961. error(N, "missing key 'contents' or 'external-contents'");
  962. return nullptr;
  963. }
  964. if (!checkMissingKeys(N, Keys))
  965. return nullptr;
  966. // check invalid configuration
  967. if (Kind == EK_Directory &&
  968. UseExternalName != RedirectingFileEntry::NK_NotSet) {
  969. error(N, "'use-external-name' is not supported for directories");
  970. return nullptr;
  971. }
  972. // Remove trailing slash(es), being careful not to remove the root path
  973. StringRef Trimmed(Name);
  974. size_t RootPathLen = sys::path::root_path(Trimmed).size();
  975. while (Trimmed.size() > RootPathLen &&
  976. sys::path::is_separator(Trimmed.back()))
  977. Trimmed = Trimmed.slice(0, Trimmed.size()-1);
  978. // Get the last component
  979. StringRef LastComponent = sys::path::filename(Trimmed);
  980. std::unique_ptr<Entry> Result;
  981. switch (Kind) {
  982. case EK_File:
  983. Result = llvm::make_unique<RedirectingFileEntry>(
  984. LastComponent, std::move(ExternalContentsPath), UseExternalName);
  985. break;
  986. case EK_Directory:
  987. Result = llvm::make_unique<RedirectingDirectoryEntry>(
  988. LastComponent, std::move(EntryArrayContents),
  989. Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
  990. file_type::directory_file, sys::fs::all_all));
  991. break;
  992. }
  993. StringRef Parent = sys::path::parent_path(Trimmed);
  994. if (Parent.empty())
  995. return Result;
  996. // if 'name' contains multiple components, create implicit directory entries
  997. for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
  998. E = sys::path::rend(Parent);
  999. I != E; ++I) {
  1000. std::vector<std::unique_ptr<Entry>> Entries;
  1001. Entries.push_back(std::move(Result));
  1002. Result = llvm::make_unique<RedirectingDirectoryEntry>(
  1003. *I, std::move(Entries),
  1004. Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
  1005. file_type::directory_file, sys::fs::all_all));
  1006. }
  1007. return Result;
  1008. }
  1009. public:
  1010. RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
  1011. // false on error
  1012. bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
  1013. yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
  1014. if (!Top) {
  1015. error(Root, "expected mapping node");
  1016. return false;
  1017. }
  1018. KeyStatusPair Fields[] = {
  1019. KeyStatusPair("version", true),
  1020. KeyStatusPair("case-sensitive", false),
  1021. KeyStatusPair("use-external-names", false),
  1022. KeyStatusPair("roots", true),
  1023. };
  1024. DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
  1025. // Parse configuration and 'roots'
  1026. for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
  1027. ++I) {
  1028. SmallString<10> KeyBuffer;
  1029. StringRef Key;
  1030. if (!parseScalarString(I->getKey(), Key, KeyBuffer))
  1031. return false;
  1032. if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
  1033. return false;
  1034. if (Key == "roots") {
  1035. yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
  1036. if (!Roots) {
  1037. error(I->getValue(), "expected array");
  1038. return false;
  1039. }
  1040. for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
  1041. I != E; ++I) {
  1042. if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
  1043. FS->Roots.push_back(std::move(E));
  1044. else
  1045. return false;
  1046. }
  1047. } else if (Key == "version") {
  1048. StringRef VersionString;
  1049. SmallString<4> Storage;
  1050. if (!parseScalarString(I->getValue(), VersionString, Storage))
  1051. return false;
  1052. int Version;
  1053. if (VersionString.getAsInteger<int>(10, Version)) {
  1054. error(I->getValue(), "expected integer");
  1055. return false;
  1056. }
  1057. if (Version < 0) {
  1058. error(I->getValue(), "invalid version number");
  1059. return false;
  1060. }
  1061. if (Version != 0) {
  1062. error(I->getValue(), "version mismatch, expected 0");
  1063. return false;
  1064. }
  1065. } else if (Key == "case-sensitive") {
  1066. if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
  1067. return false;
  1068. } else if (Key == "use-external-names") {
  1069. if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
  1070. return false;
  1071. } else {
  1072. llvm_unreachable("key missing from Keys");
  1073. }
  1074. }
  1075. if (Stream.failed())
  1076. return false;
  1077. if (!checkMissingKeys(Top, Keys))
  1078. return false;
  1079. return true;
  1080. }
  1081. };
  1082. } // end of anonymous namespace
  1083. Entry::~Entry() = default;
  1084. RedirectingFileSystem *RedirectingFileSystem::create(
  1085. std::unique_ptr<MemoryBuffer> Buffer, SourceMgr::DiagHandlerTy DiagHandler,
  1086. void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS) {
  1087. SourceMgr SM;
  1088. yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
  1089. SM.setDiagHandler(DiagHandler, DiagContext);
  1090. yaml::document_iterator DI = Stream.begin();
  1091. yaml::Node *Root = DI->getRoot();
  1092. if (DI == Stream.end() || !Root) {
  1093. SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
  1094. return nullptr;
  1095. }
  1096. RedirectingFileSystemParser P(Stream);
  1097. std::unique_ptr<RedirectingFileSystem> FS(
  1098. new RedirectingFileSystem(ExternalFS));
  1099. if (!P.parse(Root, FS.get()))
  1100. return nullptr;
  1101. return FS.release();
  1102. }
  1103. ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
  1104. SmallString<256> Path;
  1105. Path_.toVector(Path);
  1106. // Handle relative paths
  1107. if (std::error_code EC = makeAbsolute(Path))
  1108. return EC;
  1109. // Canonicalize path by removing ".", "..", "./", etc components. This is
  1110. // a VFS request, do bot bother about symlinks in the path components
  1111. // but canonicalize in order to perform the correct entry search.
  1112. if (UseCanonicalizedPaths) {
  1113. Path = sys::path::remove_leading_dotslash(Path);
  1114. sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
  1115. }
  1116. if (Path.empty())
  1117. return make_error_code(llvm::errc::invalid_argument);
  1118. sys::path::const_iterator Start = sys::path::begin(Path);
  1119. sys::path::const_iterator End = sys::path::end(Path);
  1120. for (const std::unique_ptr<Entry> &Root : Roots) {
  1121. ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
  1122. if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
  1123. return Result;
  1124. }
  1125. return make_error_code(llvm::errc::no_such_file_or_directory);
  1126. }
  1127. ErrorOr<Entry *>
  1128. RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
  1129. sys::path::const_iterator End, Entry *From) {
  1130. #ifndef LLVM_ON_WIN32
  1131. assert(!isTraversalComponent(*Start) &&
  1132. !isTraversalComponent(From->getName()) &&
  1133. "Paths should not contain traversal components");
  1134. #else
  1135. // FIXME: this is here to support windows, remove it once canonicalized
  1136. // paths become globally default.
  1137. if (Start->equals("."))
  1138. ++Start;
  1139. #endif
  1140. if (CaseSensitive ? !Start->equals(From->getName())
  1141. : !Start->equals_lower(From->getName()))
  1142. // failure to match
  1143. return make_error_code(llvm::errc::no_such_file_or_directory);
  1144. ++Start;
  1145. if (Start == End) {
  1146. // Match!
  1147. return From;
  1148. }
  1149. auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
  1150. if (!DE)
  1151. return make_error_code(llvm::errc::not_a_directory);
  1152. for (const std::unique_ptr<Entry> &DirEntry :
  1153. llvm::make_range(DE->contents_begin(), DE->contents_end())) {
  1154. ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
  1155. if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
  1156. return Result;
  1157. }
  1158. return make_error_code(llvm::errc::no_such_file_or_directory);
  1159. }
  1160. static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
  1161. Status ExternalStatus) {
  1162. Status S = ExternalStatus;
  1163. if (!UseExternalNames)
  1164. S = Status::copyWithNewName(S, Path.str());
  1165. S.IsVFSMapped = true;
  1166. return S;
  1167. }
  1168. ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
  1169. assert(E != nullptr);
  1170. if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
  1171. ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
  1172. assert(!S || S->getName() == F->getExternalContentsPath());
  1173. if (S)
  1174. return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
  1175. *S);
  1176. return S;
  1177. } else { // directory
  1178. auto *DE = cast<RedirectingDirectoryEntry>(E);
  1179. return Status::copyWithNewName(DE->getStatus(), Path.str());
  1180. }
  1181. }
  1182. ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
  1183. ErrorOr<Entry *> Result = lookupPath(Path);
  1184. if (!Result)
  1185. return Result.getError();
  1186. return status(Path, *Result);
  1187. }
  1188. namespace {
  1189. /// Provide a file wrapper with an overriden status.
  1190. class FileWithFixedStatus : public File {
  1191. std::unique_ptr<File> InnerFile;
  1192. Status S;
  1193. public:
  1194. FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
  1195. : InnerFile(std::move(InnerFile)), S(S) {}
  1196. ErrorOr<Status> status() override { return S; }
  1197. ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
  1198. getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
  1199. bool IsVolatile) override {
  1200. return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
  1201. IsVolatile);
  1202. }
  1203. std::error_code close() override { return InnerFile->close(); }
  1204. };
  1205. } // end anonymous namespace
  1206. ErrorOr<std::unique_ptr<File>>
  1207. RedirectingFileSystem::openFileForRead(const Twine &Path) {
  1208. ErrorOr<Entry *> E = lookupPath(Path);
  1209. if (!E)
  1210. return E.getError();
  1211. auto *F = dyn_cast<RedirectingFileEntry>(*E);
  1212. if (!F) // FIXME: errc::not_a_file?
  1213. return make_error_code(llvm::errc::invalid_argument);
  1214. auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
  1215. if (!Result)
  1216. return Result;
  1217. auto ExternalStatus = (*Result)->status();
  1218. if (!ExternalStatus)
  1219. return ExternalStatus.getError();
  1220. // FIXME: Update the status with the name and VFSMapped.
  1221. Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
  1222. *ExternalStatus);
  1223. return std::unique_ptr<File>(
  1224. llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
  1225. }
  1226. IntrusiveRefCntPtr<FileSystem>
  1227. vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
  1228. SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext,
  1229. IntrusiveRefCntPtr<FileSystem> ExternalFS) {
  1230. return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
  1231. DiagContext, ExternalFS);
  1232. }
  1233. UniqueID vfs::getNextVirtualUniqueID() {
  1234. static std::atomic<unsigned> UID;
  1235. unsigned ID = ++UID;
  1236. // The following assumes that uint64_t max will never collide with a real
  1237. // dev_t value from the OS.
  1238. return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
  1239. }
  1240. void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
  1241. assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
  1242. assert(sys::path::is_absolute(RealPath) && "real path not absolute");
  1243. assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
  1244. Mappings.emplace_back(VirtualPath, RealPath);
  1245. }
  1246. namespace {
  1247. class JSONWriter {
  1248. llvm::raw_ostream &OS;
  1249. SmallVector<StringRef, 16> DirStack;
  1250. inline unsigned getDirIndent() { return 4 * DirStack.size(); }
  1251. inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
  1252. bool containedIn(StringRef Parent, StringRef Path);
  1253. StringRef containedPart(StringRef Parent, StringRef Path);
  1254. void startDirectory(StringRef Path);
  1255. void endDirectory();
  1256. void writeEntry(StringRef VPath, StringRef RPath);
  1257. public:
  1258. JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
  1259. void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive);
  1260. };
  1261. }
  1262. bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
  1263. using namespace llvm::sys;
  1264. // Compare each path component.
  1265. auto IParent = path::begin(Parent), EParent = path::end(Parent);
  1266. for (auto IChild = path::begin(Path), EChild = path::end(Path);
  1267. IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
  1268. if (*IParent != *IChild)
  1269. return false;
  1270. }
  1271. // Have we exhausted the parent path?
  1272. return IParent == EParent;
  1273. }
  1274. StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
  1275. assert(!Parent.empty());
  1276. assert(containedIn(Parent, Path));
  1277. return Path.slice(Parent.size() + 1, StringRef::npos);
  1278. }
  1279. void JSONWriter::startDirectory(StringRef Path) {
  1280. StringRef Name =
  1281. DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
  1282. DirStack.push_back(Path);
  1283. unsigned Indent = getDirIndent();
  1284. OS.indent(Indent) << "{\n";
  1285. OS.indent(Indent + 2) << "'type': 'directory',\n";
  1286. OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
  1287. OS.indent(Indent + 2) << "'contents': [\n";
  1288. }
  1289. void JSONWriter::endDirectory() {
  1290. unsigned Indent = getDirIndent();
  1291. OS.indent(Indent + 2) << "]\n";
  1292. OS.indent(Indent) << "}";
  1293. DirStack.pop_back();
  1294. }
  1295. void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
  1296. unsigned Indent = getFileIndent();
  1297. OS.indent(Indent) << "{\n";
  1298. OS.indent(Indent + 2) << "'type': 'file',\n";
  1299. OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
  1300. OS.indent(Indent + 2) << "'external-contents': \""
  1301. << llvm::yaml::escape(RPath) << "\"\n";
  1302. OS.indent(Indent) << "}";
  1303. }
  1304. void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
  1305. Optional<bool> IsCaseSensitive) {
  1306. using namespace llvm::sys;
  1307. OS << "{\n"
  1308. " 'version': 0,\n";
  1309. if (IsCaseSensitive.hasValue())
  1310. OS << " 'case-sensitive': '"
  1311. << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
  1312. OS << " 'roots': [\n";
  1313. if (!Entries.empty()) {
  1314. const YAMLVFSEntry &Entry = Entries.front();
  1315. startDirectory(path::parent_path(Entry.VPath));
  1316. writeEntry(path::filename(Entry.VPath), Entry.RPath);
  1317. for (const auto &Entry : Entries.slice(1)) {
  1318. StringRef Dir = path::parent_path(Entry.VPath);
  1319. if (Dir == DirStack.back())
  1320. OS << ",\n";
  1321. else {
  1322. while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
  1323. OS << "\n";
  1324. endDirectory();
  1325. }
  1326. OS << ",\n";
  1327. startDirectory(Dir);
  1328. }
  1329. writeEntry(path::filename(Entry.VPath), Entry.RPath);
  1330. }
  1331. while (!DirStack.empty()) {
  1332. OS << "\n";
  1333. endDirectory();
  1334. }
  1335. OS << "\n";
  1336. }
  1337. OS << " ]\n"
  1338. << "}\n";
  1339. }
  1340. void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
  1341. std::sort(Mappings.begin(), Mappings.end(),
  1342. [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
  1343. return LHS.VPath < RHS.VPath;
  1344. });
  1345. JSONWriter(OS).write(Mappings, IsCaseSensitive);
  1346. }
  1347. VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
  1348. const Twine &_Path, RedirectingFileSystem &FS,
  1349. RedirectingDirectoryEntry::iterator Begin,
  1350. RedirectingDirectoryEntry::iterator End, std::error_code &EC)
  1351. : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
  1352. if (Current != End) {
  1353. SmallString<128> PathStr(Dir);
  1354. llvm::sys::path::append(PathStr, (*Current)->getName());
  1355. llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
  1356. if (S)
  1357. CurrentEntry = *S;
  1358. else
  1359. EC = S.getError();
  1360. }
  1361. }
  1362. std::error_code VFSFromYamlDirIterImpl::increment() {
  1363. assert(Current != End && "cannot iterate past end");
  1364. if (++Current != End) {
  1365. SmallString<128> PathStr(Dir);
  1366. llvm::sys::path::append(PathStr, (*Current)->getName());
  1367. llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
  1368. if (!S)
  1369. return S.getError();
  1370. CurrentEntry = *S;
  1371. } else {
  1372. CurrentEntry = Status();
  1373. }
  1374. return std::error_code();
  1375. }
  1376. vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
  1377. const Twine &Path,
  1378. std::error_code &EC)
  1379. : FS(&FS_) {
  1380. directory_iterator I = FS->dir_begin(Path, EC);
  1381. if (!EC && I != directory_iterator()) {
  1382. State = std::make_shared<IterState>();
  1383. State->push(I);
  1384. }
  1385. }
  1386. vfs::recursive_directory_iterator &
  1387. recursive_directory_iterator::increment(std::error_code &EC) {
  1388. assert(FS && State && !State->empty() && "incrementing past end");
  1389. assert(State->top()->isStatusKnown() && "non-canonical end iterator");
  1390. vfs::directory_iterator End;
  1391. if (State->top()->isDirectory()) {
  1392. vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
  1393. if (EC)
  1394. return *this;
  1395. if (I != End) {
  1396. State->push(I);
  1397. return *this;
  1398. }
  1399. }
  1400. while (!State->empty() && State->top().increment(EC) == End)
  1401. State->pop();
  1402. if (State->empty())
  1403. State.reset(); // end iterator
  1404. return *this;
  1405. }