VirtualFileSystem.cpp 49 KB

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