1 //===- VirtualFileSystem.cpp - Virtual File System Layer ------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the VirtualFileSystem interface. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Support/VirtualFileSystem.h" 14 #include "llvm/ADT/ArrayRef.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/IntrusiveRefCntPtr.h" 17 #include "llvm/ADT/None.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/Casting.h" 28 #include "llvm/Support/Chrono.h" 29 #include "llvm/Support/Compiler.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/FileSystem/UniqueID.h" 36 #include "llvm/Support/MemoryBuffer.h" 37 #include "llvm/Support/Path.h" 38 #include "llvm/Support/Process.h" 39 #include "llvm/Support/SMLoc.h" 40 #include "llvm/Support/SourceMgr.h" 41 #include "llvm/Support/YAMLParser.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include <algorithm> 44 #include <atomic> 45 #include <cassert> 46 #include <cstdint> 47 #include <iterator> 48 #include <limits> 49 #include <map> 50 #include <memory> 51 #include <mutex> 52 #include <string> 53 #include <system_error> 54 #include <utility> 55 #include <vector> 56 57 using namespace llvm; 58 using namespace llvm::vfs; 59 60 using llvm::sys::fs::file_t; 61 using llvm::sys::fs::file_status; 62 using llvm::sys::fs::file_type; 63 using llvm::sys::fs::kInvalidFile; 64 using llvm::sys::fs::perms; 65 using llvm::sys::fs::UniqueID; 66 67 Status::Status(const file_status &Status) 68 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()), 69 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()), 70 Type(Status.type()), Perms(Status.permissions()) {} 71 72 Status::Status(const Twine &Name, UniqueID UID, sys::TimePoint<> MTime, 73 uint32_t User, uint32_t Group, uint64_t Size, file_type Type, 74 perms Perms) 75 : Name(Name.str()), UID(UID), MTime(MTime), User(User), Group(Group), 76 Size(Size), Type(Type), Perms(Perms) {} 77 78 Status Status::copyWithNewSize(const Status &In, uint64_t NewSize) { 79 return Status(In.getName(), In.getUniqueID(), In.getLastModificationTime(), 80 In.getUser(), In.getGroup(), NewSize, In.getType(), 81 In.getPermissions()); 82 } 83 84 Status Status::copyWithNewName(const Status &In, const Twine &NewName) { 85 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(), 86 In.getUser(), In.getGroup(), In.getSize(), In.getType(), 87 In.getPermissions()); 88 } 89 90 Status Status::copyWithNewName(const file_status &In, const Twine &NewName) { 91 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(), 92 In.getUser(), In.getGroup(), In.getSize(), In.type(), 93 In.permissions()); 94 } 95 96 bool Status::equivalent(const Status &Other) const { 97 assert(isStatusKnown() && Other.isStatusKnown()); 98 return getUniqueID() == Other.getUniqueID(); 99 } 100 101 bool Status::isDirectory() const { return Type == file_type::directory_file; } 102 103 bool Status::isRegularFile() const { return Type == file_type::regular_file; } 104 105 bool Status::isOther() const { 106 return exists() && !isRegularFile() && !isDirectory() && !isSymlink(); 107 } 108 109 bool Status::isSymlink() const { return Type == file_type::symlink_file; } 110 111 bool Status::isStatusKnown() const { return Type != file_type::status_error; } 112 113 bool Status::exists() const { 114 return isStatusKnown() && Type != file_type::file_not_found; 115 } 116 117 File::~File() = default; 118 119 FileSystem::~FileSystem() = default; 120 121 ErrorOr<std::unique_ptr<MemoryBuffer>> 122 FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize, 123 bool RequiresNullTerminator, bool IsVolatile) { 124 auto F = openFileForRead(Name); 125 if (!F) 126 return F.getError(); 127 128 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile); 129 } 130 131 std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const { 132 if (llvm::sys::path::is_absolute(Path)) 133 return {}; 134 135 auto WorkingDir = getCurrentWorkingDirectory(); 136 if (!WorkingDir) 137 return WorkingDir.getError(); 138 139 llvm::sys::fs::make_absolute(WorkingDir.get(), Path); 140 return {}; 141 } 142 143 std::error_code FileSystem::getRealPath(const Twine &Path, 144 SmallVectorImpl<char> &Output) const { 145 return errc::operation_not_permitted; 146 } 147 148 std::error_code FileSystem::isLocal(const Twine &Path, bool &Result) { 149 return errc::operation_not_permitted; 150 } 151 152 bool FileSystem::exists(const Twine &Path) { 153 auto Status = status(Path); 154 return Status && Status->exists(); 155 } 156 157 #ifndef NDEBUG 158 static bool isTraversalComponent(StringRef Component) { 159 return Component.equals("..") || Component.equals("."); 160 } 161 162 static bool pathHasTraversal(StringRef Path) { 163 using namespace llvm::sys; 164 165 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path))) 166 if (isTraversalComponent(Comp)) 167 return true; 168 return false; 169 } 170 #endif 171 172 //===-----------------------------------------------------------------------===/ 173 // RealFileSystem implementation 174 //===-----------------------------------------------------------------------===/ 175 176 namespace { 177 178 /// Wrapper around a raw file descriptor. 179 class RealFile : public File { 180 friend class RealFileSystem; 181 182 file_t FD; 183 Status S; 184 std::string RealName; 185 186 RealFile(file_t RawFD, StringRef NewName, StringRef NewRealPathName) 187 : FD(RawFD), S(NewName, {}, {}, {}, {}, {}, 188 llvm::sys::fs::file_type::status_error, {}), 189 RealName(NewRealPathName.str()) { 190 assert(FD != kInvalidFile && "Invalid or inactive file descriptor"); 191 } 192 193 public: 194 ~RealFile() override; 195 196 ErrorOr<Status> status() override; 197 ErrorOr<std::string> getName() override; 198 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name, 199 int64_t FileSize, 200 bool RequiresNullTerminator, 201 bool IsVolatile) override; 202 std::error_code close() override; 203 void setPath(const Twine &Path) override; 204 }; 205 206 } // namespace 207 208 RealFile::~RealFile() { close(); } 209 210 ErrorOr<Status> RealFile::status() { 211 assert(FD != kInvalidFile && "cannot stat closed file"); 212 if (!S.isStatusKnown()) { 213 file_status RealStatus; 214 if (std::error_code EC = sys::fs::status(FD, RealStatus)) 215 return EC; 216 S = Status::copyWithNewName(RealStatus, S.getName()); 217 } 218 return S; 219 } 220 221 ErrorOr<std::string> RealFile::getName() { 222 return RealName.empty() ? S.getName().str() : RealName; 223 } 224 225 ErrorOr<std::unique_ptr<MemoryBuffer>> 226 RealFile::getBuffer(const Twine &Name, int64_t FileSize, 227 bool RequiresNullTerminator, bool IsVolatile) { 228 assert(FD != kInvalidFile && "cannot get buffer for closed file"); 229 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator, 230 IsVolatile); 231 } 232 233 std::error_code RealFile::close() { 234 std::error_code EC = sys::fs::closeFile(FD); 235 FD = kInvalidFile; 236 return EC; 237 } 238 239 void RealFile::setPath(const Twine &Path) { 240 RealName = Path.str(); 241 if (auto Status = status()) 242 S = Status.get().copyWithNewName(Status.get(), Path); 243 } 244 245 namespace { 246 247 /// A file system according to your operating system. 248 /// This may be linked to the process's working directory, or maintain its own. 249 /// 250 /// Currently, its own working directory is emulated by storing the path and 251 /// sending absolute paths to llvm::sys::fs:: functions. 252 /// A more principled approach would be to push this down a level, modelling 253 /// the working dir as an llvm::sys::fs::WorkingDir or similar. 254 /// This would enable the use of openat()-style functions on some platforms. 255 class RealFileSystem : public FileSystem { 256 public: 257 explicit RealFileSystem(bool LinkCWDToProcess) { 258 if (!LinkCWDToProcess) { 259 SmallString<128> PWD, RealPWD; 260 if (llvm::sys::fs::current_path(PWD)) 261 return; // Awful, but nothing to do here. 262 if (llvm::sys::fs::real_path(PWD, RealPWD)) 263 WD = {PWD, PWD}; 264 else 265 WD = {PWD, RealPWD}; 266 } 267 } 268 269 ErrorOr<Status> status(const Twine &Path) override; 270 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override; 271 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override; 272 273 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override; 274 std::error_code setCurrentWorkingDirectory(const Twine &Path) override; 275 std::error_code isLocal(const Twine &Path, bool &Result) override; 276 std::error_code getRealPath(const Twine &Path, 277 SmallVectorImpl<char> &Output) const override; 278 279 private: 280 // If this FS has its own working dir, use it to make Path absolute. 281 // The returned twine is safe to use as long as both Storage and Path live. 282 Twine adjustPath(const Twine &Path, SmallVectorImpl<char> &Storage) const { 283 if (!WD) 284 return Path; 285 Path.toVector(Storage); 286 sys::fs::make_absolute(WD->Resolved, Storage); 287 return Storage; 288 } 289 290 struct WorkingDirectory { 291 // The current working directory, without symlinks resolved. (echo $PWD). 292 SmallString<128> Specified; 293 // The current working directory, with links resolved. (readlink .). 294 SmallString<128> Resolved; 295 }; 296 Optional<WorkingDirectory> WD; 297 }; 298 299 } // namespace 300 301 ErrorOr<Status> RealFileSystem::status(const Twine &Path) { 302 SmallString<256> Storage; 303 sys::fs::file_status RealStatus; 304 if (std::error_code EC = 305 sys::fs::status(adjustPath(Path, Storage), RealStatus)) 306 return EC; 307 return Status::copyWithNewName(RealStatus, Path); 308 } 309 310 ErrorOr<std::unique_ptr<File>> 311 RealFileSystem::openFileForRead(const Twine &Name) { 312 SmallString<256> RealName, Storage; 313 Expected<file_t> FDOrErr = sys::fs::openNativeFileForRead( 314 adjustPath(Name, Storage), sys::fs::OF_None, &RealName); 315 if (!FDOrErr) 316 return errorToErrorCode(FDOrErr.takeError()); 317 return std::unique_ptr<File>( 318 new RealFile(*FDOrErr, Name.str(), RealName.str())); 319 } 320 321 llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const { 322 if (WD) 323 return std::string(WD->Specified.str()); 324 325 SmallString<128> Dir; 326 if (std::error_code EC = llvm::sys::fs::current_path(Dir)) 327 return EC; 328 return std::string(Dir.str()); 329 } 330 331 std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) { 332 if (!WD) 333 return llvm::sys::fs::set_current_path(Path); 334 335 SmallString<128> Absolute, Resolved, Storage; 336 adjustPath(Path, Storage).toVector(Absolute); 337 bool IsDir; 338 if (auto Err = llvm::sys::fs::is_directory(Absolute, IsDir)) 339 return Err; 340 if (!IsDir) 341 return std::make_error_code(std::errc::not_a_directory); 342 if (auto Err = llvm::sys::fs::real_path(Absolute, Resolved)) 343 return Err; 344 WD = {Absolute, Resolved}; 345 return std::error_code(); 346 } 347 348 std::error_code RealFileSystem::isLocal(const Twine &Path, bool &Result) { 349 SmallString<256> Storage; 350 return llvm::sys::fs::is_local(adjustPath(Path, Storage), Result); 351 } 352 353 std::error_code 354 RealFileSystem::getRealPath(const Twine &Path, 355 SmallVectorImpl<char> &Output) const { 356 SmallString<256> Storage; 357 return llvm::sys::fs::real_path(adjustPath(Path, Storage), Output); 358 } 359 360 IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() { 361 static IntrusiveRefCntPtr<FileSystem> FS(new RealFileSystem(true)); 362 return FS; 363 } 364 365 std::unique_ptr<FileSystem> vfs::createPhysicalFileSystem() { 366 return std::make_unique<RealFileSystem>(false); 367 } 368 369 namespace { 370 371 class RealFSDirIter : public llvm::vfs::detail::DirIterImpl { 372 llvm::sys::fs::directory_iterator Iter; 373 374 public: 375 RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) { 376 if (Iter != llvm::sys::fs::directory_iterator()) 377 CurrentEntry = directory_entry(Iter->path(), Iter->type()); 378 } 379 380 std::error_code increment() override { 381 std::error_code EC; 382 Iter.increment(EC); 383 CurrentEntry = (Iter == llvm::sys::fs::directory_iterator()) 384 ? directory_entry() 385 : directory_entry(Iter->path(), Iter->type()); 386 return EC; 387 } 388 }; 389 390 } // namespace 391 392 directory_iterator RealFileSystem::dir_begin(const Twine &Dir, 393 std::error_code &EC) { 394 SmallString<128> Storage; 395 return directory_iterator( 396 std::make_shared<RealFSDirIter>(adjustPath(Dir, Storage), EC)); 397 } 398 399 //===-----------------------------------------------------------------------===/ 400 // OverlayFileSystem implementation 401 //===-----------------------------------------------------------------------===/ 402 403 OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) { 404 FSList.push_back(std::move(BaseFS)); 405 } 406 407 void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) { 408 FSList.push_back(FS); 409 // Synchronize added file systems by duplicating the working directory from 410 // the first one in the list. 411 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get()); 412 } 413 414 ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) { 415 // FIXME: handle symlinks that cross file systems 416 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) { 417 ErrorOr<Status> Status = (*I)->status(Path); 418 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory) 419 return Status; 420 } 421 return make_error_code(llvm::errc::no_such_file_or_directory); 422 } 423 424 ErrorOr<std::unique_ptr<File>> 425 OverlayFileSystem::openFileForRead(const llvm::Twine &Path) { 426 // FIXME: handle symlinks that cross file systems 427 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) { 428 auto Result = (*I)->openFileForRead(Path); 429 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory) 430 return Result; 431 } 432 return make_error_code(llvm::errc::no_such_file_or_directory); 433 } 434 435 llvm::ErrorOr<std::string> 436 OverlayFileSystem::getCurrentWorkingDirectory() const { 437 // All file systems are synchronized, just take the first working directory. 438 return FSList.front()->getCurrentWorkingDirectory(); 439 } 440 441 std::error_code 442 OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) { 443 for (auto &FS : FSList) 444 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path)) 445 return EC; 446 return {}; 447 } 448 449 std::error_code OverlayFileSystem::isLocal(const Twine &Path, bool &Result) { 450 for (auto &FS : FSList) 451 if (FS->exists(Path)) 452 return FS->isLocal(Path, Result); 453 return errc::no_such_file_or_directory; 454 } 455 456 std::error_code 457 OverlayFileSystem::getRealPath(const Twine &Path, 458 SmallVectorImpl<char> &Output) const { 459 for (const auto &FS : FSList) 460 if (FS->exists(Path)) 461 return FS->getRealPath(Path, Output); 462 return errc::no_such_file_or_directory; 463 } 464 465 llvm::vfs::detail::DirIterImpl::~DirIterImpl() = default; 466 467 namespace { 468 469 /// Combines and deduplicates directory entries across multiple file systems. 470 class CombiningDirIterImpl : public llvm::vfs::detail::DirIterImpl { 471 using FileSystemPtr = llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>; 472 473 /// File systems to check for entries in. Processed in reverse order. 474 SmallVector<FileSystemPtr, 8> FSList; 475 /// The directory iterator for the current filesystem. 476 directory_iterator CurrentDirIter; 477 /// The path of the directory to iterate the entries of. 478 std::string DirPath; 479 /// The set of names already returned as entries. 480 llvm::StringSet<> SeenNames; 481 482 /// Sets \c CurrentDirIter to an iterator of \c DirPath in the next file 483 /// system in the list, or leaves it as is (at its end position) if we've 484 /// already gone through them all. 485 std::error_code incrementFS() { 486 while (!FSList.empty()) { 487 std::error_code EC; 488 CurrentDirIter = FSList.back()->dir_begin(DirPath, EC); 489 FSList.pop_back(); 490 if (EC && EC != errc::no_such_file_or_directory) 491 return EC; 492 if (CurrentDirIter != directory_iterator()) 493 break; // found 494 } 495 return {}; 496 } 497 498 std::error_code incrementDirIter(bool IsFirstTime) { 499 assert((IsFirstTime || CurrentDirIter != directory_iterator()) && 500 "incrementing past end"); 501 std::error_code EC; 502 if (!IsFirstTime) 503 CurrentDirIter.increment(EC); 504 if (!EC && CurrentDirIter == directory_iterator()) 505 EC = incrementFS(); 506 return EC; 507 } 508 509 std::error_code incrementImpl(bool IsFirstTime) { 510 while (true) { 511 std::error_code EC = incrementDirIter(IsFirstTime); 512 if (EC || CurrentDirIter == directory_iterator()) { 513 CurrentEntry = directory_entry(); 514 return EC; 515 } 516 CurrentEntry = *CurrentDirIter; 517 StringRef Name = llvm::sys::path::filename(CurrentEntry.path()); 518 if (SeenNames.insert(Name).second) 519 return EC; // name not seen before 520 } 521 llvm_unreachable("returned above"); 522 } 523 524 public: 525 CombiningDirIterImpl(ArrayRef<FileSystemPtr> FileSystems, std::string Dir, 526 std::error_code &EC) 527 : FSList(FileSystems.begin(), FileSystems.end()), 528 DirPath(std::move(Dir)) { 529 if (!FSList.empty()) { 530 CurrentDirIter = FSList.back()->dir_begin(DirPath, EC); 531 FSList.pop_back(); 532 if (!EC || EC == errc::no_such_file_or_directory) 533 EC = incrementImpl(true); 534 } 535 } 536 537 CombiningDirIterImpl(directory_iterator FirstIter, FileSystemPtr Fallback, 538 std::string FallbackDir, std::error_code &EC) 539 : FSList({Fallback}), CurrentDirIter(FirstIter), 540 DirPath(std::move(FallbackDir)) { 541 if (!EC || EC == errc::no_such_file_or_directory) 542 EC = incrementImpl(true); 543 } 544 545 std::error_code increment() override { return incrementImpl(false); } 546 }; 547 548 } // namespace 549 550 directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir, 551 std::error_code &EC) { 552 return directory_iterator( 553 std::make_shared<CombiningDirIterImpl>(FSList, Dir.str(), EC)); 554 } 555 556 void ProxyFileSystem::anchor() {} 557 558 namespace llvm { 559 namespace vfs { 560 561 namespace detail { 562 563 enum InMemoryNodeKind { IME_File, IME_Directory, IME_HardLink }; 564 565 /// The in memory file system is a tree of Nodes. Every node can either be a 566 /// file , hardlink or a directory. 567 class InMemoryNode { 568 InMemoryNodeKind Kind; 569 std::string FileName; 570 571 public: 572 InMemoryNode(llvm::StringRef FileName, InMemoryNodeKind Kind) 573 : Kind(Kind), FileName(std::string(llvm::sys::path::filename(FileName))) { 574 } 575 virtual ~InMemoryNode() = default; 576 577 /// Return the \p Status for this node. \p RequestedName should be the name 578 /// through which the caller referred to this node. It will override 579 /// \p Status::Name in the return value, to mimic the behavior of \p RealFile. 580 virtual Status getStatus(const Twine &RequestedName) const = 0; 581 582 /// Get the filename of this node (the name without the directory part). 583 StringRef getFileName() const { return FileName; } 584 InMemoryNodeKind getKind() const { return Kind; } 585 virtual std::string toString(unsigned Indent) const = 0; 586 }; 587 588 class InMemoryFile : public InMemoryNode { 589 Status Stat; 590 std::unique_ptr<llvm::MemoryBuffer> Buffer; 591 592 public: 593 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer) 594 : InMemoryNode(Stat.getName(), IME_File), Stat(std::move(Stat)), 595 Buffer(std::move(Buffer)) {} 596 597 Status getStatus(const Twine &RequestedName) const override { 598 return Status::copyWithNewName(Stat, RequestedName); 599 } 600 llvm::MemoryBuffer *getBuffer() const { return Buffer.get(); } 601 602 std::string toString(unsigned Indent) const override { 603 return (std::string(Indent, ' ') + Stat.getName() + "\n").str(); 604 } 605 606 static bool classof(const InMemoryNode *N) { 607 return N->getKind() == IME_File; 608 } 609 }; 610 611 namespace { 612 613 class InMemoryHardLink : public InMemoryNode { 614 const InMemoryFile &ResolvedFile; 615 616 public: 617 InMemoryHardLink(StringRef Path, const InMemoryFile &ResolvedFile) 618 : InMemoryNode(Path, IME_HardLink), ResolvedFile(ResolvedFile) {} 619 const InMemoryFile &getResolvedFile() const { return ResolvedFile; } 620 621 Status getStatus(const Twine &RequestedName) const override { 622 return ResolvedFile.getStatus(RequestedName); 623 } 624 625 std::string toString(unsigned Indent) const override { 626 return std::string(Indent, ' ') + "HardLink to -> " + 627 ResolvedFile.toString(0); 628 } 629 630 static bool classof(const InMemoryNode *N) { 631 return N->getKind() == IME_HardLink; 632 } 633 }; 634 635 /// Adapt a InMemoryFile for VFS' File interface. The goal is to make 636 /// \p InMemoryFileAdaptor mimic as much as possible the behavior of 637 /// \p RealFile. 638 class InMemoryFileAdaptor : public File { 639 const InMemoryFile &Node; 640 /// The name to use when returning a Status for this file. 641 std::string RequestedName; 642 643 public: 644 explicit InMemoryFileAdaptor(const InMemoryFile &Node, 645 std::string RequestedName) 646 : Node(Node), RequestedName(std::move(RequestedName)) {} 647 648 llvm::ErrorOr<Status> status() override { 649 return Node.getStatus(RequestedName); 650 } 651 652 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 653 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator, 654 bool IsVolatile) override { 655 llvm::MemoryBuffer *Buf = Node.getBuffer(); 656 return llvm::MemoryBuffer::getMemBuffer( 657 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator); 658 } 659 660 std::error_code close() override { return {}; } 661 662 void setPath(const Twine &Path) override { RequestedName = Path.str(); } 663 }; 664 } // namespace 665 666 class InMemoryDirectory : public InMemoryNode { 667 Status Stat; 668 llvm::StringMap<std::unique_ptr<InMemoryNode>> Entries; 669 670 public: 671 InMemoryDirectory(Status Stat) 672 : InMemoryNode(Stat.getName(), IME_Directory), Stat(std::move(Stat)) {} 673 674 /// Return the \p Status for this node. \p RequestedName should be the name 675 /// through which the caller referred to this node. It will override 676 /// \p Status::Name in the return value, to mimic the behavior of \p RealFile. 677 Status getStatus(const Twine &RequestedName) const override { 678 return Status::copyWithNewName(Stat, RequestedName); 679 } 680 681 UniqueID getUniqueID() const { return Stat.getUniqueID(); } 682 683 InMemoryNode *getChild(StringRef Name) { 684 auto I = Entries.find(Name); 685 if (I != Entries.end()) 686 return I->second.get(); 687 return nullptr; 688 } 689 690 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) { 691 return Entries.insert(make_pair(Name, std::move(Child))) 692 .first->second.get(); 693 } 694 695 using const_iterator = decltype(Entries)::const_iterator; 696 697 const_iterator begin() const { return Entries.begin(); } 698 const_iterator end() const { return Entries.end(); } 699 700 std::string toString(unsigned Indent) const override { 701 std::string Result = 702 (std::string(Indent, ' ') + Stat.getName() + "\n").str(); 703 for (const auto &Entry : Entries) 704 Result += Entry.second->toString(Indent + 2); 705 return Result; 706 } 707 708 static bool classof(const InMemoryNode *N) { 709 return N->getKind() == IME_Directory; 710 } 711 }; 712 713 } // namespace detail 714 715 // The UniqueID of in-memory files is derived from path and content. 716 // This avoids difficulties in creating exactly equivalent in-memory FSes, 717 // as often needed in multithreaded programs. 718 static sys::fs::UniqueID getUniqueID(hash_code Hash) { 719 return sys::fs::UniqueID(std::numeric_limits<uint64_t>::max(), 720 uint64_t(size_t(Hash))); 721 } 722 static sys::fs::UniqueID getFileID(sys::fs::UniqueID Parent, 723 llvm::StringRef Name, 724 llvm::StringRef Contents) { 725 return getUniqueID(llvm::hash_combine(Parent.getFile(), Name, Contents)); 726 } 727 static sys::fs::UniqueID getDirectoryID(sys::fs::UniqueID Parent, 728 llvm::StringRef Name) { 729 return getUniqueID(llvm::hash_combine(Parent.getFile(), Name)); 730 } 731 732 Status detail::NewInMemoryNodeInfo::makeStatus() const { 733 UniqueID UID = 734 (Type == sys::fs::file_type::directory_file) 735 ? getDirectoryID(DirUID, Name) 736 : getFileID(DirUID, Name, Buffer ? Buffer->getBuffer() : ""); 737 738 return Status(Path, UID, llvm::sys::toTimePoint(ModificationTime), User, 739 Group, Buffer ? Buffer->getBufferSize() : 0, Type, Perms); 740 } 741 742 InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths) 743 : Root(new detail::InMemoryDirectory( 744 Status("", getDirectoryID(llvm::sys::fs::UniqueID(), ""), 745 llvm::sys::TimePoint<>(), 0, 0, 0, 746 llvm::sys::fs::file_type::directory_file, 747 llvm::sys::fs::perms::all_all))), 748 UseNormalizedPaths(UseNormalizedPaths) {} 749 750 InMemoryFileSystem::~InMemoryFileSystem() = default; 751 752 std::string InMemoryFileSystem::toString() const { 753 return Root->toString(/*Indent=*/0); 754 } 755 756 bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime, 757 std::unique_ptr<llvm::MemoryBuffer> Buffer, 758 Optional<uint32_t> User, 759 Optional<uint32_t> Group, 760 Optional<llvm::sys::fs::file_type> Type, 761 Optional<llvm::sys::fs::perms> Perms, 762 MakeNodeFn MakeNode) { 763 SmallString<128> Path; 764 P.toVector(Path); 765 766 // Fix up relative paths. This just prepends the current working directory. 767 std::error_code EC = makeAbsolute(Path); 768 assert(!EC); 769 (void)EC; 770 771 if (useNormalizedPaths()) 772 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true); 773 774 if (Path.empty()) 775 return false; 776 777 detail::InMemoryDirectory *Dir = Root.get(); 778 auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path); 779 const auto ResolvedUser = User.getValueOr(0); 780 const auto ResolvedGroup = Group.getValueOr(0); 781 const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file); 782 const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all); 783 // Any intermediate directories we create should be accessible by 784 // the owner, even if Perms says otherwise for the final path. 785 const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all; 786 while (true) { 787 StringRef Name = *I; 788 detail::InMemoryNode *Node = Dir->getChild(Name); 789 ++I; 790 if (!Node) { 791 if (I == E) { 792 // End of the path. 793 Dir->addChild( 794 Name, MakeNode({Dir->getUniqueID(), Path, Name, ModificationTime, 795 std::move(Buffer), ResolvedUser, ResolvedGroup, 796 ResolvedType, ResolvedPerms})); 797 return true; 798 } 799 800 // Create a new directory. Use the path up to here. 801 Status Stat( 802 StringRef(Path.str().begin(), Name.end() - Path.str().begin()), 803 getDirectoryID(Dir->getUniqueID(), Name), 804 llvm::sys::toTimePoint(ModificationTime), ResolvedUser, ResolvedGroup, 805 0, sys::fs::file_type::directory_file, NewDirectoryPerms); 806 Dir = cast<detail::InMemoryDirectory>(Dir->addChild( 807 Name, std::make_unique<detail::InMemoryDirectory>(std::move(Stat)))); 808 continue; 809 } 810 811 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) { 812 Dir = NewDir; 813 } else { 814 assert((isa<detail::InMemoryFile>(Node) || 815 isa<detail::InMemoryHardLink>(Node)) && 816 "Must be either file, hardlink or directory!"); 817 818 // Trying to insert a directory in place of a file. 819 if (I != E) 820 return false; 821 822 // Return false only if the new file is different from the existing one. 823 if (auto Link = dyn_cast<detail::InMemoryHardLink>(Node)) { 824 return Link->getResolvedFile().getBuffer()->getBuffer() == 825 Buffer->getBuffer(); 826 } 827 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() == 828 Buffer->getBuffer(); 829 } 830 } 831 } 832 833 bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime, 834 std::unique_ptr<llvm::MemoryBuffer> Buffer, 835 Optional<uint32_t> User, 836 Optional<uint32_t> Group, 837 Optional<llvm::sys::fs::file_type> Type, 838 Optional<llvm::sys::fs::perms> Perms) { 839 return addFile(P, ModificationTime, std::move(Buffer), User, Group, Type, 840 Perms, 841 [](detail::NewInMemoryNodeInfo NNI) 842 -> std::unique_ptr<detail::InMemoryNode> { 843 Status Stat = NNI.makeStatus(); 844 if (Stat.getType() == sys::fs::file_type::directory_file) 845 return std::make_unique<detail::InMemoryDirectory>(Stat); 846 return std::make_unique<detail::InMemoryFile>( 847 Stat, std::move(NNI.Buffer)); 848 }); 849 } 850 851 bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime, 852 const llvm::MemoryBufferRef &Buffer, 853 Optional<uint32_t> User, 854 Optional<uint32_t> Group, 855 Optional<llvm::sys::fs::file_type> Type, 856 Optional<llvm::sys::fs::perms> Perms) { 857 return addFile(P, ModificationTime, llvm::MemoryBuffer::getMemBuffer(Buffer), 858 std::move(User), std::move(Group), std::move(Type), 859 std::move(Perms), 860 [](detail::NewInMemoryNodeInfo NNI) 861 -> std::unique_ptr<detail::InMemoryNode> { 862 Status Stat = NNI.makeStatus(); 863 if (Stat.getType() == sys::fs::file_type::directory_file) 864 return std::make_unique<detail::InMemoryDirectory>(Stat); 865 return std::make_unique<detail::InMemoryFile>( 866 Stat, std::move(NNI.Buffer)); 867 }); 868 } 869 870 static ErrorOr<const detail::InMemoryNode *> 871 lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir, 872 const Twine &P) { 873 SmallString<128> Path; 874 P.toVector(Path); 875 876 // Fix up relative paths. This just prepends the current working directory. 877 std::error_code EC = FS.makeAbsolute(Path); 878 assert(!EC); 879 (void)EC; 880 881 if (FS.useNormalizedPaths()) 882 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true); 883 884 if (Path.empty()) 885 return Dir; 886 887 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path); 888 while (true) { 889 detail::InMemoryNode *Node = Dir->getChild(*I); 890 ++I; 891 if (!Node) 892 return errc::no_such_file_or_directory; 893 894 // Return the file if it's at the end of the path. 895 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) { 896 if (I == E) 897 return File; 898 return errc::no_such_file_or_directory; 899 } 900 901 // If Node is HardLink then return the resolved file. 902 if (auto File = dyn_cast<detail::InMemoryHardLink>(Node)) { 903 if (I == E) 904 return &File->getResolvedFile(); 905 return errc::no_such_file_or_directory; 906 } 907 // Traverse directories. 908 Dir = cast<detail::InMemoryDirectory>(Node); 909 if (I == E) 910 return Dir; 911 } 912 } 913 914 bool InMemoryFileSystem::addHardLink(const Twine &FromPath, 915 const Twine &ToPath) { 916 auto FromNode = lookupInMemoryNode(*this, Root.get(), FromPath); 917 auto ToNode = lookupInMemoryNode(*this, Root.get(), ToPath); 918 // FromPath must not have been added before. ToPath must have been added 919 // before. Resolved ToPath must be a File. 920 if (!ToNode || FromNode || !isa<detail::InMemoryFile>(*ToNode)) 921 return false; 922 return addFile(FromPath, 0, nullptr, None, None, None, None, 923 [&](detail::NewInMemoryNodeInfo NNI) { 924 return std::make_unique<detail::InMemoryHardLink>( 925 NNI.Path.str(), *cast<detail::InMemoryFile>(*ToNode)); 926 }); 927 } 928 929 llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) { 930 auto Node = lookupInMemoryNode(*this, Root.get(), Path); 931 if (Node) 932 return (*Node)->getStatus(Path); 933 return Node.getError(); 934 } 935 936 llvm::ErrorOr<std::unique_ptr<File>> 937 InMemoryFileSystem::openFileForRead(const Twine &Path) { 938 auto Node = lookupInMemoryNode(*this, Root.get(), Path); 939 if (!Node) 940 return Node.getError(); 941 942 // When we have a file provide a heap-allocated wrapper for the memory buffer 943 // to match the ownership semantics for File. 944 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node)) 945 return std::unique_ptr<File>( 946 new detail::InMemoryFileAdaptor(*F, Path.str())); 947 948 // FIXME: errc::not_a_file? 949 return make_error_code(llvm::errc::invalid_argument); 950 } 951 952 namespace { 953 954 /// Adaptor from InMemoryDir::iterator to directory_iterator. 955 class InMemoryDirIterator : public llvm::vfs::detail::DirIterImpl { 956 detail::InMemoryDirectory::const_iterator I; 957 detail::InMemoryDirectory::const_iterator E; 958 std::string RequestedDirName; 959 960 void setCurrentEntry() { 961 if (I != E) { 962 SmallString<256> Path(RequestedDirName); 963 llvm::sys::path::append(Path, I->second->getFileName()); 964 sys::fs::file_type Type = sys::fs::file_type::type_unknown; 965 switch (I->second->getKind()) { 966 case detail::IME_File: 967 case detail::IME_HardLink: 968 Type = sys::fs::file_type::regular_file; 969 break; 970 case detail::IME_Directory: 971 Type = sys::fs::file_type::directory_file; 972 break; 973 } 974 CurrentEntry = directory_entry(std::string(Path.str()), Type); 975 } else { 976 // When we're at the end, make CurrentEntry invalid and DirIterImpl will 977 // do the rest. 978 CurrentEntry = directory_entry(); 979 } 980 } 981 982 public: 983 InMemoryDirIterator() = default; 984 985 explicit InMemoryDirIterator(const detail::InMemoryDirectory &Dir, 986 std::string RequestedDirName) 987 : I(Dir.begin()), E(Dir.end()), 988 RequestedDirName(std::move(RequestedDirName)) { 989 setCurrentEntry(); 990 } 991 992 std::error_code increment() override { 993 ++I; 994 setCurrentEntry(); 995 return {}; 996 } 997 }; 998 999 } // namespace 1000 1001 directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir, 1002 std::error_code &EC) { 1003 auto Node = lookupInMemoryNode(*this, Root.get(), Dir); 1004 if (!Node) { 1005 EC = Node.getError(); 1006 return directory_iterator(std::make_shared<InMemoryDirIterator>()); 1007 } 1008 1009 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node)) 1010 return directory_iterator( 1011 std::make_shared<InMemoryDirIterator>(*DirNode, Dir.str())); 1012 1013 EC = make_error_code(llvm::errc::not_a_directory); 1014 return directory_iterator(std::make_shared<InMemoryDirIterator>()); 1015 } 1016 1017 std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) { 1018 SmallString<128> Path; 1019 P.toVector(Path); 1020 1021 // Fix up relative paths. This just prepends the current working directory. 1022 std::error_code EC = makeAbsolute(Path); 1023 assert(!EC); 1024 (void)EC; 1025 1026 if (useNormalizedPaths()) 1027 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true); 1028 1029 if (!Path.empty()) 1030 WorkingDirectory = std::string(Path.str()); 1031 return {}; 1032 } 1033 1034 std::error_code 1035 InMemoryFileSystem::getRealPath(const Twine &Path, 1036 SmallVectorImpl<char> &Output) const { 1037 auto CWD = getCurrentWorkingDirectory(); 1038 if (!CWD || CWD->empty()) 1039 return errc::operation_not_permitted; 1040 Path.toVector(Output); 1041 if (auto EC = makeAbsolute(Output)) 1042 return EC; 1043 llvm::sys::path::remove_dots(Output, /*remove_dot_dot=*/true); 1044 return {}; 1045 } 1046 1047 std::error_code InMemoryFileSystem::isLocal(const Twine &Path, bool &Result) { 1048 Result = false; 1049 return {}; 1050 } 1051 1052 } // namespace vfs 1053 } // namespace llvm 1054 1055 //===-----------------------------------------------------------------------===/ 1056 // RedirectingFileSystem implementation 1057 //===-----------------------------------------------------------------------===/ 1058 1059 namespace { 1060 1061 static llvm::sys::path::Style getExistingStyle(llvm::StringRef Path) { 1062 // Detect the path style in use by checking the first separator. 1063 llvm::sys::path::Style style = llvm::sys::path::Style::native; 1064 const size_t n = Path.find_first_of("/\\"); 1065 // Can't distinguish between posix and windows_slash here. 1066 if (n != static_cast<size_t>(-1)) 1067 style = (Path[n] == '/') ? llvm::sys::path::Style::posix 1068 : llvm::sys::path::Style::windows_backslash; 1069 return style; 1070 } 1071 1072 /// Removes leading "./" as well as path components like ".." and ".". 1073 static llvm::SmallString<256> canonicalize(llvm::StringRef Path) { 1074 // First detect the path style in use by checking the first separator. 1075 llvm::sys::path::Style style = getExistingStyle(Path); 1076 1077 // Now remove the dots. Explicitly specifying the path style prevents the 1078 // direction of the slashes from changing. 1079 llvm::SmallString<256> result = 1080 llvm::sys::path::remove_leading_dotslash(Path, style); 1081 llvm::sys::path::remove_dots(result, /*remove_dot_dot=*/true, style); 1082 return result; 1083 } 1084 1085 } // anonymous namespace 1086 1087 1088 RedirectingFileSystem::RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> FS) 1089 : ExternalFS(std::move(FS)) { 1090 if (ExternalFS) 1091 if (auto ExternalWorkingDirectory = 1092 ExternalFS->getCurrentWorkingDirectory()) { 1093 WorkingDirectory = *ExternalWorkingDirectory; 1094 } 1095 } 1096 1097 /// Directory iterator implementation for \c RedirectingFileSystem's 1098 /// directory entries. 1099 class llvm::vfs::RedirectingFSDirIterImpl 1100 : public llvm::vfs::detail::DirIterImpl { 1101 std::string Dir; 1102 RedirectingFileSystem::DirectoryEntry::iterator Current, End; 1103 1104 std::error_code incrementImpl(bool IsFirstTime) { 1105 assert((IsFirstTime || Current != End) && "cannot iterate past end"); 1106 if (!IsFirstTime) 1107 ++Current; 1108 if (Current != End) { 1109 SmallString<128> PathStr(Dir); 1110 llvm::sys::path::append(PathStr, (*Current)->getName()); 1111 sys::fs::file_type Type = sys::fs::file_type::type_unknown; 1112 switch ((*Current)->getKind()) { 1113 case RedirectingFileSystem::EK_Directory: 1114 LLVM_FALLTHROUGH; 1115 case RedirectingFileSystem::EK_DirectoryRemap: 1116 Type = sys::fs::file_type::directory_file; 1117 break; 1118 case RedirectingFileSystem::EK_File: 1119 Type = sys::fs::file_type::regular_file; 1120 break; 1121 } 1122 CurrentEntry = directory_entry(std::string(PathStr.str()), Type); 1123 } else { 1124 CurrentEntry = directory_entry(); 1125 } 1126 return {}; 1127 }; 1128 1129 public: 1130 RedirectingFSDirIterImpl( 1131 const Twine &Path, RedirectingFileSystem::DirectoryEntry::iterator Begin, 1132 RedirectingFileSystem::DirectoryEntry::iterator End, std::error_code &EC) 1133 : Dir(Path.str()), Current(Begin), End(End) { 1134 EC = incrementImpl(/*IsFirstTime=*/true); 1135 } 1136 1137 std::error_code increment() override { 1138 return incrementImpl(/*IsFirstTime=*/false); 1139 } 1140 }; 1141 1142 namespace { 1143 /// Directory iterator implementation for \c RedirectingFileSystem's 1144 /// directory remap entries that maps the paths reported by the external 1145 /// file system's directory iterator back to the virtual directory's path. 1146 class RedirectingFSDirRemapIterImpl : public llvm::vfs::detail::DirIterImpl { 1147 std::string Dir; 1148 llvm::sys::path::Style DirStyle; 1149 llvm::vfs::directory_iterator ExternalIter; 1150 1151 public: 1152 RedirectingFSDirRemapIterImpl(std::string DirPath, 1153 llvm::vfs::directory_iterator ExtIter) 1154 : Dir(std::move(DirPath)), DirStyle(getExistingStyle(Dir)), 1155 ExternalIter(ExtIter) { 1156 if (ExternalIter != llvm::vfs::directory_iterator()) 1157 setCurrentEntry(); 1158 } 1159 1160 void setCurrentEntry() { 1161 StringRef ExternalPath = ExternalIter->path(); 1162 llvm::sys::path::Style ExternalStyle = getExistingStyle(ExternalPath); 1163 StringRef File = llvm::sys::path::filename(ExternalPath, ExternalStyle); 1164 1165 SmallString<128> NewPath(Dir); 1166 llvm::sys::path::append(NewPath, DirStyle, File); 1167 1168 CurrentEntry = directory_entry(std::string(NewPath), ExternalIter->type()); 1169 } 1170 1171 std::error_code increment() override { 1172 std::error_code EC; 1173 ExternalIter.increment(EC); 1174 if (!EC && ExternalIter != llvm::vfs::directory_iterator()) 1175 setCurrentEntry(); 1176 else 1177 CurrentEntry = directory_entry(); 1178 return EC; 1179 } 1180 }; 1181 } // namespace 1182 1183 llvm::ErrorOr<std::string> 1184 RedirectingFileSystem::getCurrentWorkingDirectory() const { 1185 return WorkingDirectory; 1186 } 1187 1188 std::error_code 1189 RedirectingFileSystem::setCurrentWorkingDirectory(const Twine &Path) { 1190 // Don't change the working directory if the path doesn't exist. 1191 if (!exists(Path)) 1192 return errc::no_such_file_or_directory; 1193 1194 SmallString<128> AbsolutePath; 1195 Path.toVector(AbsolutePath); 1196 if (std::error_code EC = makeAbsolute(AbsolutePath)) 1197 return EC; 1198 WorkingDirectory = std::string(AbsolutePath.str()); 1199 return {}; 1200 } 1201 1202 std::error_code RedirectingFileSystem::isLocal(const Twine &Path_, 1203 bool &Result) { 1204 SmallString<256> Path; 1205 Path_.toVector(Path); 1206 1207 if (std::error_code EC = makeCanonical(Path)) 1208 return {}; 1209 1210 return ExternalFS->isLocal(Path, Result); 1211 } 1212 1213 std::error_code RedirectingFileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const { 1214 // is_absolute(..., Style::windows_*) accepts paths with both slash types. 1215 if (llvm::sys::path::is_absolute(Path, llvm::sys::path::Style::posix) || 1216 llvm::sys::path::is_absolute(Path, 1217 llvm::sys::path::Style::windows_backslash)) 1218 return {}; 1219 1220 auto WorkingDir = getCurrentWorkingDirectory(); 1221 if (!WorkingDir) 1222 return WorkingDir.getError(); 1223 1224 // We can't use sys::fs::make_absolute because that assumes the path style 1225 // is native and there is no way to override that. Since we know WorkingDir 1226 // is absolute, we can use it to determine which style we actually have and 1227 // append Path ourselves. 1228 sys::path::Style style = sys::path::Style::windows_backslash; 1229 if (sys::path::is_absolute(WorkingDir.get(), sys::path::Style::posix)) { 1230 style = sys::path::Style::posix; 1231 } else { 1232 // Distinguish between windows_backslash and windows_slash; getExistingStyle 1233 // returns posix for a path with windows_slash. 1234 if (getExistingStyle(WorkingDir.get()) != 1235 sys::path::Style::windows_backslash) 1236 style = sys::path::Style::windows_slash; 1237 } 1238 1239 std::string Result = WorkingDir.get(); 1240 StringRef Dir(Result); 1241 if (!Dir.endswith(sys::path::get_separator(style))) { 1242 Result += sys::path::get_separator(style); 1243 } 1244 Result.append(Path.data(), Path.size()); 1245 Path.assign(Result.begin(), Result.end()); 1246 1247 return {}; 1248 } 1249 1250 directory_iterator RedirectingFileSystem::dir_begin(const Twine &Dir, 1251 std::error_code &EC) { 1252 SmallString<256> Path; 1253 Dir.toVector(Path); 1254 1255 EC = makeCanonical(Path); 1256 if (EC) 1257 return {}; 1258 1259 ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path); 1260 if (!Result) { 1261 EC = Result.getError(); 1262 if (shouldFallBackToExternalFS(EC)) 1263 return ExternalFS->dir_begin(Path, EC); 1264 return {}; 1265 } 1266 1267 // Use status to make sure the path exists and refers to a directory. 1268 ErrorOr<Status> S = status(Path, Dir, *Result); 1269 if (!S) { 1270 if (shouldFallBackToExternalFS(S.getError(), Result->E)) 1271 return ExternalFS->dir_begin(Dir, EC); 1272 EC = S.getError(); 1273 return {}; 1274 } 1275 if (!S->isDirectory()) { 1276 EC = std::error_code(static_cast<int>(errc::not_a_directory), 1277 std::system_category()); 1278 return {}; 1279 } 1280 1281 // Create the appropriate directory iterator based on whether we found a 1282 // DirectoryRemapEntry or DirectoryEntry. 1283 directory_iterator DirIter; 1284 if (auto ExtRedirect = Result->getExternalRedirect()) { 1285 auto RE = cast<RedirectingFileSystem::RemapEntry>(Result->E); 1286 DirIter = ExternalFS->dir_begin(*ExtRedirect, EC); 1287 1288 if (!RE->useExternalName(UseExternalNames)) { 1289 // Update the paths in the results to use the virtual directory's path. 1290 DirIter = 1291 directory_iterator(std::make_shared<RedirectingFSDirRemapIterImpl>( 1292 std::string(Path), DirIter)); 1293 } 1294 } else { 1295 auto DE = cast<DirectoryEntry>(Result->E); 1296 DirIter = directory_iterator(std::make_shared<RedirectingFSDirIterImpl>( 1297 Path, DE->contents_begin(), DE->contents_end(), EC)); 1298 } 1299 1300 if (!shouldUseExternalFS()) 1301 return DirIter; 1302 return directory_iterator(std::make_shared<CombiningDirIterImpl>( 1303 DirIter, ExternalFS, std::string(Path), EC)); 1304 } 1305 1306 void RedirectingFileSystem::setExternalContentsPrefixDir(StringRef PrefixDir) { 1307 ExternalContentsPrefixDir = PrefixDir.str(); 1308 } 1309 1310 StringRef RedirectingFileSystem::getExternalContentsPrefixDir() const { 1311 return ExternalContentsPrefixDir; 1312 } 1313 1314 void RedirectingFileSystem::setFallthrough(bool Fallthrough) { 1315 IsFallthrough = Fallthrough; 1316 } 1317 1318 std::vector<StringRef> RedirectingFileSystem::getRoots() const { 1319 std::vector<StringRef> R; 1320 for (const auto &Root : Roots) 1321 R.push_back(Root->getName()); 1322 return R; 1323 } 1324 1325 void RedirectingFileSystem::dump(raw_ostream &OS) const { 1326 for (const auto &Root : Roots) 1327 dumpEntry(OS, Root.get()); 1328 } 1329 1330 void RedirectingFileSystem::dumpEntry(raw_ostream &OS, 1331 RedirectingFileSystem::Entry *E, 1332 int NumSpaces) const { 1333 StringRef Name = E->getName(); 1334 for (int i = 0, e = NumSpaces; i < e; ++i) 1335 OS << " "; 1336 OS << "'" << Name.str().c_str() << "'" 1337 << "\n"; 1338 1339 if (E->getKind() == RedirectingFileSystem::EK_Directory) { 1340 auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(E); 1341 assert(DE && "Should be a directory"); 1342 1343 for (std::unique_ptr<Entry> &SubEntry : 1344 llvm::make_range(DE->contents_begin(), DE->contents_end())) 1345 dumpEntry(OS, SubEntry.get(), NumSpaces + 2); 1346 } 1347 } 1348 1349 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1350 LLVM_DUMP_METHOD void RedirectingFileSystem::dump() const { dump(dbgs()); } 1351 #endif 1352 1353 /// A helper class to hold the common YAML parsing state. 1354 class llvm::vfs::RedirectingFileSystemParser { 1355 yaml::Stream &Stream; 1356 1357 void error(yaml::Node *N, const Twine &Msg) { Stream.printError(N, Msg); } 1358 1359 // false on error 1360 bool parseScalarString(yaml::Node *N, StringRef &Result, 1361 SmallVectorImpl<char> &Storage) { 1362 const auto *S = dyn_cast<yaml::ScalarNode>(N); 1363 1364 if (!S) { 1365 error(N, "expected string"); 1366 return false; 1367 } 1368 Result = S->getValue(Storage); 1369 return true; 1370 } 1371 1372 // false on error 1373 bool parseScalarBool(yaml::Node *N, bool &Result) { 1374 SmallString<5> Storage; 1375 StringRef Value; 1376 if (!parseScalarString(N, Value, Storage)) 1377 return false; 1378 1379 if (Value.equals_insensitive("true") || Value.equals_insensitive("on") || 1380 Value.equals_insensitive("yes") || Value == "1") { 1381 Result = true; 1382 return true; 1383 } else if (Value.equals_insensitive("false") || 1384 Value.equals_insensitive("off") || 1385 Value.equals_insensitive("no") || Value == "0") { 1386 Result = false; 1387 return true; 1388 } 1389 1390 error(N, "expected boolean value"); 1391 return false; 1392 } 1393 1394 struct KeyStatus { 1395 bool Required; 1396 bool Seen = false; 1397 1398 KeyStatus(bool Required = false) : Required(Required) {} 1399 }; 1400 1401 using KeyStatusPair = std::pair<StringRef, KeyStatus>; 1402 1403 // false on error 1404 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key, 1405 DenseMap<StringRef, KeyStatus> &Keys) { 1406 if (!Keys.count(Key)) { 1407 error(KeyNode, "unknown key"); 1408 return false; 1409 } 1410 KeyStatus &S = Keys[Key]; 1411 if (S.Seen) { 1412 error(KeyNode, Twine("duplicate key '") + Key + "'"); 1413 return false; 1414 } 1415 S.Seen = true; 1416 return true; 1417 } 1418 1419 // false on error 1420 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) { 1421 for (const auto &I : Keys) { 1422 if (I.second.Required && !I.second.Seen) { 1423 error(Obj, Twine("missing key '") + I.first + "'"); 1424 return false; 1425 } 1426 } 1427 return true; 1428 } 1429 1430 public: 1431 static RedirectingFileSystem::Entry * 1432 lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name, 1433 RedirectingFileSystem::Entry *ParentEntry = nullptr) { 1434 if (!ParentEntry) { // Look for a existent root 1435 for (const auto &Root : FS->Roots) { 1436 if (Name.equals(Root->getName())) { 1437 ParentEntry = Root.get(); 1438 return ParentEntry; 1439 } 1440 } 1441 } else { // Advance to the next component 1442 auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(ParentEntry); 1443 for (std::unique_ptr<RedirectingFileSystem::Entry> &Content : 1444 llvm::make_range(DE->contents_begin(), DE->contents_end())) { 1445 auto *DirContent = 1446 dyn_cast<RedirectingFileSystem::DirectoryEntry>(Content.get()); 1447 if (DirContent && Name.equals(Content->getName())) 1448 return DirContent; 1449 } 1450 } 1451 1452 // ... or create a new one 1453 std::unique_ptr<RedirectingFileSystem::Entry> E = 1454 std::make_unique<RedirectingFileSystem::DirectoryEntry>( 1455 Name, Status("", getNextVirtualUniqueID(), 1456 std::chrono::system_clock::now(), 0, 0, 0, 1457 file_type::directory_file, sys::fs::all_all)); 1458 1459 if (!ParentEntry) { // Add a new root to the overlay 1460 FS->Roots.push_back(std::move(E)); 1461 ParentEntry = FS->Roots.back().get(); 1462 return ParentEntry; 1463 } 1464 1465 auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(ParentEntry); 1466 DE->addContent(std::move(E)); 1467 return DE->getLastContent(); 1468 } 1469 1470 private: 1471 void uniqueOverlayTree(RedirectingFileSystem *FS, 1472 RedirectingFileSystem::Entry *SrcE, 1473 RedirectingFileSystem::Entry *NewParentE = nullptr) { 1474 StringRef Name = SrcE->getName(); 1475 switch (SrcE->getKind()) { 1476 case RedirectingFileSystem::EK_Directory: { 1477 auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(SrcE); 1478 // Empty directories could be present in the YAML as a way to 1479 // describe a file for a current directory after some of its subdir 1480 // is parsed. This only leads to redundant walks, ignore it. 1481 if (!Name.empty()) 1482 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE); 1483 for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry : 1484 llvm::make_range(DE->contents_begin(), DE->contents_end())) 1485 uniqueOverlayTree(FS, SubEntry.get(), NewParentE); 1486 break; 1487 } 1488 case RedirectingFileSystem::EK_DirectoryRemap: { 1489 assert(NewParentE && "Parent entry must exist"); 1490 auto *DR = cast<RedirectingFileSystem::DirectoryRemapEntry>(SrcE); 1491 auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(NewParentE); 1492 DE->addContent( 1493 std::make_unique<RedirectingFileSystem::DirectoryRemapEntry>( 1494 Name, DR->getExternalContentsPath(), DR->getUseName())); 1495 break; 1496 } 1497 case RedirectingFileSystem::EK_File: { 1498 assert(NewParentE && "Parent entry must exist"); 1499 auto *FE = cast<RedirectingFileSystem::FileEntry>(SrcE); 1500 auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(NewParentE); 1501 DE->addContent(std::make_unique<RedirectingFileSystem::FileEntry>( 1502 Name, FE->getExternalContentsPath(), FE->getUseName())); 1503 break; 1504 } 1505 } 1506 } 1507 1508 std::unique_ptr<RedirectingFileSystem::Entry> 1509 parseEntry(yaml::Node *N, RedirectingFileSystem *FS, bool IsRootEntry) { 1510 auto *M = dyn_cast<yaml::MappingNode>(N); 1511 if (!M) { 1512 error(N, "expected mapping node for file or directory entry"); 1513 return nullptr; 1514 } 1515 1516 KeyStatusPair Fields[] = { 1517 KeyStatusPair("name", true), 1518 KeyStatusPair("type", true), 1519 KeyStatusPair("contents", false), 1520 KeyStatusPair("external-contents", false), 1521 KeyStatusPair("use-external-name", false), 1522 }; 1523 1524 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields)); 1525 1526 enum { CF_NotSet, CF_List, CF_External } ContentsField = CF_NotSet; 1527 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> 1528 EntryArrayContents; 1529 SmallString<256> ExternalContentsPath; 1530 SmallString<256> Name; 1531 yaml::Node *NameValueNode = nullptr; 1532 auto UseExternalName = RedirectingFileSystem::NK_NotSet; 1533 RedirectingFileSystem::EntryKind Kind; 1534 1535 for (auto &I : *M) { 1536 StringRef Key; 1537 // Reuse the buffer for key and value, since we don't look at key after 1538 // parsing value. 1539 SmallString<256> Buffer; 1540 if (!parseScalarString(I.getKey(), Key, Buffer)) 1541 return nullptr; 1542 1543 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys)) 1544 return nullptr; 1545 1546 StringRef Value; 1547 if (Key == "name") { 1548 if (!parseScalarString(I.getValue(), Value, Buffer)) 1549 return nullptr; 1550 1551 NameValueNode = I.getValue(); 1552 // Guarantee that old YAML files containing paths with ".." and "." 1553 // are properly canonicalized before read into the VFS. 1554 Name = canonicalize(Value).str(); 1555 } else if (Key == "type") { 1556 if (!parseScalarString(I.getValue(), Value, Buffer)) 1557 return nullptr; 1558 if (Value == "file") 1559 Kind = RedirectingFileSystem::EK_File; 1560 else if (Value == "directory") 1561 Kind = RedirectingFileSystem::EK_Directory; 1562 else if (Value == "directory-remap") 1563 Kind = RedirectingFileSystem::EK_DirectoryRemap; 1564 else { 1565 error(I.getValue(), "unknown value for 'type'"); 1566 return nullptr; 1567 } 1568 } else if (Key == "contents") { 1569 if (ContentsField != CF_NotSet) { 1570 error(I.getKey(), 1571 "entry already has 'contents' or 'external-contents'"); 1572 return nullptr; 1573 } 1574 ContentsField = CF_List; 1575 auto *Contents = dyn_cast<yaml::SequenceNode>(I.getValue()); 1576 if (!Contents) { 1577 // FIXME: this is only for directories, what about files? 1578 error(I.getValue(), "expected array"); 1579 return nullptr; 1580 } 1581 1582 for (auto &I : *Contents) { 1583 if (std::unique_ptr<RedirectingFileSystem::Entry> E = 1584 parseEntry(&I, FS, /*IsRootEntry*/ false)) 1585 EntryArrayContents.push_back(std::move(E)); 1586 else 1587 return nullptr; 1588 } 1589 } else if (Key == "external-contents") { 1590 if (ContentsField != CF_NotSet) { 1591 error(I.getKey(), 1592 "entry already has 'contents' or 'external-contents'"); 1593 return nullptr; 1594 } 1595 ContentsField = CF_External; 1596 if (!parseScalarString(I.getValue(), Value, Buffer)) 1597 return nullptr; 1598 1599 SmallString<256> FullPath; 1600 if (FS->IsRelativeOverlay) { 1601 FullPath = FS->getExternalContentsPrefixDir(); 1602 assert(!FullPath.empty() && 1603 "External contents prefix directory must exist"); 1604 llvm::sys::path::append(FullPath, Value); 1605 } else { 1606 FullPath = Value; 1607 } 1608 1609 // Guarantee that old YAML files containing paths with ".." and "." 1610 // are properly canonicalized before read into the VFS. 1611 FullPath = canonicalize(FullPath); 1612 ExternalContentsPath = FullPath.str(); 1613 } else if (Key == "use-external-name") { 1614 bool Val; 1615 if (!parseScalarBool(I.getValue(), Val)) 1616 return nullptr; 1617 UseExternalName = Val ? RedirectingFileSystem::NK_External 1618 : RedirectingFileSystem::NK_Virtual; 1619 } else { 1620 llvm_unreachable("key missing from Keys"); 1621 } 1622 } 1623 1624 if (Stream.failed()) 1625 return nullptr; 1626 1627 // check for missing keys 1628 if (ContentsField == CF_NotSet) { 1629 error(N, "missing key 'contents' or 'external-contents'"); 1630 return nullptr; 1631 } 1632 if (!checkMissingKeys(N, Keys)) 1633 return nullptr; 1634 1635 // check invalid configuration 1636 if (Kind == RedirectingFileSystem::EK_Directory && 1637 UseExternalName != RedirectingFileSystem::NK_NotSet) { 1638 error(N, "'use-external-name' is not supported for 'directory' entries"); 1639 return nullptr; 1640 } 1641 1642 if (Kind == RedirectingFileSystem::EK_DirectoryRemap && 1643 ContentsField == CF_List) { 1644 error(N, "'contents' is not supported for 'directory-remap' entries"); 1645 return nullptr; 1646 } 1647 1648 sys::path::Style path_style = sys::path::Style::native; 1649 if (IsRootEntry) { 1650 // VFS root entries may be in either Posix or Windows style. Figure out 1651 // which style we have, and use it consistently. 1652 if (sys::path::is_absolute(Name, sys::path::Style::posix)) { 1653 path_style = sys::path::Style::posix; 1654 } else if (sys::path::is_absolute(Name, 1655 sys::path::Style::windows_backslash)) { 1656 path_style = sys::path::Style::windows_backslash; 1657 } else { 1658 // Relative VFS root entries are made absolute to the current working 1659 // directory, then we can determine the path style from that. 1660 auto EC = sys::fs::make_absolute(Name); 1661 if (EC) { 1662 assert(NameValueNode && "Name presence should be checked earlier"); 1663 error( 1664 NameValueNode, 1665 "entry with relative path at the root level is not discoverable"); 1666 return nullptr; 1667 } 1668 path_style = sys::path::is_absolute(Name, sys::path::Style::posix) 1669 ? sys::path::Style::posix 1670 : sys::path::Style::windows_backslash; 1671 } 1672 } 1673 1674 // Remove trailing slash(es), being careful not to remove the root path 1675 StringRef Trimmed = Name; 1676 size_t RootPathLen = sys::path::root_path(Trimmed, path_style).size(); 1677 while (Trimmed.size() > RootPathLen && 1678 sys::path::is_separator(Trimmed.back(), path_style)) 1679 Trimmed = Trimmed.slice(0, Trimmed.size() - 1); 1680 1681 // Get the last component 1682 StringRef LastComponent = sys::path::filename(Trimmed, path_style); 1683 1684 std::unique_ptr<RedirectingFileSystem::Entry> Result; 1685 switch (Kind) { 1686 case RedirectingFileSystem::EK_File: 1687 Result = std::make_unique<RedirectingFileSystem::FileEntry>( 1688 LastComponent, std::move(ExternalContentsPath), UseExternalName); 1689 break; 1690 case RedirectingFileSystem::EK_DirectoryRemap: 1691 Result = std::make_unique<RedirectingFileSystem::DirectoryRemapEntry>( 1692 LastComponent, std::move(ExternalContentsPath), UseExternalName); 1693 break; 1694 case RedirectingFileSystem::EK_Directory: 1695 Result = std::make_unique<RedirectingFileSystem::DirectoryEntry>( 1696 LastComponent, std::move(EntryArrayContents), 1697 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(), 1698 0, 0, 0, file_type::directory_file, sys::fs::all_all)); 1699 break; 1700 } 1701 1702 StringRef Parent = sys::path::parent_path(Trimmed, path_style); 1703 if (Parent.empty()) 1704 return Result; 1705 1706 // if 'name' contains multiple components, create implicit directory entries 1707 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent, path_style), 1708 E = sys::path::rend(Parent); 1709 I != E; ++I) { 1710 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> Entries; 1711 Entries.push_back(std::move(Result)); 1712 Result = std::make_unique<RedirectingFileSystem::DirectoryEntry>( 1713 *I, std::move(Entries), 1714 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(), 1715 0, 0, 0, file_type::directory_file, sys::fs::all_all)); 1716 } 1717 return Result; 1718 } 1719 1720 public: 1721 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {} 1722 1723 // false on error 1724 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) { 1725 auto *Top = dyn_cast<yaml::MappingNode>(Root); 1726 if (!Top) { 1727 error(Root, "expected mapping node"); 1728 return false; 1729 } 1730 1731 KeyStatusPair Fields[] = { 1732 KeyStatusPair("version", true), 1733 KeyStatusPair("case-sensitive", false), 1734 KeyStatusPair("use-external-names", false), 1735 KeyStatusPair("overlay-relative", false), 1736 KeyStatusPair("fallthrough", false), 1737 KeyStatusPair("roots", true), 1738 }; 1739 1740 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields)); 1741 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> RootEntries; 1742 1743 // Parse configuration and 'roots' 1744 for (auto &I : *Top) { 1745 SmallString<10> KeyBuffer; 1746 StringRef Key; 1747 if (!parseScalarString(I.getKey(), Key, KeyBuffer)) 1748 return false; 1749 1750 if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys)) 1751 return false; 1752 1753 if (Key == "roots") { 1754 auto *Roots = dyn_cast<yaml::SequenceNode>(I.getValue()); 1755 if (!Roots) { 1756 error(I.getValue(), "expected array"); 1757 return false; 1758 } 1759 1760 for (auto &I : *Roots) { 1761 if (std::unique_ptr<RedirectingFileSystem::Entry> E = 1762 parseEntry(&I, FS, /*IsRootEntry*/ true)) 1763 RootEntries.push_back(std::move(E)); 1764 else 1765 return false; 1766 } 1767 } else if (Key == "version") { 1768 StringRef VersionString; 1769 SmallString<4> Storage; 1770 if (!parseScalarString(I.getValue(), VersionString, Storage)) 1771 return false; 1772 int Version; 1773 if (VersionString.getAsInteger<int>(10, Version)) { 1774 error(I.getValue(), "expected integer"); 1775 return false; 1776 } 1777 if (Version < 0) { 1778 error(I.getValue(), "invalid version number"); 1779 return false; 1780 } 1781 if (Version != 0) { 1782 error(I.getValue(), "version mismatch, expected 0"); 1783 return false; 1784 } 1785 } else if (Key == "case-sensitive") { 1786 if (!parseScalarBool(I.getValue(), FS->CaseSensitive)) 1787 return false; 1788 } else if (Key == "overlay-relative") { 1789 if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay)) 1790 return false; 1791 } else if (Key == "use-external-names") { 1792 if (!parseScalarBool(I.getValue(), FS->UseExternalNames)) 1793 return false; 1794 } else if (Key == "fallthrough") { 1795 if (!parseScalarBool(I.getValue(), FS->IsFallthrough)) 1796 return false; 1797 } else { 1798 llvm_unreachable("key missing from Keys"); 1799 } 1800 } 1801 1802 if (Stream.failed()) 1803 return false; 1804 1805 if (!checkMissingKeys(Top, Keys)) 1806 return false; 1807 1808 // Now that we sucessefully parsed the YAML file, canonicalize the internal 1809 // representation to a proper directory tree so that we can search faster 1810 // inside the VFS. 1811 for (auto &E : RootEntries) 1812 uniqueOverlayTree(FS, E.get()); 1813 1814 return true; 1815 } 1816 }; 1817 1818 std::unique_ptr<RedirectingFileSystem> 1819 RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer, 1820 SourceMgr::DiagHandlerTy DiagHandler, 1821 StringRef YAMLFilePath, void *DiagContext, 1822 IntrusiveRefCntPtr<FileSystem> ExternalFS) { 1823 SourceMgr SM; 1824 yaml::Stream Stream(Buffer->getMemBufferRef(), SM); 1825 1826 SM.setDiagHandler(DiagHandler, DiagContext); 1827 yaml::document_iterator DI = Stream.begin(); 1828 yaml::Node *Root = DI->getRoot(); 1829 if (DI == Stream.end() || !Root) { 1830 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node"); 1831 return nullptr; 1832 } 1833 1834 RedirectingFileSystemParser P(Stream); 1835 1836 std::unique_ptr<RedirectingFileSystem> FS( 1837 new RedirectingFileSystem(ExternalFS)); 1838 1839 if (!YAMLFilePath.empty()) { 1840 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed 1841 // to each 'external-contents' path. 1842 // 1843 // Example: 1844 // -ivfsoverlay dummy.cache/vfs/vfs.yaml 1845 // yields: 1846 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs 1847 // 1848 SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath); 1849 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir); 1850 assert(!EC && "Overlay dir final path must be absolute"); 1851 (void)EC; 1852 FS->setExternalContentsPrefixDir(OverlayAbsDir); 1853 } 1854 1855 if (!P.parse(Root, FS.get())) 1856 return nullptr; 1857 1858 return FS; 1859 } 1860 1861 std::unique_ptr<RedirectingFileSystem> RedirectingFileSystem::create( 1862 ArrayRef<std::pair<std::string, std::string>> RemappedFiles, 1863 bool UseExternalNames, FileSystem &ExternalFS) { 1864 std::unique_ptr<RedirectingFileSystem> FS( 1865 new RedirectingFileSystem(&ExternalFS)); 1866 FS->UseExternalNames = UseExternalNames; 1867 1868 StringMap<RedirectingFileSystem::Entry *> Entries; 1869 1870 for (auto &Mapping : llvm::reverse(RemappedFiles)) { 1871 SmallString<128> From = StringRef(Mapping.first); 1872 SmallString<128> To = StringRef(Mapping.second); 1873 { 1874 auto EC = ExternalFS.makeAbsolute(From); 1875 (void)EC; 1876 assert(!EC && "Could not make absolute path"); 1877 } 1878 1879 // Check if we've already mapped this file. The first one we see (in the 1880 // reverse iteration) wins. 1881 RedirectingFileSystem::Entry *&ToEntry = Entries[From]; 1882 if (ToEntry) 1883 continue; 1884 1885 // Add parent directories. 1886 RedirectingFileSystem::Entry *Parent = nullptr; 1887 StringRef FromDirectory = llvm::sys::path::parent_path(From); 1888 for (auto I = llvm::sys::path::begin(FromDirectory), 1889 E = llvm::sys::path::end(FromDirectory); 1890 I != E; ++I) { 1891 Parent = RedirectingFileSystemParser::lookupOrCreateEntry(FS.get(), *I, 1892 Parent); 1893 } 1894 assert(Parent && "File without a directory?"); 1895 { 1896 auto EC = ExternalFS.makeAbsolute(To); 1897 (void)EC; 1898 assert(!EC && "Could not make absolute path"); 1899 } 1900 1901 // Add the file. 1902 auto NewFile = std::make_unique<RedirectingFileSystem::FileEntry>( 1903 llvm::sys::path::filename(From), To, 1904 UseExternalNames ? RedirectingFileSystem::NK_External 1905 : RedirectingFileSystem::NK_Virtual); 1906 ToEntry = NewFile.get(); 1907 cast<RedirectingFileSystem::DirectoryEntry>(Parent)->addContent( 1908 std::move(NewFile)); 1909 } 1910 1911 return FS; 1912 } 1913 1914 RedirectingFileSystem::LookupResult::LookupResult( 1915 Entry *E, sys::path::const_iterator Start, sys::path::const_iterator End) 1916 : E(E) { 1917 assert(E != nullptr); 1918 // If the matched entry is a DirectoryRemapEntry, set ExternalRedirect to the 1919 // path of the directory it maps to in the external file system plus any 1920 // remaining path components in the provided iterator. 1921 if (auto *DRE = dyn_cast<RedirectingFileSystem::DirectoryRemapEntry>(E)) { 1922 SmallString<256> Redirect(DRE->getExternalContentsPath()); 1923 sys::path::append(Redirect, Start, End, 1924 getExistingStyle(DRE->getExternalContentsPath())); 1925 ExternalRedirect = std::string(Redirect); 1926 } 1927 } 1928 1929 bool RedirectingFileSystem::shouldFallBackToExternalFS( 1930 std::error_code EC, RedirectingFileSystem::Entry *E) const { 1931 if (E && !isa<RedirectingFileSystem::DirectoryRemapEntry>(E)) 1932 return false; 1933 return shouldUseExternalFS() && EC == llvm::errc::no_such_file_or_directory; 1934 } 1935 1936 std::error_code 1937 RedirectingFileSystem::makeCanonical(SmallVectorImpl<char> &Path) const { 1938 if (std::error_code EC = makeAbsolute(Path)) 1939 return EC; 1940 1941 llvm::SmallString<256> CanonicalPath = 1942 canonicalize(StringRef(Path.data(), Path.size())); 1943 if (CanonicalPath.empty()) 1944 return make_error_code(llvm::errc::invalid_argument); 1945 1946 Path.assign(CanonicalPath.begin(), CanonicalPath.end()); 1947 return {}; 1948 } 1949 1950 ErrorOr<RedirectingFileSystem::LookupResult> 1951 RedirectingFileSystem::lookupPath(StringRef Path) const { 1952 sys::path::const_iterator Start = sys::path::begin(Path); 1953 sys::path::const_iterator End = sys::path::end(Path); 1954 for (const auto &Root : Roots) { 1955 ErrorOr<RedirectingFileSystem::LookupResult> Result = 1956 lookupPathImpl(Start, End, Root.get()); 1957 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory) 1958 return Result; 1959 } 1960 return make_error_code(llvm::errc::no_such_file_or_directory); 1961 } 1962 1963 ErrorOr<RedirectingFileSystem::LookupResult> 1964 RedirectingFileSystem::lookupPathImpl( 1965 sys::path::const_iterator Start, sys::path::const_iterator End, 1966 RedirectingFileSystem::Entry *From) const { 1967 assert(!isTraversalComponent(*Start) && 1968 !isTraversalComponent(From->getName()) && 1969 "Paths should not contain traversal components"); 1970 1971 StringRef FromName = From->getName(); 1972 1973 // Forward the search to the next component in case this is an empty one. 1974 if (!FromName.empty()) { 1975 if (!pathComponentMatches(*Start, FromName)) 1976 return make_error_code(llvm::errc::no_such_file_or_directory); 1977 1978 ++Start; 1979 1980 if (Start == End) { 1981 // Match! 1982 return LookupResult(From, Start, End); 1983 } 1984 } 1985 1986 if (isa<RedirectingFileSystem::FileEntry>(From)) 1987 return make_error_code(llvm::errc::not_a_directory); 1988 1989 if (isa<RedirectingFileSystem::DirectoryRemapEntry>(From)) 1990 return LookupResult(From, Start, End); 1991 1992 auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(From); 1993 for (const std::unique_ptr<RedirectingFileSystem::Entry> &DirEntry : 1994 llvm::make_range(DE->contents_begin(), DE->contents_end())) { 1995 ErrorOr<RedirectingFileSystem::LookupResult> Result = 1996 lookupPathImpl(Start, End, DirEntry.get()); 1997 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory) 1998 return Result; 1999 } 2000 2001 return make_error_code(llvm::errc::no_such_file_or_directory); 2002 } 2003 2004 static Status getRedirectedFileStatus(const Twine &OriginalPath, 2005 bool UseExternalNames, 2006 Status ExternalStatus) { 2007 Status S = ExternalStatus; 2008 if (!UseExternalNames) 2009 S = Status::copyWithNewName(S, OriginalPath); 2010 S.IsVFSMapped = true; 2011 return S; 2012 } 2013 2014 ErrorOr<Status> RedirectingFileSystem::status( 2015 const Twine &CanonicalPath, const Twine &OriginalPath, 2016 const RedirectingFileSystem::LookupResult &Result) { 2017 if (Optional<StringRef> ExtRedirect = Result.getExternalRedirect()) { 2018 SmallString<256> CanonicalRemappedPath((*ExtRedirect).str()); 2019 if (std::error_code EC = makeCanonical(CanonicalRemappedPath)) 2020 return EC; 2021 2022 ErrorOr<Status> S = ExternalFS->status(CanonicalRemappedPath); 2023 if (!S) 2024 return S; 2025 S = Status::copyWithNewName(*S, *ExtRedirect); 2026 auto *RE = cast<RedirectingFileSystem::RemapEntry>(Result.E); 2027 return getRedirectedFileStatus(OriginalPath, 2028 RE->useExternalName(UseExternalNames), *S); 2029 } 2030 2031 auto *DE = cast<RedirectingFileSystem::DirectoryEntry>(Result.E); 2032 return Status::copyWithNewName(DE->getStatus(), CanonicalPath); 2033 } 2034 2035 ErrorOr<Status> 2036 RedirectingFileSystem::getExternalStatus(const Twine &CanonicalPath, 2037 const Twine &OriginalPath) const { 2038 if (auto Result = ExternalFS->status(CanonicalPath)) { 2039 return Result.get().copyWithNewName(Result.get(), OriginalPath); 2040 } else { 2041 return Result.getError(); 2042 } 2043 } 2044 2045 ErrorOr<Status> RedirectingFileSystem::status(const Twine &OriginalPath) { 2046 SmallString<256> CanonicalPath; 2047 OriginalPath.toVector(CanonicalPath); 2048 2049 if (std::error_code EC = makeCanonical(CanonicalPath)) 2050 return EC; 2051 2052 ErrorOr<RedirectingFileSystem::LookupResult> Result = 2053 lookupPath(CanonicalPath); 2054 if (!Result) { 2055 if (shouldFallBackToExternalFS(Result.getError())) { 2056 return getExternalStatus(CanonicalPath, OriginalPath); 2057 } 2058 return Result.getError(); 2059 } 2060 2061 ErrorOr<Status> S = status(CanonicalPath, OriginalPath, *Result); 2062 if (!S && shouldFallBackToExternalFS(S.getError(), Result->E)) { 2063 return getExternalStatus(CanonicalPath, OriginalPath); 2064 } 2065 2066 return S; 2067 } 2068 2069 namespace { 2070 2071 /// Provide a file wrapper with an overriden status. 2072 class FileWithFixedStatus : public File { 2073 std::unique_ptr<File> InnerFile; 2074 Status S; 2075 2076 public: 2077 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S) 2078 : InnerFile(std::move(InnerFile)), S(std::move(S)) {} 2079 2080 ErrorOr<Status> status() override { return S; } 2081 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 2082 2083 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator, 2084 bool IsVolatile) override { 2085 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator, 2086 IsVolatile); 2087 } 2088 2089 std::error_code close() override { return InnerFile->close(); } 2090 2091 void setPath(const Twine &Path) override { S = S.copyWithNewName(S, Path); } 2092 }; 2093 2094 } // namespace 2095 2096 ErrorOr<std::unique_ptr<File>> 2097 File::getWithPath(ErrorOr<std::unique_ptr<File>> Result, const Twine &P) { 2098 if (!Result) 2099 return Result; 2100 2101 ErrorOr<std::unique_ptr<File>> F = std::move(*Result); 2102 auto Name = F->get()->getName(); 2103 if (Name && Name.get() != P.str()) 2104 F->get()->setPath(P); 2105 return F; 2106 } 2107 2108 ErrorOr<std::unique_ptr<File>> 2109 RedirectingFileSystem::openFileForRead(const Twine &OriginalPath) { 2110 SmallString<256> CanonicalPath; 2111 OriginalPath.toVector(CanonicalPath); 2112 2113 if (std::error_code EC = makeCanonical(CanonicalPath)) 2114 return EC; 2115 2116 ErrorOr<RedirectingFileSystem::LookupResult> Result = 2117 lookupPath(CanonicalPath); 2118 if (!Result) { 2119 if (shouldFallBackToExternalFS(Result.getError())) 2120 return File::getWithPath(ExternalFS->openFileForRead(CanonicalPath), 2121 OriginalPath); 2122 2123 return Result.getError(); 2124 } 2125 2126 if (!Result->getExternalRedirect()) // FIXME: errc::not_a_file? 2127 return make_error_code(llvm::errc::invalid_argument); 2128 2129 StringRef ExtRedirect = *Result->getExternalRedirect(); 2130 SmallString<256> CanonicalRemappedPath(ExtRedirect.str()); 2131 if (std::error_code EC = makeCanonical(CanonicalRemappedPath)) 2132 return EC; 2133 2134 auto *RE = cast<RedirectingFileSystem::RemapEntry>(Result->E); 2135 2136 auto ExternalFile = File::getWithPath( 2137 ExternalFS->openFileForRead(CanonicalRemappedPath), ExtRedirect); 2138 if (!ExternalFile) { 2139 if (shouldFallBackToExternalFS(ExternalFile.getError(), Result->E)) 2140 return File::getWithPath(ExternalFS->openFileForRead(CanonicalPath), 2141 OriginalPath); 2142 return ExternalFile; 2143 } 2144 2145 auto ExternalStatus = (*ExternalFile)->status(); 2146 if (!ExternalStatus) 2147 return ExternalStatus.getError(); 2148 2149 // FIXME: Update the status with the name and VFSMapped. 2150 Status S = getRedirectedFileStatus( 2151 OriginalPath, RE->useExternalName(UseExternalNames), *ExternalStatus); 2152 return std::unique_ptr<File>( 2153 std::make_unique<FileWithFixedStatus>(std::move(*ExternalFile), S)); 2154 } 2155 2156 std::error_code 2157 RedirectingFileSystem::getRealPath(const Twine &Path_, 2158 SmallVectorImpl<char> &Output) const { 2159 SmallString<256> Path; 2160 Path_.toVector(Path); 2161 2162 if (std::error_code EC = makeCanonical(Path)) 2163 return EC; 2164 2165 ErrorOr<RedirectingFileSystem::LookupResult> Result = lookupPath(Path); 2166 if (!Result) { 2167 if (shouldFallBackToExternalFS(Result.getError())) 2168 return ExternalFS->getRealPath(Path, Output); 2169 return Result.getError(); 2170 } 2171 2172 // If we found FileEntry or DirectoryRemapEntry, look up the mapped 2173 // path in the external file system. 2174 if (auto ExtRedirect = Result->getExternalRedirect()) { 2175 auto P = ExternalFS->getRealPath(*ExtRedirect, Output); 2176 if (!P && shouldFallBackToExternalFS(P, Result->E)) { 2177 return ExternalFS->getRealPath(Path, Output); 2178 } 2179 return P; 2180 } 2181 2182 // If we found a DirectoryEntry, still fall back to ExternalFS if allowed, 2183 // because directories don't have a single external contents path. 2184 return shouldUseExternalFS() ? ExternalFS->getRealPath(Path, Output) 2185 : llvm::errc::invalid_argument; 2186 } 2187 2188 std::unique_ptr<FileSystem> 2189 vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer, 2190 SourceMgr::DiagHandlerTy DiagHandler, 2191 StringRef YAMLFilePath, void *DiagContext, 2192 IntrusiveRefCntPtr<FileSystem> ExternalFS) { 2193 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler, 2194 YAMLFilePath, DiagContext, 2195 std::move(ExternalFS)); 2196 } 2197 2198 static void getVFSEntries(RedirectingFileSystem::Entry *SrcE, 2199 SmallVectorImpl<StringRef> &Path, 2200 SmallVectorImpl<YAMLVFSEntry> &Entries) { 2201 auto Kind = SrcE->getKind(); 2202 if (Kind == RedirectingFileSystem::EK_Directory) { 2203 auto *DE = dyn_cast<RedirectingFileSystem::DirectoryEntry>(SrcE); 2204 assert(DE && "Must be a directory"); 2205 for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry : 2206 llvm::make_range(DE->contents_begin(), DE->contents_end())) { 2207 Path.push_back(SubEntry->getName()); 2208 getVFSEntries(SubEntry.get(), Path, Entries); 2209 Path.pop_back(); 2210 } 2211 return; 2212 } 2213 2214 if (Kind == RedirectingFileSystem::EK_DirectoryRemap) { 2215 auto *DR = dyn_cast<RedirectingFileSystem::DirectoryRemapEntry>(SrcE); 2216 assert(DR && "Must be a directory remap"); 2217 SmallString<128> VPath; 2218 for (auto &Comp : Path) 2219 llvm::sys::path::append(VPath, Comp); 2220 Entries.push_back( 2221 YAMLVFSEntry(VPath.c_str(), DR->getExternalContentsPath())); 2222 return; 2223 } 2224 2225 assert(Kind == RedirectingFileSystem::EK_File && "Must be a EK_File"); 2226 auto *FE = dyn_cast<RedirectingFileSystem::FileEntry>(SrcE); 2227 assert(FE && "Must be a file"); 2228 SmallString<128> VPath; 2229 for (auto &Comp : Path) 2230 llvm::sys::path::append(VPath, Comp); 2231 Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath())); 2232 } 2233 2234 void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer, 2235 SourceMgr::DiagHandlerTy DiagHandler, 2236 StringRef YAMLFilePath, 2237 SmallVectorImpl<YAMLVFSEntry> &CollectedEntries, 2238 void *DiagContext, 2239 IntrusiveRefCntPtr<FileSystem> ExternalFS) { 2240 std::unique_ptr<RedirectingFileSystem> VFS = RedirectingFileSystem::create( 2241 std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext, 2242 std::move(ExternalFS)); 2243 if (!VFS) 2244 return; 2245 ErrorOr<RedirectingFileSystem::LookupResult> RootResult = 2246 VFS->lookupPath("/"); 2247 if (!RootResult) 2248 return; 2249 SmallVector<StringRef, 8> Components; 2250 Components.push_back("/"); 2251 getVFSEntries(RootResult->E, Components, CollectedEntries); 2252 } 2253 2254 UniqueID vfs::getNextVirtualUniqueID() { 2255 static std::atomic<unsigned> UID; 2256 unsigned ID = ++UID; 2257 // The following assumes that uint64_t max will never collide with a real 2258 // dev_t value from the OS. 2259 return UniqueID(std::numeric_limits<uint64_t>::max(), ID); 2260 } 2261 2262 void YAMLVFSWriter::addEntry(StringRef VirtualPath, StringRef RealPath, 2263 bool IsDirectory) { 2264 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute"); 2265 assert(sys::path::is_absolute(RealPath) && "real path not absolute"); 2266 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported"); 2267 Mappings.emplace_back(VirtualPath, RealPath, IsDirectory); 2268 } 2269 2270 void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) { 2271 addEntry(VirtualPath, RealPath, /*IsDirectory=*/false); 2272 } 2273 2274 void YAMLVFSWriter::addDirectoryMapping(StringRef VirtualPath, 2275 StringRef RealPath) { 2276 addEntry(VirtualPath, RealPath, /*IsDirectory=*/true); 2277 } 2278 2279 namespace { 2280 2281 class JSONWriter { 2282 llvm::raw_ostream &OS; 2283 SmallVector<StringRef, 16> DirStack; 2284 2285 unsigned getDirIndent() { return 4 * DirStack.size(); } 2286 unsigned getFileIndent() { return 4 * (DirStack.size() + 1); } 2287 bool containedIn(StringRef Parent, StringRef Path); 2288 StringRef containedPart(StringRef Parent, StringRef Path); 2289 void startDirectory(StringRef Path); 2290 void endDirectory(); 2291 void writeEntry(StringRef VPath, StringRef RPath); 2292 2293 public: 2294 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {} 2295 2296 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames, 2297 Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative, 2298 StringRef OverlayDir); 2299 }; 2300 2301 } // namespace 2302 2303 bool JSONWriter::containedIn(StringRef Parent, StringRef Path) { 2304 using namespace llvm::sys; 2305 2306 // Compare each path component. 2307 auto IParent = path::begin(Parent), EParent = path::end(Parent); 2308 for (auto IChild = path::begin(Path), EChild = path::end(Path); 2309 IParent != EParent && IChild != EChild; ++IParent, ++IChild) { 2310 if (*IParent != *IChild) 2311 return false; 2312 } 2313 // Have we exhausted the parent path? 2314 return IParent == EParent; 2315 } 2316 2317 StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) { 2318 assert(!Parent.empty()); 2319 assert(containedIn(Parent, Path)); 2320 return Path.slice(Parent.size() + 1, StringRef::npos); 2321 } 2322 2323 void JSONWriter::startDirectory(StringRef Path) { 2324 StringRef Name = 2325 DirStack.empty() ? Path : containedPart(DirStack.back(), Path); 2326 DirStack.push_back(Path); 2327 unsigned Indent = getDirIndent(); 2328 OS.indent(Indent) << "{\n"; 2329 OS.indent(Indent + 2) << "'type': 'directory',\n"; 2330 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n"; 2331 OS.indent(Indent + 2) << "'contents': [\n"; 2332 } 2333 2334 void JSONWriter::endDirectory() { 2335 unsigned Indent = getDirIndent(); 2336 OS.indent(Indent + 2) << "]\n"; 2337 OS.indent(Indent) << "}"; 2338 2339 DirStack.pop_back(); 2340 } 2341 2342 void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) { 2343 unsigned Indent = getFileIndent(); 2344 OS.indent(Indent) << "{\n"; 2345 OS.indent(Indent + 2) << "'type': 'file',\n"; 2346 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n"; 2347 OS.indent(Indent + 2) << "'external-contents': \"" 2348 << llvm::yaml::escape(RPath) << "\"\n"; 2349 OS.indent(Indent) << "}"; 2350 } 2351 2352 void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries, 2353 Optional<bool> UseExternalNames, 2354 Optional<bool> IsCaseSensitive, 2355 Optional<bool> IsOverlayRelative, 2356 StringRef OverlayDir) { 2357 using namespace llvm::sys; 2358 2359 OS << "{\n" 2360 " 'version': 0,\n"; 2361 if (IsCaseSensitive.hasValue()) 2362 OS << " 'case-sensitive': '" 2363 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n"; 2364 if (UseExternalNames.hasValue()) 2365 OS << " 'use-external-names': '" 2366 << (UseExternalNames.getValue() ? "true" : "false") << "',\n"; 2367 bool UseOverlayRelative = false; 2368 if (IsOverlayRelative.hasValue()) { 2369 UseOverlayRelative = IsOverlayRelative.getValue(); 2370 OS << " 'overlay-relative': '" << (UseOverlayRelative ? "true" : "false") 2371 << "',\n"; 2372 } 2373 OS << " 'roots': [\n"; 2374 2375 if (!Entries.empty()) { 2376 const YAMLVFSEntry &Entry = Entries.front(); 2377 2378 startDirectory( 2379 Entry.IsDirectory ? Entry.VPath : path::parent_path(Entry.VPath) 2380 ); 2381 2382 StringRef RPath = Entry.RPath; 2383 if (UseOverlayRelative) { 2384 unsigned OverlayDirLen = OverlayDir.size(); 2385 assert(RPath.substr(0, OverlayDirLen) == OverlayDir && 2386 "Overlay dir must be contained in RPath"); 2387 RPath = RPath.slice(OverlayDirLen, RPath.size()); 2388 } 2389 2390 bool IsCurrentDirEmpty = true; 2391 if (!Entry.IsDirectory) { 2392 writeEntry(path::filename(Entry.VPath), RPath); 2393 IsCurrentDirEmpty = false; 2394 } 2395 2396 for (const auto &Entry : Entries.slice(1)) { 2397 StringRef Dir = 2398 Entry.IsDirectory ? Entry.VPath : path::parent_path(Entry.VPath); 2399 if (Dir == DirStack.back()) { 2400 if (!IsCurrentDirEmpty) { 2401 OS << ",\n"; 2402 } 2403 } else { 2404 bool IsDirPoppedFromStack = false; 2405 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) { 2406 OS << "\n"; 2407 endDirectory(); 2408 IsDirPoppedFromStack = true; 2409 } 2410 if (IsDirPoppedFromStack || !IsCurrentDirEmpty) { 2411 OS << ",\n"; 2412 } 2413 startDirectory(Dir); 2414 IsCurrentDirEmpty = true; 2415 } 2416 StringRef RPath = Entry.RPath; 2417 if (UseOverlayRelative) { 2418 unsigned OverlayDirLen = OverlayDir.size(); 2419 assert(RPath.substr(0, OverlayDirLen) == OverlayDir && 2420 "Overlay dir must be contained in RPath"); 2421 RPath = RPath.slice(OverlayDirLen, RPath.size()); 2422 } 2423 if (!Entry.IsDirectory) { 2424 writeEntry(path::filename(Entry.VPath), RPath); 2425 IsCurrentDirEmpty = false; 2426 } 2427 } 2428 2429 while (!DirStack.empty()) { 2430 OS << "\n"; 2431 endDirectory(); 2432 } 2433 OS << "\n"; 2434 } 2435 2436 OS << " ]\n" 2437 << "}\n"; 2438 } 2439 2440 void YAMLVFSWriter::write(llvm::raw_ostream &OS) { 2441 llvm::sort(Mappings, [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) { 2442 return LHS.VPath < RHS.VPath; 2443 }); 2444 2445 JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive, 2446 IsOverlayRelative, OverlayDir); 2447 } 2448 2449 vfs::recursive_directory_iterator::recursive_directory_iterator( 2450 FileSystem &FS_, const Twine &Path, std::error_code &EC) 2451 : FS(&FS_) { 2452 directory_iterator I = FS->dir_begin(Path, EC); 2453 if (I != directory_iterator()) { 2454 State = std::make_shared<detail::RecDirIterState>(); 2455 State->Stack.push(I); 2456 } 2457 } 2458 2459 vfs::recursive_directory_iterator & 2460 recursive_directory_iterator::increment(std::error_code &EC) { 2461 assert(FS && State && !State->Stack.empty() && "incrementing past end"); 2462 assert(!State->Stack.top()->path().empty() && "non-canonical end iterator"); 2463 vfs::directory_iterator End; 2464 2465 if (State->HasNoPushRequest) 2466 State->HasNoPushRequest = false; 2467 else { 2468 if (State->Stack.top()->type() == sys::fs::file_type::directory_file) { 2469 vfs::directory_iterator I = FS->dir_begin(State->Stack.top()->path(), EC); 2470 if (I != End) { 2471 State->Stack.push(I); 2472 return *this; 2473 } 2474 } 2475 } 2476 2477 while (!State->Stack.empty() && State->Stack.top().increment(EC) == End) 2478 State->Stack.pop(); 2479 2480 if (State->Stack.empty()) 2481 State.reset(); // end iterator 2482 2483 return *this; 2484 } 2485