VirtualFileSystem.cpp 64 KB

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