VirtualFileSystem.cpp 52 KB

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