VirtualFileSystem.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  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(bool UseNormalizedPaths)
  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. UseNormalizedPaths(UseNormalizedPaths) {}
  425. InMemoryFileSystem::~InMemoryFileSystem() {}
  426. std::string InMemoryFileSystem::toString() const {
  427. return Root->toString(/*Indent=*/0);
  428. }
  429. bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
  430. std::unique_ptr<llvm::MemoryBuffer> Buffer) {
  431. SmallString<128> Path;
  432. P.toVector(Path);
  433. // Fix up relative paths. This just prepends the current working directory.
  434. std::error_code EC = makeAbsolute(Path);
  435. assert(!EC);
  436. (void)EC;
  437. if (useNormalizedPaths())
  438. FileManager::removeDotPaths(Path, /*RemoveDotDot=*/true);
  439. if (Path.empty())
  440. return false;
  441. detail::InMemoryDirectory *Dir = Root.get();
  442. auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
  443. while (true) {
  444. StringRef Name = *I;
  445. detail::InMemoryNode *Node = Dir->getChild(Name);
  446. ++I;
  447. if (!Node) {
  448. if (I == E) {
  449. // End of the path, create a new file.
  450. // FIXME: expose the status details in the interface.
  451. Status Stat(P.str(), getNextVirtualUniqueID(),
  452. llvm::sys::TimeValue(ModificationTime, 0), 0, 0,
  453. Buffer->getBufferSize(),
  454. llvm::sys::fs::file_type::regular_file,
  455. llvm::sys::fs::all_all);
  456. Dir->addChild(Name, llvm::make_unique<detail::InMemoryFile>(
  457. std::move(Stat), std::move(Buffer)));
  458. return true;
  459. }
  460. // Create a new directory. Use the path up to here.
  461. // FIXME: expose the status details in the interface.
  462. Status Stat(
  463. StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
  464. getNextVirtualUniqueID(), llvm::sys::TimeValue(ModificationTime, 0),
  465. 0, 0, Buffer->getBufferSize(),
  466. llvm::sys::fs::file_type::directory_file, llvm::sys::fs::all_all);
  467. Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
  468. Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
  469. continue;
  470. }
  471. if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
  472. Dir = NewDir;
  473. } else {
  474. assert(isa<detail::InMemoryFile>(Node) &&
  475. "Must be either file or directory!");
  476. // Trying to insert a directory in place of a file.
  477. if (I != E)
  478. return false;
  479. // Return false only if the new file is different from the existing one.
  480. return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
  481. Buffer->getBuffer();
  482. }
  483. }
  484. }
  485. bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
  486. llvm::MemoryBuffer *Buffer) {
  487. return addFile(P, ModificationTime,
  488. llvm::MemoryBuffer::getMemBuffer(
  489. Buffer->getBuffer(), Buffer->getBufferIdentifier()));
  490. }
  491. static ErrorOr<detail::InMemoryNode *>
  492. lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
  493. const Twine &P) {
  494. SmallString<128> Path;
  495. P.toVector(Path);
  496. // Fix up relative paths. This just prepends the current working directory.
  497. std::error_code EC = FS.makeAbsolute(Path);
  498. assert(!EC);
  499. (void)EC;
  500. if (FS.useNormalizedPaths())
  501. FileManager::removeDotPaths(Path, /*RemoveDotDot=*/true);
  502. if (Path.empty())
  503. return Dir;
  504. auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
  505. while (true) {
  506. detail::InMemoryNode *Node = Dir->getChild(*I);
  507. ++I;
  508. if (!Node)
  509. return errc::no_such_file_or_directory;
  510. // Return the file if it's at the end of the path.
  511. if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
  512. if (I == E)
  513. return File;
  514. return errc::no_such_file_or_directory;
  515. }
  516. // Traverse directories.
  517. Dir = cast<detail::InMemoryDirectory>(Node);
  518. if (I == E)
  519. return Dir;
  520. }
  521. }
  522. llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
  523. auto Node = lookupInMemoryNode(*this, Root.get(), Path);
  524. if (Node)
  525. return (*Node)->getStatus();
  526. return Node.getError();
  527. }
  528. llvm::ErrorOr<std::unique_ptr<File>>
  529. InMemoryFileSystem::openFileForRead(const Twine &Path) {
  530. auto Node = lookupInMemoryNode(*this, Root.get(), Path);
  531. if (!Node)
  532. return Node.getError();
  533. // When we have a file provide a heap-allocated wrapper for the memory buffer
  534. // to match the ownership semantics for File.
  535. if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
  536. return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
  537. // FIXME: errc::not_a_file?
  538. return make_error_code(llvm::errc::invalid_argument);
  539. }
  540. namespace {
  541. /// Adaptor from InMemoryDir::iterator to directory_iterator.
  542. class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
  543. detail::InMemoryDirectory::const_iterator I;
  544. detail::InMemoryDirectory::const_iterator E;
  545. public:
  546. InMemoryDirIterator() {}
  547. explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
  548. : I(Dir.begin()), E(Dir.end()) {
  549. if (I != E)
  550. CurrentEntry = I->second->getStatus();
  551. }
  552. std::error_code increment() override {
  553. ++I;
  554. // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
  555. // the rest.
  556. CurrentEntry = I != E ? I->second->getStatus() : Status();
  557. return std::error_code();
  558. }
  559. };
  560. } // end anonymous namespace
  561. directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
  562. std::error_code &EC) {
  563. auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
  564. if (!Node) {
  565. EC = Node.getError();
  566. return directory_iterator(std::make_shared<InMemoryDirIterator>());
  567. }
  568. if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
  569. return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
  570. EC = make_error_code(llvm::errc::not_a_directory);
  571. return directory_iterator(std::make_shared<InMemoryDirIterator>());
  572. }
  573. }
  574. }
  575. //===-----------------------------------------------------------------------===/
  576. // RedirectingFileSystem implementation
  577. //===-----------------------------------------------------------------------===/
  578. namespace {
  579. enum EntryKind {
  580. EK_Directory,
  581. EK_File
  582. };
  583. /// \brief A single file or directory in the VFS.
  584. class Entry {
  585. EntryKind Kind;
  586. std::string Name;
  587. public:
  588. virtual ~Entry();
  589. Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
  590. StringRef getName() const { return Name; }
  591. EntryKind getKind() const { return Kind; }
  592. };
  593. class RedirectingDirectoryEntry : public Entry {
  594. std::vector<std::unique_ptr<Entry>> Contents;
  595. Status S;
  596. public:
  597. RedirectingDirectoryEntry(StringRef Name,
  598. std::vector<std::unique_ptr<Entry>> Contents,
  599. Status S)
  600. : Entry(EK_Directory, Name), Contents(std::move(Contents)),
  601. S(std::move(S)) {}
  602. Status getStatus() { return S; }
  603. typedef decltype(Contents)::iterator iterator;
  604. iterator contents_begin() { return Contents.begin(); }
  605. iterator contents_end() { return Contents.end(); }
  606. static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
  607. };
  608. class RedirectingFileEntry : public Entry {
  609. public:
  610. enum NameKind {
  611. NK_NotSet,
  612. NK_External,
  613. NK_Virtual
  614. };
  615. private:
  616. std::string ExternalContentsPath;
  617. NameKind UseName;
  618. public:
  619. RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
  620. NameKind UseName)
  621. : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
  622. UseName(UseName) {}
  623. StringRef getExternalContentsPath() const { return ExternalContentsPath; }
  624. /// \brief whether to use the external path as the name for this file.
  625. bool useExternalName(bool GlobalUseExternalName) const {
  626. return UseName == NK_NotSet ? GlobalUseExternalName
  627. : (UseName == NK_External);
  628. }
  629. static bool classof(const Entry *E) { return E->getKind() == EK_File; }
  630. };
  631. class RedirectingFileSystem;
  632. class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
  633. std::string Dir;
  634. RedirectingFileSystem &FS;
  635. RedirectingDirectoryEntry::iterator Current, End;
  636. public:
  637. VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
  638. RedirectingDirectoryEntry::iterator Begin,
  639. RedirectingDirectoryEntry::iterator End,
  640. std::error_code &EC);
  641. std::error_code increment() override;
  642. };
  643. /// \brief A virtual file system parsed from a YAML file.
  644. ///
  645. /// Currently, this class allows creating virtual directories and mapping
  646. /// virtual file paths to existing external files, available in \c ExternalFS.
  647. ///
  648. /// The basic structure of the parsed file is:
  649. /// \verbatim
  650. /// {
  651. /// 'version': <version number>,
  652. /// <optional configuration>
  653. /// 'roots': [
  654. /// <directory entries>
  655. /// ]
  656. /// }
  657. /// \endverbatim
  658. ///
  659. /// All configuration options are optional.
  660. /// 'case-sensitive': <boolean, default=true>
  661. /// 'use-external-names': <boolean, default=true>
  662. ///
  663. /// Virtual directories are represented as
  664. /// \verbatim
  665. /// {
  666. /// 'type': 'directory',
  667. /// 'name': <string>,
  668. /// 'contents': [ <file or directory entries> ]
  669. /// }
  670. /// \endverbatim
  671. ///
  672. /// The default attributes for virtual directories are:
  673. /// \verbatim
  674. /// MTime = now() when created
  675. /// Perms = 0777
  676. /// User = Group = 0
  677. /// Size = 0
  678. /// UniqueID = unspecified unique value
  679. /// \endverbatim
  680. ///
  681. /// Re-mapped files are represented as
  682. /// \verbatim
  683. /// {
  684. /// 'type': 'file',
  685. /// 'name': <string>,
  686. /// 'use-external-name': <boolean> # Optional
  687. /// 'external-contents': <path to external file>)
  688. /// }
  689. /// \endverbatim
  690. ///
  691. /// and inherit their attributes from the external contents.
  692. ///
  693. /// In both cases, the 'name' field may contain multiple path components (e.g.
  694. /// /path/to/file). However, any directory that contains more than one child
  695. /// must be uniquely represented by a directory entry.
  696. class RedirectingFileSystem : public vfs::FileSystem {
  697. /// The root(s) of the virtual file system.
  698. std::vector<std::unique_ptr<Entry>> Roots;
  699. /// \brief The file system to use for external references.
  700. IntrusiveRefCntPtr<FileSystem> ExternalFS;
  701. /// @name Configuration
  702. /// @{
  703. /// \brief Whether to perform case-sensitive comparisons.
  704. ///
  705. /// Currently, case-insensitive matching only works correctly with ASCII.
  706. bool CaseSensitive;
  707. /// \brief Whether to use to use the value of 'external-contents' for the
  708. /// names of files. This global value is overridable on a per-file basis.
  709. bool UseExternalNames;
  710. /// @}
  711. friend class RedirectingFileSystemParser;
  712. private:
  713. RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
  714. : ExternalFS(ExternalFS), CaseSensitive(true), UseExternalNames(true) {}
  715. /// \brief Looks up \p Path in \c Roots.
  716. ErrorOr<Entry *> lookupPath(const Twine &Path);
  717. /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
  718. /// recursing into the contents of \p From if it is a directory.
  719. ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
  720. sys::path::const_iterator End, Entry *From);
  721. /// \brief Get the status of a given an \c Entry.
  722. ErrorOr<Status> status(const Twine &Path, Entry *E);
  723. public:
  724. /// \brief Parses \p Buffer, which is expected to be in YAML format and
  725. /// returns a virtual file system representing its contents.
  726. static RedirectingFileSystem *
  727. create(std::unique_ptr<MemoryBuffer> Buffer,
  728. SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext,
  729. IntrusiveRefCntPtr<FileSystem> ExternalFS);
  730. ErrorOr<Status> status(const Twine &Path) override;
  731. ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
  732. llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
  733. return ExternalFS->getCurrentWorkingDirectory();
  734. }
  735. std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
  736. return ExternalFS->setCurrentWorkingDirectory(Path);
  737. }
  738. directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
  739. ErrorOr<Entry *> E = lookupPath(Dir);
  740. if (!E) {
  741. EC = E.getError();
  742. return directory_iterator();
  743. }
  744. ErrorOr<Status> S = status(Dir, *E);
  745. if (!S) {
  746. EC = S.getError();
  747. return directory_iterator();
  748. }
  749. if (!S->isDirectory()) {
  750. EC = std::error_code(static_cast<int>(errc::not_a_directory),
  751. std::system_category());
  752. return directory_iterator();
  753. }
  754. auto *D = cast<RedirectingDirectoryEntry>(*E);
  755. return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
  756. *this, D->contents_begin(), D->contents_end(), EC));
  757. }
  758. };
  759. /// \brief A helper class to hold the common YAML parsing state.
  760. class RedirectingFileSystemParser {
  761. yaml::Stream &Stream;
  762. void error(yaml::Node *N, const Twine &Msg) {
  763. Stream.printError(N, Msg);
  764. }
  765. // false on error
  766. bool parseScalarString(yaml::Node *N, StringRef &Result,
  767. SmallVectorImpl<char> &Storage) {
  768. yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
  769. if (!S) {
  770. error(N, "expected string");
  771. return false;
  772. }
  773. Result = S->getValue(Storage);
  774. return true;
  775. }
  776. // false on error
  777. bool parseScalarBool(yaml::Node *N, bool &Result) {
  778. SmallString<5> Storage;
  779. StringRef Value;
  780. if (!parseScalarString(N, Value, Storage))
  781. return false;
  782. if (Value.equals_lower("true") || Value.equals_lower("on") ||
  783. Value.equals_lower("yes") || Value == "1") {
  784. Result = true;
  785. return true;
  786. } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
  787. Value.equals_lower("no") || Value == "0") {
  788. Result = false;
  789. return true;
  790. }
  791. error(N, "expected boolean value");
  792. return false;
  793. }
  794. struct KeyStatus {
  795. KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
  796. bool Required;
  797. bool Seen;
  798. };
  799. typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
  800. // false on error
  801. bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
  802. DenseMap<StringRef, KeyStatus> &Keys) {
  803. if (!Keys.count(Key)) {
  804. error(KeyNode, "unknown key");
  805. return false;
  806. }
  807. KeyStatus &S = Keys[Key];
  808. if (S.Seen) {
  809. error(KeyNode, Twine("duplicate key '") + Key + "'");
  810. return false;
  811. }
  812. S.Seen = true;
  813. return true;
  814. }
  815. // false on error
  816. bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
  817. for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
  818. E = Keys.end();
  819. I != E; ++I) {
  820. if (I->second.Required && !I->second.Seen) {
  821. error(Obj, Twine("missing key '") + I->first + "'");
  822. return false;
  823. }
  824. }
  825. return true;
  826. }
  827. std::unique_ptr<Entry> parseEntry(yaml::Node *N) {
  828. yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
  829. if (!M) {
  830. error(N, "expected mapping node for file or directory entry");
  831. return nullptr;
  832. }
  833. KeyStatusPair Fields[] = {
  834. KeyStatusPair("name", true),
  835. KeyStatusPair("type", true),
  836. KeyStatusPair("contents", false),
  837. KeyStatusPair("external-contents", false),
  838. KeyStatusPair("use-external-name", false),
  839. };
  840. DenseMap<StringRef, KeyStatus> Keys(
  841. &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
  842. bool HasContents = false; // external or otherwise
  843. std::vector<std::unique_ptr<Entry>> EntryArrayContents;
  844. std::string ExternalContentsPath;
  845. std::string Name;
  846. auto UseExternalName = RedirectingFileEntry::NK_NotSet;
  847. EntryKind Kind;
  848. for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
  849. ++I) {
  850. StringRef Key;
  851. // Reuse the buffer for key and value, since we don't look at key after
  852. // parsing value.
  853. SmallString<256> Buffer;
  854. if (!parseScalarString(I->getKey(), Key, Buffer))
  855. return nullptr;
  856. if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
  857. return nullptr;
  858. StringRef Value;
  859. if (Key == "name") {
  860. if (!parseScalarString(I->getValue(), Value, Buffer))
  861. return nullptr;
  862. Name = Value;
  863. } else if (Key == "type") {
  864. if (!parseScalarString(I->getValue(), Value, Buffer))
  865. return nullptr;
  866. if (Value == "file")
  867. Kind = EK_File;
  868. else if (Value == "directory")
  869. Kind = EK_Directory;
  870. else {
  871. error(I->getValue(), "unknown value for 'type'");
  872. return nullptr;
  873. }
  874. } else if (Key == "contents") {
  875. if (HasContents) {
  876. error(I->getKey(),
  877. "entry already has 'contents' or 'external-contents'");
  878. return nullptr;
  879. }
  880. HasContents = true;
  881. yaml::SequenceNode *Contents =
  882. dyn_cast<yaml::SequenceNode>(I->getValue());
  883. if (!Contents) {
  884. // FIXME: this is only for directories, what about files?
  885. error(I->getValue(), "expected array");
  886. return nullptr;
  887. }
  888. for (yaml::SequenceNode::iterator I = Contents->begin(),
  889. E = Contents->end();
  890. I != E; ++I) {
  891. if (std::unique_ptr<Entry> E = parseEntry(&*I))
  892. EntryArrayContents.push_back(std::move(E));
  893. else
  894. return nullptr;
  895. }
  896. } else if (Key == "external-contents") {
  897. if (HasContents) {
  898. error(I->getKey(),
  899. "entry already has 'contents' or 'external-contents'");
  900. return nullptr;
  901. }
  902. HasContents = true;
  903. if (!parseScalarString(I->getValue(), Value, Buffer))
  904. return nullptr;
  905. ExternalContentsPath = Value;
  906. } else if (Key == "use-external-name") {
  907. bool Val;
  908. if (!parseScalarBool(I->getValue(), Val))
  909. return nullptr;
  910. UseExternalName = Val ? RedirectingFileEntry::NK_External
  911. : RedirectingFileEntry::NK_Virtual;
  912. } else {
  913. llvm_unreachable("key missing from Keys");
  914. }
  915. }
  916. if (Stream.failed())
  917. return nullptr;
  918. // check for missing keys
  919. if (!HasContents) {
  920. error(N, "missing key 'contents' or 'external-contents'");
  921. return nullptr;
  922. }
  923. if (!checkMissingKeys(N, Keys))
  924. return nullptr;
  925. // check invalid configuration
  926. if (Kind == EK_Directory &&
  927. UseExternalName != RedirectingFileEntry::NK_NotSet) {
  928. error(N, "'use-external-name' is not supported for directories");
  929. return nullptr;
  930. }
  931. // Remove trailing slash(es), being careful not to remove the root path
  932. StringRef Trimmed(Name);
  933. size_t RootPathLen = sys::path::root_path(Trimmed).size();
  934. while (Trimmed.size() > RootPathLen &&
  935. sys::path::is_separator(Trimmed.back()))
  936. Trimmed = Trimmed.slice(0, Trimmed.size()-1);
  937. // Get the last component
  938. StringRef LastComponent = sys::path::filename(Trimmed);
  939. std::unique_ptr<Entry> Result;
  940. switch (Kind) {
  941. case EK_File:
  942. Result = llvm::make_unique<RedirectingFileEntry>(
  943. LastComponent, std::move(ExternalContentsPath), UseExternalName);
  944. break;
  945. case EK_Directory:
  946. Result = llvm::make_unique<RedirectingDirectoryEntry>(
  947. LastComponent, std::move(EntryArrayContents),
  948. Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
  949. file_type::directory_file, sys::fs::all_all));
  950. break;
  951. }
  952. StringRef Parent = sys::path::parent_path(Trimmed);
  953. if (Parent.empty())
  954. return Result;
  955. // if 'name' contains multiple components, create implicit directory entries
  956. for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
  957. E = sys::path::rend(Parent);
  958. I != E; ++I) {
  959. std::vector<std::unique_ptr<Entry>> Entries;
  960. Entries.push_back(std::move(Result));
  961. Result = llvm::make_unique<RedirectingDirectoryEntry>(
  962. *I, std::move(Entries),
  963. Status("", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0,
  964. file_type::directory_file, sys::fs::all_all));
  965. }
  966. return Result;
  967. }
  968. public:
  969. RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
  970. // false on error
  971. bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
  972. yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
  973. if (!Top) {
  974. error(Root, "expected mapping node");
  975. return false;
  976. }
  977. KeyStatusPair Fields[] = {
  978. KeyStatusPair("version", true),
  979. KeyStatusPair("case-sensitive", false),
  980. KeyStatusPair("use-external-names", false),
  981. KeyStatusPair("roots", true),
  982. };
  983. DenseMap<StringRef, KeyStatus> Keys(
  984. &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
  985. // Parse configuration and 'roots'
  986. for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
  987. ++I) {
  988. SmallString<10> KeyBuffer;
  989. StringRef Key;
  990. if (!parseScalarString(I->getKey(), Key, KeyBuffer))
  991. return false;
  992. if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
  993. return false;
  994. if (Key == "roots") {
  995. yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
  996. if (!Roots) {
  997. error(I->getValue(), "expected array");
  998. return false;
  999. }
  1000. for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
  1001. I != E; ++I) {
  1002. if (std::unique_ptr<Entry> E = parseEntry(&*I))
  1003. FS->Roots.push_back(std::move(E));
  1004. else
  1005. return false;
  1006. }
  1007. } else if (Key == "version") {
  1008. StringRef VersionString;
  1009. SmallString<4> Storage;
  1010. if (!parseScalarString(I->getValue(), VersionString, Storage))
  1011. return false;
  1012. int Version;
  1013. if (VersionString.getAsInteger<int>(10, Version)) {
  1014. error(I->getValue(), "expected integer");
  1015. return false;
  1016. }
  1017. if (Version < 0) {
  1018. error(I->getValue(), "invalid version number");
  1019. return false;
  1020. }
  1021. if (Version != 0) {
  1022. error(I->getValue(), "version mismatch, expected 0");
  1023. return false;
  1024. }
  1025. } else if (Key == "case-sensitive") {
  1026. if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
  1027. return false;
  1028. } else if (Key == "use-external-names") {
  1029. if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
  1030. return false;
  1031. } else {
  1032. llvm_unreachable("key missing from Keys");
  1033. }
  1034. }
  1035. if (Stream.failed())
  1036. return false;
  1037. if (!checkMissingKeys(Top, Keys))
  1038. return false;
  1039. return true;
  1040. }
  1041. };
  1042. } // end of anonymous namespace
  1043. Entry::~Entry() = default;
  1044. RedirectingFileSystem *RedirectingFileSystem::create(
  1045. std::unique_ptr<MemoryBuffer> Buffer, SourceMgr::DiagHandlerTy DiagHandler,
  1046. void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS) {
  1047. SourceMgr SM;
  1048. yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
  1049. SM.setDiagHandler(DiagHandler, DiagContext);
  1050. yaml::document_iterator DI = Stream.begin();
  1051. yaml::Node *Root = DI->getRoot();
  1052. if (DI == Stream.end() || !Root) {
  1053. SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
  1054. return nullptr;
  1055. }
  1056. RedirectingFileSystemParser P(Stream);
  1057. std::unique_ptr<RedirectingFileSystem> FS(
  1058. new RedirectingFileSystem(ExternalFS));
  1059. if (!P.parse(Root, FS.get()))
  1060. return nullptr;
  1061. return FS.release();
  1062. }
  1063. ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
  1064. SmallString<256> Path;
  1065. Path_.toVector(Path);
  1066. // Handle relative paths
  1067. if (std::error_code EC = makeAbsolute(Path))
  1068. return EC;
  1069. if (Path.empty())
  1070. return make_error_code(llvm::errc::invalid_argument);
  1071. sys::path::const_iterator Start = sys::path::begin(Path);
  1072. sys::path::const_iterator End = sys::path::end(Path);
  1073. for (const std::unique_ptr<Entry> &Root : Roots) {
  1074. ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
  1075. if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
  1076. return Result;
  1077. }
  1078. return make_error_code(llvm::errc::no_such_file_or_directory);
  1079. }
  1080. ErrorOr<Entry *>
  1081. RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
  1082. sys::path::const_iterator End, Entry *From) {
  1083. if (Start->equals("."))
  1084. ++Start;
  1085. // FIXME: handle ..
  1086. if (CaseSensitive ? !Start->equals(From->getName())
  1087. : !Start->equals_lower(From->getName()))
  1088. // failure to match
  1089. return make_error_code(llvm::errc::no_such_file_or_directory);
  1090. ++Start;
  1091. if (Start == End) {
  1092. // Match!
  1093. return From;
  1094. }
  1095. auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
  1096. if (!DE)
  1097. return make_error_code(llvm::errc::not_a_directory);
  1098. for (const std::unique_ptr<Entry> &DirEntry :
  1099. llvm::make_range(DE->contents_begin(), DE->contents_end())) {
  1100. ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
  1101. if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
  1102. return Result;
  1103. }
  1104. return make_error_code(llvm::errc::no_such_file_or_directory);
  1105. }
  1106. ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
  1107. assert(E != nullptr);
  1108. std::string PathStr(Path.str());
  1109. if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
  1110. ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
  1111. assert(!S || S->getName() == F->getExternalContentsPath());
  1112. if (S && !F->useExternalName(UseExternalNames))
  1113. *S = Status::copyWithNewName(*S, PathStr);
  1114. if (S)
  1115. S->IsVFSMapped = true;
  1116. return S;
  1117. } else { // directory
  1118. auto *DE = cast<RedirectingDirectoryEntry>(E);
  1119. return Status::copyWithNewName(DE->getStatus(), PathStr);
  1120. }
  1121. }
  1122. ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
  1123. ErrorOr<Entry *> Result = lookupPath(Path);
  1124. if (!Result)
  1125. return Result.getError();
  1126. return status(Path, *Result);
  1127. }
  1128. namespace {
  1129. /// Provide a file wrapper that returns the external name when asked.
  1130. class NamedFileAdaptor : public File {
  1131. std::unique_ptr<File> InnerFile;
  1132. std::string NewName;
  1133. public:
  1134. NamedFileAdaptor(std::unique_ptr<File> InnerFile, std::string NewName)
  1135. : InnerFile(std::move(InnerFile)), NewName(std::move(NewName)) {}
  1136. llvm::ErrorOr<Status> status() override {
  1137. auto InnerStatus = InnerFile->status();
  1138. if (InnerStatus)
  1139. return Status::copyWithNewName(*InnerStatus, NewName);
  1140. return InnerStatus.getError();
  1141. }
  1142. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
  1143. getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
  1144. bool IsVolatile) override {
  1145. return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
  1146. IsVolatile);
  1147. }
  1148. std::error_code close() override { return InnerFile->close(); }
  1149. };
  1150. } // end anonymous namespace
  1151. ErrorOr<std::unique_ptr<File>>
  1152. RedirectingFileSystem::openFileForRead(const Twine &Path) {
  1153. ErrorOr<Entry *> E = lookupPath(Path);
  1154. if (!E)
  1155. return E.getError();
  1156. auto *F = dyn_cast<RedirectingFileEntry>(*E);
  1157. if (!F) // FIXME: errc::not_a_file?
  1158. return make_error_code(llvm::errc::invalid_argument);
  1159. auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
  1160. if (!Result)
  1161. return Result;
  1162. if (!F->useExternalName(UseExternalNames))
  1163. return std::unique_ptr<File>(
  1164. new NamedFileAdaptor(std::move(*Result), Path.str()));
  1165. return Result;
  1166. }
  1167. IntrusiveRefCntPtr<FileSystem>
  1168. vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
  1169. SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext,
  1170. IntrusiveRefCntPtr<FileSystem> ExternalFS) {
  1171. return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
  1172. DiagContext, ExternalFS);
  1173. }
  1174. UniqueID vfs::getNextVirtualUniqueID() {
  1175. static std::atomic<unsigned> UID;
  1176. unsigned ID = ++UID;
  1177. // The following assumes that uint64_t max will never collide with a real
  1178. // dev_t value from the OS.
  1179. return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
  1180. }
  1181. #ifndef NDEBUG
  1182. static bool pathHasTraversal(StringRef Path) {
  1183. using namespace llvm::sys;
  1184. for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
  1185. if (Comp == "." || Comp == "..")
  1186. return true;
  1187. return false;
  1188. }
  1189. #endif
  1190. void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
  1191. assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
  1192. assert(sys::path::is_absolute(RealPath) && "real path not absolute");
  1193. assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
  1194. Mappings.emplace_back(VirtualPath, RealPath);
  1195. }
  1196. namespace {
  1197. class JSONWriter {
  1198. llvm::raw_ostream &OS;
  1199. SmallVector<StringRef, 16> DirStack;
  1200. inline unsigned getDirIndent() { return 4 * DirStack.size(); }
  1201. inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
  1202. bool containedIn(StringRef Parent, StringRef Path);
  1203. StringRef containedPart(StringRef Parent, StringRef Path);
  1204. void startDirectory(StringRef Path);
  1205. void endDirectory();
  1206. void writeEntry(StringRef VPath, StringRef RPath);
  1207. public:
  1208. JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
  1209. void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive);
  1210. };
  1211. }
  1212. bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
  1213. using namespace llvm::sys;
  1214. // Compare each path component.
  1215. auto IParent = path::begin(Parent), EParent = path::end(Parent);
  1216. for (auto IChild = path::begin(Path), EChild = path::end(Path);
  1217. IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
  1218. if (*IParent != *IChild)
  1219. return false;
  1220. }
  1221. // Have we exhausted the parent path?
  1222. return IParent == EParent;
  1223. }
  1224. StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
  1225. assert(!Parent.empty());
  1226. assert(containedIn(Parent, Path));
  1227. return Path.slice(Parent.size() + 1, StringRef::npos);
  1228. }
  1229. void JSONWriter::startDirectory(StringRef Path) {
  1230. StringRef Name =
  1231. DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
  1232. DirStack.push_back(Path);
  1233. unsigned Indent = getDirIndent();
  1234. OS.indent(Indent) << "{\n";
  1235. OS.indent(Indent + 2) << "'type': 'directory',\n";
  1236. OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
  1237. OS.indent(Indent + 2) << "'contents': [\n";
  1238. }
  1239. void JSONWriter::endDirectory() {
  1240. unsigned Indent = getDirIndent();
  1241. OS.indent(Indent + 2) << "]\n";
  1242. OS.indent(Indent) << "}";
  1243. DirStack.pop_back();
  1244. }
  1245. void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
  1246. unsigned Indent = getFileIndent();
  1247. OS.indent(Indent) << "{\n";
  1248. OS.indent(Indent + 2) << "'type': 'file',\n";
  1249. OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
  1250. OS.indent(Indent + 2) << "'external-contents': \""
  1251. << llvm::yaml::escape(RPath) << "\"\n";
  1252. OS.indent(Indent) << "}";
  1253. }
  1254. void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
  1255. Optional<bool> IsCaseSensitive) {
  1256. using namespace llvm::sys;
  1257. OS << "{\n"
  1258. " 'version': 0,\n";
  1259. if (IsCaseSensitive.hasValue())
  1260. OS << " 'case-sensitive': '"
  1261. << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
  1262. OS << " 'roots': [\n";
  1263. if (!Entries.empty()) {
  1264. const YAMLVFSEntry &Entry = Entries.front();
  1265. startDirectory(path::parent_path(Entry.VPath));
  1266. writeEntry(path::filename(Entry.VPath), Entry.RPath);
  1267. for (const auto &Entry : Entries.slice(1)) {
  1268. StringRef Dir = path::parent_path(Entry.VPath);
  1269. if (Dir == DirStack.back())
  1270. OS << ",\n";
  1271. else {
  1272. while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
  1273. OS << "\n";
  1274. endDirectory();
  1275. }
  1276. OS << ",\n";
  1277. startDirectory(Dir);
  1278. }
  1279. writeEntry(path::filename(Entry.VPath), Entry.RPath);
  1280. }
  1281. while (!DirStack.empty()) {
  1282. OS << "\n";
  1283. endDirectory();
  1284. }
  1285. OS << "\n";
  1286. }
  1287. OS << " ]\n"
  1288. << "}\n";
  1289. }
  1290. void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
  1291. std::sort(Mappings.begin(), Mappings.end(),
  1292. [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
  1293. return LHS.VPath < RHS.VPath;
  1294. });
  1295. JSONWriter(OS).write(Mappings, IsCaseSensitive);
  1296. }
  1297. VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
  1298. const Twine &_Path, RedirectingFileSystem &FS,
  1299. RedirectingDirectoryEntry::iterator Begin,
  1300. RedirectingDirectoryEntry::iterator End, std::error_code &EC)
  1301. : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
  1302. if (Current != End) {
  1303. SmallString<128> PathStr(Dir);
  1304. llvm::sys::path::append(PathStr, (*Current)->getName());
  1305. llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
  1306. if (S)
  1307. CurrentEntry = *S;
  1308. else
  1309. EC = S.getError();
  1310. }
  1311. }
  1312. std::error_code VFSFromYamlDirIterImpl::increment() {
  1313. assert(Current != End && "cannot iterate past end");
  1314. if (++Current != End) {
  1315. SmallString<128> PathStr(Dir);
  1316. llvm::sys::path::append(PathStr, (*Current)->getName());
  1317. llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
  1318. if (!S)
  1319. return S.getError();
  1320. CurrentEntry = *S;
  1321. } else {
  1322. CurrentEntry = Status();
  1323. }
  1324. return std::error_code();
  1325. }
  1326. vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
  1327. const Twine &Path,
  1328. std::error_code &EC)
  1329. : FS(&FS_) {
  1330. directory_iterator I = FS->dir_begin(Path, EC);
  1331. if (!EC && I != directory_iterator()) {
  1332. State = std::make_shared<IterState>();
  1333. State->push(I);
  1334. }
  1335. }
  1336. vfs::recursive_directory_iterator &
  1337. recursive_directory_iterator::increment(std::error_code &EC) {
  1338. assert(FS && State && !State->empty() && "incrementing past end");
  1339. assert(State->top()->isStatusKnown() && "non-canonical end iterator");
  1340. vfs::directory_iterator End;
  1341. if (State->top()->isDirectory()) {
  1342. vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
  1343. if (EC)
  1344. return *this;
  1345. if (I != End) {
  1346. State->push(I);
  1347. return *this;
  1348. }
  1349. }
  1350. while (!State->empty() && State->top().increment(EC) == End)
  1351. State->pop();
  1352. if (State->empty())
  1353. State.reset(); // end iterator
  1354. return *this;
  1355. }