Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Support/VirtualFileSystem.cpp
Line
Count
Source (jump to first uncovered line)
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/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 <mutex>
51
#include <string>
52
#include <system_error>
53
#include <utility>
54
#include <vector>
55
56
using namespace llvm;
57
using namespace llvm::vfs;
58
59
using llvm::sys::fs::file_t;
60
using llvm::sys::fs::file_status;
61
using llvm::sys::fs::file_type;
62
using llvm::sys::fs::kInvalidFile;
63
using llvm::sys::fs::perms;
64
using llvm::sys::fs::UniqueID;
65
66
Status::Status(const file_status &Status)
67
    : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
68
      User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
69
0
      Type(Status.type()), Perms(Status.permissions()) {}
70
71
Status::Status(const Twine &Name, UniqueID UID, sys::TimePoint<> MTime,
72
               uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
73
               perms Perms)
74
    : Name(Name.str()), UID(UID), MTime(MTime), User(User), Group(Group),
75
1.66M
      Size(Size), Type(Type), Perms(Perms) {}
76
77
118k
Status Status::copyWithNewName(const Status &In, const Twine &NewName) {
78
118k
  return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
79
118k
                In.getUser(), In.getGroup(), In.getSize(), In.getType(),
80
118k
                In.getPermissions());
81
118k
}
82
83
834k
Status Status::copyWithNewName(const file_status &In, const Twine &NewName) {
84
834k
  return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
85
834k
                In.getUser(), In.getGroup(), In.getSize(), In.type(),
86
834k
                In.permissions());
87
834k
}
88
89
16
bool Status::equivalent(const Status &Other) const {
90
16
  assert(isStatusKnown() && Other.isStatusKnown());
91
16
  return getUniqueID() == Other.getUniqueID();
92
16
}
93
94
857k
bool Status::isDirectory() const { return Type == file_type::directory_file; }
95
96
12
bool Status::isRegularFile() const { return Type == file_type::regular_file; }
97
98
3
bool Status::isOther() const {
99
3
  return exists() && !isRegularFile() && 
!isDirectory()2
&&
!isSymlink()1
;
100
3
}
101
102
10
bool Status::isSymlink() const { return Type == file_type::symlink_file; }
103
104
591k
bool Status::isStatusKnown() const { return Type != file_type::status_error; }
105
106
91.9k
bool Status::exists() const {
107
91.9k
  return isStatusKnown() && Type != file_type::file_not_found;
108
91.9k
}
109
110
563k
File::~File() = default;
111
112
108k
FileSystem::~FileSystem() = default;
113
114
ErrorOr<std::unique_ptr<MemoryBuffer>>
115
FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
116
420k
                             bool RequiresNullTerminator, bool IsVolatile) {
117
420k
  auto F = openFileForRead(Name);
118
420k
  if (!F)
119
356k
    return F.getError();
120
63.3k
121
63.3k
  return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
122
63.3k
}
123
124
553k
std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
125
553k
  if (llvm::sys::path::is_absolute(Path))
126
219k
    return {};
127
334k
128
334k
  auto WorkingDir = getCurrentWorkingDirectory();
129
334k
  if (!WorkingDir)
130
0
    return WorkingDir.getError();
131
334k
132
334k
  llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
133
334k
  return {};
134
334k
}
135
136
std::error_code FileSystem::getRealPath(const Twine &Path,
137
0
                                        SmallVectorImpl<char> &Output) const {
138
0
  return errc::operation_not_permitted;
139
0
}
140
141
0
std::error_code FileSystem::isLocal(const Twine &Path, bool &Result) {
142
0
  return errc::operation_not_permitted;
143
0
}
144
145
690k
bool FileSystem::exists(const Twine &Path) {
146
690k
  auto Status = status(Path);
147
690k
  return Status && 
Status->exists()91.9k
;
148
690k
}
149
150
#ifndef NDEBUG
151
static bool isTraversalComponent(StringRef Component) {
152
  return Component.equals("..") || Component.equals(".");
153
}
154
155
static bool pathHasTraversal(StringRef Path) {
156
  using namespace llvm::sys;
157
158
  for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
159
    if (isTraversalComponent(Comp))
160
      return true;
161
  return false;
162
}
163
#endif
164
165
//===-----------------------------------------------------------------------===/
166
// RealFileSystem implementation
167
//===-----------------------------------------------------------------------===/
168
169
namespace {
170
171
/// Wrapper around a raw file descriptor.
172
class RealFile : public File {
173
  friend class RealFileSystem;
174
175
  file_t FD;
176
  Status S;
177
  std::string RealName;
178
179
  RealFile(file_t FD, StringRef NewName, StringRef NewRealPathName)
180
      : FD(FD), S(NewName, {}, {}, {}, {}, {},
181
                  llvm::sys::fs::file_type::status_error, {}),
182
518k
        RealName(NewRealPathName.str()) {
183
518k
    assert(FD != kInvalidFile && "Invalid or inactive file descriptor");
184
518k
  }
185
186
public:
187
  ~RealFile() override;
188
189
  ErrorOr<Status> status() override;
190
  ErrorOr<std::string> getName() override;
191
  ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
192
                                                   int64_t FileSize,
193
                                                   bool RequiresNullTerminator,
194
                                                   bool IsVolatile) override;
195
  std::error_code close() override;
196
};
197
198
} // namespace
199
200
511k
RealFile::~RealFile() { close(); }
201
202
499k
ErrorOr<Status> RealFile::status() {
203
499k
  assert(FD != kInvalidFile && "cannot stat closed file");
204
499k
  if (!S.isStatusKnown()) {
205
499k
    file_status RealStatus;
206
499k
    if (std::error_code EC = sys::fs::status(FD, RealStatus))
207
0
      return EC;
208
499k
    S = Status::copyWithNewName(RealStatus, S.getName());
209
499k
  }
210
499k
  return S;
211
499k
}
212
213
497k
ErrorOr<std::string> RealFile::getName() {
214
497k
  return RealName.empty() ? 
S.getName().str()1
:
RealName497k
;
215
497k
}
216
217
ErrorOr<std::unique_ptr<MemoryBuffer>>
218
RealFile::getBuffer(const Twine &Name, int64_t FileSize,
219
508k
                    bool RequiresNullTerminator, bool IsVolatile) {
220
508k
  assert(FD != kInvalidFile && "cannot get buffer for closed file");
221
508k
  return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
222
508k
                                   IsVolatile);
223
508k
}
224
225
511k
std::error_code RealFile::close() {
226
511k
  std::error_code EC = sys::fs::closeFile(FD);
227
511k
  FD = kInvalidFile;
228
511k
  return EC;
229
511k
}
230
231
namespace {
232
233
/// A file system according to your operating system.
234
/// This may be linked to the process's working directory, or maintain its own.
235
///
236
/// Currently, its own working directory is emulated by storing the path and
237
/// sending absolute paths to llvm::sys::fs:: functions.
238
/// A more principled approach would be to push this down a level, modelling
239
/// the working dir as an llvm::sys::fs::WorkingDir or similar.
240
/// This would enable the use of openat()-style functions on some platforms.
241
class RealFileSystem : public FileSystem {
242
public:
243
65.0k
  explicit RealFileSystem(bool LinkCWDToProcess) {
244
65.0k
    if (!LinkCWDToProcess) {
245
23.3k
      SmallString<128> PWD, RealPWD;
246
23.3k
      if (llvm::sys::fs::current_path(PWD))
247
0
        return; // Awful, but nothing to do here.
248
23.3k
      if (llvm::sys::fs::real_path(PWD, RealPWD))
249
0
        WD = {PWD, PWD};
250
23.3k
      else
251
23.3k
        WD = {PWD, RealPWD};
252
23.3k
    }
253
65.0k
  }
254
255
  ErrorOr<Status> status(const Twine &Path) override;
256
  ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
257
  directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
258
259
  llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
260
  std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
261
  std::error_code isLocal(const Twine &Path, bool &Result) override;
262
  std::error_code getRealPath(const Twine &Path,
263
                              SmallVectorImpl<char> &Output) const override;
264
265
private:
266
  // If this FS has its own working dir, use it to make Path absolute.
267
  // The returned twine is safe to use as long as both Storage and Path live.
268
2.55M
  Twine adjustPath(const Twine &Path, SmallVectorImpl<char> &Storage) const {
269
2.55M
    if (!WD)
270
1.26M
      return Path;
271
1.28M
    Path.toVector(Storage);
272
1.28M
    sys::fs::make_absolute(WD->Resolved, Storage);
273
1.28M
    return Storage;
274
1.28M
  }
275
276
  struct WorkingDirectory {
277
    // The current working directory, without symlinks resolved. (echo $PWD).
278
    SmallString<128> Specified;
279
    // The current working directory, with links resolved. (readlink .).
280
    SmallString<128> Resolved;
281
  };
282
  Optional<WorkingDirectory> WD;
283
};
284
285
} // namespace
286
287
1.11M
ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
288
1.11M
  SmallString<256> Storage;
289
1.11M
  sys::fs::file_status RealStatus;
290
1.11M
  if (std::error_code EC =
291
784k
          sys::fs::status(adjustPath(Path, Storage), RealStatus))
292
784k
    return EC;
293
334k
  return Status::copyWithNewName(RealStatus, Path);
294
334k
}
295
296
ErrorOr<std::unique_ptr<File>>
297
1.01M
RealFileSystem::openFileForRead(const Twine &Name) {
298
1.01M
  SmallString<256> RealName, Storage;
299
1.01M
  Expected<file_t> FDOrErr = sys::fs::openNativeFileForRead(
300
1.01M
      adjustPath(Name, Storage), sys::fs::OF_None, &RealName);
301
1.01M
  if (!FDOrErr)
302
499k
    return errorToErrorCode(FDOrErr.takeError());
303
518k
  return std::unique_ptr<File>(
304
518k
      new RealFile(*FDOrErr, Name.str(), RealName.str()));
305
518k
}
306
307
71.8k
llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
308
71.8k
  if (WD)
309
40.2k
    return WD->Specified.str();
310
31.5k
311
31.5k
  SmallString<128> Dir;
312
31.5k
  if (std::error_code EC = llvm::sys::fs::current_path(Dir))
313
0
    return EC;
314
31.5k
  return Dir.str();
315
31.5k
}
316
317
623
std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
318
623
  if (!WD)
319
409
    return llvm::sys::fs::set_current_path(Path);
320
214
321
214
  SmallString<128> Absolute, Resolved, Storage;
322
214
  adjustPath(Path, Storage).toVector(Absolute);
323
214
  bool IsDir;
324
214
  if (auto Err = llvm::sys::fs::is_directory(Absolute, IsDir))
325
1
    return Err;
326
213
  if (!IsDir)
327
0
    return std::make_error_code(std::errc::not_a_directory);
328
213
  if (auto Err = llvm::sys::fs::real_path(Absolute, Resolved))
329
0
    return Err;
330
213
  WD = {Absolute, Resolved};
331
213
  return std::error_code();
332
213
}
333
334
0
std::error_code RealFileSystem::isLocal(const Twine &Path, bool &Result) {
335
0
  SmallString<256> Storage;
336
0
  return llvm::sys::fs::is_local(adjustPath(Path, Storage), Result);
337
0
}
338
339
std::error_code
340
RealFileSystem::getRealPath(const Twine &Path,
341
1.51k
                            SmallVectorImpl<char> &Output) const {
342
1.51k
  SmallString<256> Storage;
343
1.51k
  return llvm::sys::fs::real_path(adjustPath(Path, Storage), Output);
344
1.51k
}
345
346
46.9k
IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
347
46.9k
  static IntrusiveRefCntPtr<FileSystem> FS(new RealFileSystem(true));
348
46.9k
  return FS;
349
46.9k
}
350
351
23.3k
std::unique_ptr<FileSystem> vfs::createPhysicalFileSystem() {
352
23.3k
  return llvm::make_unique<RealFileSystem>(false);
353
23.3k
}
354
355
namespace {
356
357
class RealFSDirIter : public llvm::vfs::detail::DirIterImpl {
358
  llvm::sys::fs::directory_iterator Iter;
359
360
public:
361
415k
  RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) {
362
415k
    if (Iter != llvm::sys::fs::directory_iterator())
363
1.72k
      CurrentEntry = directory_entry(Iter->path(), Iter->type());
364
415k
  }
365
366
9.34k
  std::error_code increment() override {
367
9.34k
    std::error_code EC;
368
9.34k
    Iter.increment(EC);
369
9.34k
    CurrentEntry = (Iter == llvm::sys::fs::directory_iterator())
370
9.34k
                       ? 
directory_entry()1.72k
371
9.34k
                       : 
directory_entry(Iter->path(), Iter->type())7.62k
;
372
9.34k
    return EC;
373
9.34k
  }
374
};
375
376
} // namespace
377
378
directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
379
415k
                                             std::error_code &EC) {
380
415k
  SmallString<128> Storage;
381
415k
  return directory_iterator(
382
415k
      std::make_shared<RealFSDirIter>(adjustPath(Dir, Storage), EC));
383
415k
}
384
385
//===-----------------------------------------------------------------------===/
386
// OverlayFileSystem implementation
387
//===-----------------------------------------------------------------------===/
388
389
7.30k
OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
390
7.30k
  FSList.push_back(std::move(BaseFS));
391
7.30k
}
392
393
7.31k
void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
394
7.31k
  FSList.push_back(FS);
395
7.31k
  // Synchronize added file systems by duplicating the working directory from
396
7.31k
  // the first one in the list.
397
7.31k
  FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
398
7.31k
}
399
400
199k
ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
401
199k
  // FIXME: handle symlinks that cross file systems
402
541k
  for (iterator I = overlays_begin(), E = overlays_end(); I != E; 
++I341k
) {
403
382k
    ErrorOr<Status> Status = (*I)->status(Path);
404
382k
    if (Status || 
Status.getError() != llvm::errc::no_such_file_or_directory341k
)
405
40.8k
      return Status;
406
382k
  }
407
199k
  
return make_error_code(llvm::errc::no_such_file_or_directory)158k
;
408
199k
}
409
410
ErrorOr<std::unique_ptr<File>>
411
72.2k
OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
412
72.2k
  // FIXME: handle symlinks that cross file systems
413
199k
  for (iterator I = overlays_begin(), E = overlays_end(); I != E; 
++I127k
) {
414
136k
    auto Result = (*I)->openFileForRead(Path);
415
136k
    if (Result || 
Result.getError() != llvm::errc::no_such_file_or_directory127k
)
416
8.83k
      return Result;
417
136k
  }
418
72.2k
  
return make_error_code(llvm::errc::no_such_file_or_directory)63.4k
;
419
72.2k
}
420
421
llvm::ErrorOr<std::string>
422
24.1k
OverlayFileSystem::getCurrentWorkingDirectory() const {
423
24.1k
  // All file systems are synchronized, just take the first working directory.
424
24.1k
  return FSList.front()->getCurrentWorkingDirectory();
425
24.1k
}
426
427
std::error_code
428
626
OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
429
626
  for (auto &FS : FSList)
430
1.25k
    if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
431
0
      return EC;
432
626
  return {};
433
626
}
434
435
0
std::error_code OverlayFileSystem::isLocal(const Twine &Path, bool &Result) {
436
0
  for (auto &FS : FSList)
437
0
    if (FS->exists(Path))
438
0
      return FS->isLocal(Path, Result);
439
0
  return errc::no_such_file_or_directory;
440
0
}
441
442
std::error_code
443
OverlayFileSystem::getRealPath(const Twine &Path,
444
4
                               SmallVectorImpl<char> &Output) const {
445
4
  for (auto &FS : FSList)
446
6
    if (FS->exists(Path))
447
3
      return FS->getRealPath(Path, Output);
448
4
  
return errc::no_such_file_or_directory1
;
449
4
}
450
451
415k
llvm::vfs::detail::DirIterImpl::~DirIterImpl() = default;
452
453
namespace {
454
455
class OverlayFSDirIterImpl : public llvm::vfs::detail::DirIterImpl {
456
  OverlayFileSystem &Overlays;
457
  std::string Path;
458
  OverlayFileSystem::iterator CurrentFS;
459
  directory_iterator CurrentDirIter;
460
  llvm::StringSet<> SeenNames;
461
462
53
  std::error_code incrementFS() {
463
53
    assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
464
53
    ++CurrentFS;
465
76
    for (auto E = Overlays.overlays_end(); CurrentFS != E; 
++CurrentFS23
) {
466
47
      std::error_code EC;
467
47
      CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
468
47
      if (EC && 
EC != errc::no_such_file_or_directory0
)
469
0
        return EC;
470
47
      if (CurrentDirIter != directory_iterator())
471
24
        break; // found
472
47
    }
473
53
    return {};
474
53
  }
475
476
93
  std::error_code incrementDirIter(bool IsFirstTime) {
477
93
    assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
478
93
           "incrementing past end");
479
93
    std::error_code EC;
480
93
    if (!IsFirstTime)
481
62
      CurrentDirIter.increment(EC);
482
93
    if (!EC && CurrentDirIter == directory_iterator())
483
53
      EC = incrementFS();
484
93
    return EC;
485
93
  }
486
487
81
  std::error_code incrementImpl(bool IsFirstTime) {
488
93
    while (true) {
489
93
      std::error_code EC = incrementDirIter(IsFirstTime);
490
93
      if (EC || CurrentDirIter == directory_iterator()) {
491
29
        CurrentEntry = directory_entry();
492
29
        return EC;
493
29
      }
494
64
      CurrentEntry = *CurrentDirIter;
495
64
      StringRef Name = llvm::sys::path::filename(CurrentEntry.path());
496
64
      if (SeenNames.insert(Name).second)
497
52
        return EC; // name not seen before
498
64
    }
499
81
    
llvm_unreachable0
("returned above");
500
81
  }
501
502
public:
503
  OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
504
                       std::error_code &EC)
505
31
      : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
506
31
    CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
507
31
    EC = incrementImpl(true);
508
31
  }
509
510
50
  std::error_code increment() override { return incrementImpl(false); }
511
};
512
513
} // namespace
514
515
directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
516
31
                                                std::error_code &EC) {
517
31
  return directory_iterator(
518
31
      std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
519
31
}
520
521
0
void ProxyFileSystem::anchor() {}
522
523
namespace llvm {
524
namespace vfs {
525
526
namespace detail {
527
528
enum InMemoryNodeKind { IME_File, IME_Directory, IME_HardLink };
529
530
/// The in memory file system is a tree of Nodes. Every node can either be a
531
/// file , hardlink or a directory.
532
class InMemoryNode {
533
  InMemoryNodeKind Kind;
534
  std::string FileName;
535
536
public:
537
  InMemoryNode(llvm::StringRef FileName, InMemoryNodeKind Kind)
538
191k
      : Kind(Kind), FileName(llvm::sys::path::filename(FileName)) {}
539
191k
  virtual ~InMemoryNode() = default;
540
541
  /// Get the filename of this node (the name without the directory part).
542
11
  StringRef getFileName() const { return FileName; }
543
2.21M
  InMemoryNodeKind getKind() const { return Kind; }
544
  virtual std::string toString(unsigned Indent) const = 0;
545
};
546
547
class InMemoryFile : public InMemoryNode {
548
  Status Stat;
549
  std::unique_ptr<llvm::MemoryBuffer> Buffer;
550
551
public:
552
  InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
553
      : InMemoryNode(Stat.getName(), IME_File), Stat(std::move(Stat)),
554
62.9k
        Buffer(std::move(Buffer)) {}
555
556
  /// Return the \p Status for this node. \p RequestedName should be the name
557
  /// through which the caller referred to this node. It will override
558
  /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
559
67.3k
  Status getStatus(const Twine &RequestedName) const {
560
67.3k
    return Status::copyWithNewName(Stat, RequestedName);
561
67.3k
  }
562
52.3k
  llvm::MemoryBuffer *getBuffer() const { return Buffer.get(); }
563
564
0
  std::string toString(unsigned Indent) const override {
565
0
    return (std::string(Indent, ' ') + Stat.getName() + "\n").str();
566
0
  }
567
568
1.09M
  static bool classof(const InMemoryNode *N) {
569
1.09M
    return N->getKind() == IME_File;
570
1.09M
  }
571
};
572
573
namespace {
574
575
class InMemoryHardLink : public InMemoryNode {
576
  const InMemoryFile &ResolvedFile;
577
578
public:
579
  InMemoryHardLink(StringRef Path, const InMemoryFile &ResolvedFile)
580
8
      : InMemoryNode(Path, IME_HardLink), ResolvedFile(ResolvedFile) {}
581
11
  const InMemoryFile &getResolvedFile() const { return ResolvedFile; }
582
583
0
  std::string toString(unsigned Indent) const override {
584
0
    return std::string(Indent, ' ') + "HardLink to -> " +
585
0
           ResolvedFile.toString(0);
586
0
  }
587
588
885k
  static bool classof(const InMemoryNode *N) {
589
885k
    return N->getKind() == IME_HardLink;
590
885k
  }
591
};
592
593
/// Adapt a InMemoryFile for VFS' File interface.  The goal is to make
594
/// \p InMemoryFileAdaptor mimic as much as possible the behavior of
595
/// \p RealFile.
596
class InMemoryFileAdaptor : public File {
597
  const InMemoryFile &Node;
598
  /// The name to use when returning a Status for this file.
599
  std::string RequestedName;
600
601
public:
602
  explicit InMemoryFileAdaptor(const InMemoryFile &Node,
603
                               std::string RequestedName)
604
51.6k
      : Node(Node), RequestedName(std::move(RequestedName)) {}
605
606
14.7k
  llvm::ErrorOr<Status> status() override {
607
14.7k
    return Node.getStatus(RequestedName);
608
14.7k
  }
609
610
  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
611
  getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
612
51.6k
            bool IsVolatile) override {
613
51.6k
    llvm::MemoryBuffer *Buf = Node.getBuffer();
614
51.6k
    return llvm::MemoryBuffer::getMemBuffer(
615
51.6k
        Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
616
51.6k
  }
617
618
0
  std::error_code close() override { return {}; }
619
};
620
} // namespace
621
622
class InMemoryDirectory : public InMemoryNode {
623
  Status Stat;
624
  llvm::StringMap<std::unique_ptr<InMemoryNode>> Entries;
625
626
public:
627
  InMemoryDirectory(Status Stat)
628
128k
      : InMemoryNode(Stat.getName(), IME_Directory), Stat(std::move(Stat)) {}
629
630
  /// Return the \p Status for this node. \p RequestedName should be the name
631
  /// through which the caller referred to this node. It will override
632
  /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
633
50.5k
  Status getStatus(const Twine &RequestedName) const {
634
50.5k
    return Status::copyWithNewName(Stat, RequestedName);
635
50.5k
  }
636
1.50M
  InMemoryNode *getChild(StringRef Name) {
637
1.50M
    auto I = Entries.find(Name);
638
1.50M
    if (I != Entries.end())
639
1.12M
      return I->second.get();
640
388k
    return nullptr;
641
388k
  }
642
643
140k
  InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
644
140k
    return Entries.insert(make_pair(Name, std::move(Child)))
645
140k
        .first->second.get();
646
140k
  }
647
648
  using const_iterator = decltype(Entries)::const_iterator;
649
650
9
  const_iterator begin() const { return Entries.begin(); }
651
9
  const_iterator end() const { return Entries.end(); }
652
653
0
  std::string toString(unsigned Indent) const override {
654
0
    std::string Result =
655
0
        (std::string(Indent, ' ') + Stat.getName() + "\n").str();
656
0
    for (const auto &Entry : Entries)
657
0
      Result += Entry.second->toString(Indent + 2);
658
0
    return Result;
659
0
  }
660
661
234k
  static bool classof(const InMemoryNode *N) {
662
234k
    return N->getKind() == IME_Directory;
663
234k
  }
664
};
665
666
namespace {
667
103k
Status getNodeStatus(const InMemoryNode *Node, const Twine &RequestedName) {
668
103k
  if (auto Dir = dyn_cast<detail::InMemoryDirectory>(Node))
669
50.5k
    return Dir->getStatus(RequestedName);
670
52.6k
  if (auto File = dyn_cast<detail::InMemoryFile>(Node))
671
52.6k
    return File->getStatus(RequestedName);
672
0
  if (auto Link = dyn_cast<detail::InMemoryHardLink>(Node))
673
0
    return Link->getResolvedFile().getStatus(RequestedName);
674
0
  llvm_unreachable("Unknown node type");
675
0
}
676
} // namespace
677
} // namespace detail
678
679
InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
680
    : Root(new detail::InMemoryDirectory(
681
          Status("", getNextVirtualUniqueID(), llvm::sys::TimePoint<>(), 0, 0,
682
                 0, llvm::sys::fs::file_type::directory_file,
683
                 llvm::sys::fs::perms::all_all))),
684
50.7k
      UseNormalizedPaths(UseNormalizedPaths) {}
685
686
50.7k
InMemoryFileSystem::~InMemoryFileSystem() = default;
687
688
0
std::string InMemoryFileSystem::toString() const {
689
0
  return Root->toString(/*Indent=*/0);
690
0
}
691
692
bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
693
                                 std::unique_ptr<llvm::MemoryBuffer> Buffer,
694
                                 Optional<uint32_t> User,
695
                                 Optional<uint32_t> Group,
696
                                 Optional<llvm::sys::fs::file_type> Type,
697
                                 Optional<llvm::sys::fs::perms> Perms,
698
63.6k
                                 const detail::InMemoryFile *HardLinkTarget) {
699
63.6k
  SmallString<128> Path;
700
63.6k
  P.toVector(Path);
701
63.6k
702
63.6k
  // Fix up relative paths. This just prepends the current working directory.
703
63.6k
  std::error_code EC = makeAbsolute(Path);
704
63.6k
  assert(!EC);
705
63.6k
  (void)EC;
706
63.6k
707
63.6k
  if (useNormalizedPaths())
708
63.6k
    llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
709
63.6k
710
63.6k
  if (Path.empty())
711
0
    return false;
712
63.6k
713
63.6k
  detail::InMemoryDirectory *Dir = Root.get();
714
63.6k
  auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path);
715
63.6k
  const auto ResolvedUser = User.getValueOr(0);
716
63.6k
  const auto ResolvedGroup = Group.getValueOr(0);
717
63.6k
  const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file);
718
63.6k
  const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all);
719
63.6k
  assert(!(HardLinkTarget && Buffer) && "HardLink cannot have a buffer");
720
63.6k
  // Any intermediate directories we create should be accessible by
721
63.6k
  // the owner, even if Perms says otherwise for the final path.
722
63.6k
  const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
723
271k
  while (true) {
724
271k
    StringRef Name = *I;
725
271k
    detail::InMemoryNode *Node = Dir->getChild(Name);
726
271k
    ++I;
727
271k
    if (!Node) {
728
140k
      if (I == E) {
729
62.9k
        // End of the path.
730
62.9k
        std::unique_ptr<detail::InMemoryNode> Child;
731
62.9k
        if (HardLinkTarget)
732
8
          Child.reset(new detail::InMemoryHardLink(P.str(), *HardLinkTarget));
733
62.9k
        else {
734
62.9k
          // Create a new file or directory.
735
62.9k
          Status Stat(P.str(), getNextVirtualUniqueID(),
736
62.9k
                      llvm::sys::toTimePoint(ModificationTime), ResolvedUser,
737
62.9k
                      ResolvedGroup, Buffer->getBufferSize(), ResolvedType,
738
62.9k
                      ResolvedPerms);
739
62.9k
          if (ResolvedType == sys::fs::file_type::directory_file) {
740
9
            Child.reset(new detail::InMemoryDirectory(std::move(Stat)));
741
62.9k
          } else {
742
62.9k
            Child.reset(
743
62.9k
                new detail::InMemoryFile(std::move(Stat), std::move(Buffer)));
744
62.9k
          }
745
62.9k
        }
746
62.9k
        Dir->addChild(Name, std::move(Child));
747
62.9k
        return true;
748
62.9k
      }
749
77.5k
750
77.5k
      // Create a new directory. Use the path up to here.
751
77.5k
      Status Stat(
752
77.5k
          StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
753
77.5k
          getNextVirtualUniqueID(), llvm::sys::toTimePoint(ModificationTime),
754
77.5k
          ResolvedUser, ResolvedGroup, 0, sys::fs::file_type::directory_file,
755
77.5k
          NewDirectoryPerms);
756
77.5k
      Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
757
77.5k
          Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
758
77.5k
      continue;
759
77.5k
    }
760
131k
761
131k
    if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
762
130k
      Dir = NewDir;
763
130k
    } else {
764
676
      assert((isa<detail::InMemoryFile>(Node) ||
765
676
              isa<detail::InMemoryHardLink>(Node)) &&
766
676
             "Must be either file, hardlink or directory!");
767
676
768
676
      // Trying to insert a directory in place of a file.
769
676
      if (I != E)
770
2
        return false;
771
674
772
674
      // Return false only if the new file is different from the existing one.
773
674
      if (auto Link = dyn_cast<detail::InMemoryHardLink>(Node)) {
774
2
        return Link->getResolvedFile().getBuffer()->getBuffer() ==
775
2
               Buffer->getBuffer();
776
2
      }
777
672
      return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
778
672
             Buffer->getBuffer();
779
672
    }
780
131k
  }
781
63.6k
}
782
783
bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
784
                                 std::unique_ptr<llvm::MemoryBuffer> Buffer,
785
                                 Optional<uint32_t> User,
786
                                 Optional<uint32_t> Group,
787
                                 Optional<llvm::sys::fs::file_type> Type,
788
63.6k
                                 Optional<llvm::sys::fs::perms> Perms) {
789
63.6k
  return addFile(P, ModificationTime, std::move(Buffer), User, Group, Type,
790
63.6k
                 Perms, /*HardLinkTarget=*/nullptr);
791
63.6k
}
792
793
bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
794
                                      llvm::MemoryBuffer *Buffer,
795
                                      Optional<uint32_t> User,
796
                                      Optional<uint32_t> Group,
797
                                      Optional<llvm::sys::fs::file_type> Type,
798
279
                                      Optional<llvm::sys::fs::perms> Perms) {
799
279
  return addFile(P, ModificationTime,
800
279
                 llvm::MemoryBuffer::getMemBuffer(
801
279
                     Buffer->getBuffer(), Buffer->getBufferIdentifier()),
802
279
                 std::move(User), std::move(Group), std::move(Type),
803
279
                 std::move(Perms));
804
279
}
805
806
static ErrorOr<const detail::InMemoryNode *>
807
lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
808
403k
                   const Twine &P) {
809
403k
  SmallString<128> Path;
810
403k
  P.toVector(Path);
811
403k
812
403k
  // Fix up relative paths. This just prepends the current working directory.
813
403k
  std::error_code EC = FS.makeAbsolute(Path);
814
403k
  assert(!EC);
815
403k
  (void)EC;
816
403k
817
403k
  if (FS.useNormalizedPaths())
818
403k
    llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
819
403k
820
403k
  if (Path.empty())
821
42.7k
    return Dir;
822
360k
823
360k
  auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
824
1.23M
  while (
true1.23M
) {
825
1.23M
    detail::InMemoryNode *Node = Dir->getChild(*I);
826
1.23M
    ++I;
827
1.23M
    if (!Node)
828
248k
      return errc::no_such_file_or_directory;
829
989k
830
989k
    // Return the file if it's at the end of the path.
831
989k
    if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
832
104k
      if (I == E)
833
104k
        return File;
834
1
      return errc::no_such_file_or_directory;
835
1
    }
836
884k
837
884k
    // If Node is HardLink then return the resolved file.
838
884k
    if (auto File = dyn_cast<detail::InMemoryHardLink>(Node)) {
839
9
      if (I == E)
840
9
        return &File->getResolvedFile();
841
0
      return errc::no_such_file_or_directory;
842
0
    }
843
884k
    // Traverse directories.
844
884k
    Dir = cast<detail::InMemoryDirectory>(Node);
845
884k
    if (I == E)
846
7.77k
      return Dir;
847
884k
  }
848
360k
}
849
850
bool InMemoryFileSystem::addHardLink(const Twine &FromPath,
851
14
                                     const Twine &ToPath) {
852
14
  auto FromNode = lookupInMemoryNode(*this, Root.get(), FromPath);
853
14
  auto ToNode = lookupInMemoryNode(*this, Root.get(), ToPath);
854
14
  // FromPath must not have been added before. ToPath must have been added
855
14
  // before. Resolved ToPath must be a File.
856
14
  if (!ToNode || 
FromNode13
||
!isa<detail::InMemoryFile>(*ToNode)10
)
857
5
    return false;
858
9
  return this->addFile(FromPath, 0, nullptr, None, None, None, None,
859
9
                       cast<detail::InMemoryFile>(*ToNode));
860
9
}
861
862
287k
llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
863
287k
  auto Node = lookupInMemoryNode(*this, Root.get(), Path);
864
287k
  if (Node)
865
103k
    return detail::getNodeStatus(*Node, Path);
866
184k
  return Node.getError();
867
184k
}
868
869
llvm::ErrorOr<std::unique_ptr<File>>
870
115k
InMemoryFileSystem::openFileForRead(const Twine &Path) {
871
115k
  auto Node = lookupInMemoryNode(*this, Root.get(), Path);
872
115k
  if (!Node)
873
64.2k
    return Node.getError();
874
51.6k
875
51.6k
  // When we have a file provide a heap-allocated wrapper for the memory buffer
876
51.6k
  // to match the ownership semantics for File.
877
51.6k
  if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
878
51.6k
    return std::unique_ptr<File>(
879
51.6k
        new detail::InMemoryFileAdaptor(*F, Path.str()));
880
18.4E
881
18.4E
  // FIXME: errc::not_a_file?
882
18.4E
  return make_error_code(llvm::errc::invalid_argument);
883
18.4E
}
884
885
namespace {
886
887
/// Adaptor from InMemoryDir::iterator to directory_iterator.
888
class InMemoryDirIterator : public llvm::vfs::detail::DirIterImpl {
889
  detail::InMemoryDirectory::const_iterator I;
890
  detail::InMemoryDirectory::const_iterator E;
891
  std::string RequestedDirName;
892
893
19
  void setCurrentEntry() {
894
19
    if (I != E) {
895
11
      SmallString<256> Path(RequestedDirName);
896
11
      llvm::sys::path::append(Path, I->second->getFileName());
897
11
      sys::fs::file_type Type;
898
11
      switch (I->second->getKind()) {
899
11
      case detail::IME_File:
900
6
      case detail::IME_HardLink:
901
6
        Type = sys::fs::file_type::regular_file;
902
6
        break;
903
6
      case detail::IME_Directory:
904
5
        Type = sys::fs::file_type::directory_file;
905
5
        break;
906
11
      }
907
11
      CurrentEntry = directory_entry(Path.str(), Type);
908
11
    } else {
909
8
      // When we're at the end, make CurrentEntry invalid and DirIterImpl will
910
8
      // do the rest.
911
8
      CurrentEntry = directory_entry();
912
8
    }
913
19
  }
914
915
public:
916
46
  InMemoryDirIterator() = default;
917
918
  explicit InMemoryDirIterator(const detail::InMemoryDirectory &Dir,
919
                               std::string RequestedDirName)
920
      : I(Dir.begin()), E(Dir.end()),
921
9
        RequestedDirName(std::move(RequestedDirName)) {
922
9
    setCurrentEntry();
923
9
  }
924
925
10
  std::error_code increment() override {
926
10
    ++I;
927
10
    setCurrentEntry();
928
10
    return {};
929
10
  }
930
};
931
932
} // namespace
933
934
directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
935
55
                                                 std::error_code &EC) {
936
55
  auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
937
55
  if (!Node) {
938
46
    EC = Node.getError();
939
46
    return directory_iterator(std::make_shared<InMemoryDirIterator>());
940
46
  }
941
9
942
9
  if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
943
9
    return directory_iterator(
944
9
        std::make_shared<InMemoryDirIterator>(*DirNode, Dir.str()));
945
0
946
0
  EC = make_error_code(llvm::errc::not_a_directory);
947
0
  return directory_iterator(std::make_shared<InMemoryDirIterator>());
948
0
}
949
950
7.93k
std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
951
7.93k
  SmallString<128> Path;
952
7.93k
  P.toVector(Path);
953
7.93k
954
7.93k
  // Fix up relative paths. This just prepends the current working directory.
955
7.93k
  std::error_code EC = makeAbsolute(Path);
956
7.93k
  assert(!EC);
957
7.93k
  (void)EC;
958
7.93k
959
7.93k
  if (useNormalizedPaths())
960
7.93k
    llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
961
7.93k
962
7.93k
  if (!Path.empty())
963
7.93k
    WorkingDirectory = Path.str();
964
7.93k
  return {};
965
7.93k
}
966
967
std::error_code
968
InMemoryFileSystem::getRealPath(const Twine &Path,
969
8
                                SmallVectorImpl<char> &Output) const {
970
8
  auto CWD = getCurrentWorkingDirectory();
971
8
  if (!CWD || CWD->empty())
972
1
    return errc::operation_not_permitted;
973
7
  Path.toVector(Output);
974
7
  if (auto EC = makeAbsolute(Output))
975
0
    return EC;
976
7
  llvm::sys::path::remove_dots(Output, /*remove_dot_dot=*/true);
977
7
  return {};
978
7
}
979
980
2
std::error_code InMemoryFileSystem::isLocal(const Twine &Path, bool &Result) {
981
2
  Result = false;
982
2
  return {};
983
2
}
984
985
} // namespace vfs
986
} // namespace llvm
987
988
//===-----------------------------------------------------------------------===/
989
// RedirectingFileSystem implementation
990
//===-----------------------------------------------------------------------===/
991
992
// FIXME: reuse implementation common with OverlayFSDirIterImpl as these
993
// iterators are conceptually similar.
994
class llvm::vfs::VFSFromYamlDirIterImpl
995
    : public llvm::vfs::detail::DirIterImpl {
996
  std::string Dir;
997
  RedirectingFileSystem::RedirectingDirectoryEntry::iterator Current, End;
998
999
  // To handle 'fallthrough' mode we need to iterate at first through
1000
  // RedirectingDirectoryEntry and then through ExternalFS. These operations are
1001
  // done sequentially, we just need to keep a track of what kind of iteration
1002
  // we are currently performing.
1003
1004
  /// Flag telling if we should iterate through ExternalFS or stop at the last
1005
  /// RedirectingDirectoryEntry::iterator.
1006
  bool IterateExternalFS;
1007
  /// Flag telling if we have switched to iterating through ExternalFS.
1008
  bool IsExternalFSCurrent = false;
1009
  FileSystem &ExternalFS;
1010
  directory_iterator ExternalDirIter;
1011
  llvm::StringSet<> SeenNames;
1012
1013
  /// To combine multiple iterations, different methods are responsible for
1014
  /// different iteration steps.
1015
  /// @{
1016
1017
  /// Responsible for dispatching between RedirectingDirectoryEntry iteration
1018
  /// and ExternalFS iteration.
1019
  std::error_code incrementImpl(bool IsFirstTime);
1020
  /// Responsible for RedirectingDirectoryEntry iteration.
1021
  std::error_code incrementContent(bool IsFirstTime);
1022
  /// Responsible for ExternalFS iteration.
1023
  std::error_code incrementExternal();
1024
  /// @}
1025
1026
public:
1027
  VFSFromYamlDirIterImpl(
1028
      const Twine &Path,
1029
      RedirectingFileSystem::RedirectingDirectoryEntry::iterator Begin,
1030
      RedirectingFileSystem::RedirectingDirectoryEntry::iterator End,
1031
      bool IterateExternalFS, FileSystem &ExternalFS, std::error_code &EC);
1032
1033
  std::error_code increment() override;
1034
};
1035
1036
llvm::ErrorOr<std::string>
1037
109
RedirectingFileSystem::getCurrentWorkingDirectory() const {
1038
109
  return ExternalFS->getCurrentWorkingDirectory();
1039
109
}
1040
1041
std::error_code
1042
6
RedirectingFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
1043
6
  return ExternalFS->setCurrentWorkingDirectory(Path);
1044
6
}
1045
1046
std::error_code RedirectingFileSystem::isLocal(const Twine &Path,
1047
0
                                               bool &Result) {
1048
0
  return ExternalFS->isLocal(Path, Result);
1049
0
}
1050
1051
directory_iterator RedirectingFileSystem::dir_begin(const Twine &Dir,
1052
39
                                                    std::error_code &EC) {
1053
39
  ErrorOr<RedirectingFileSystem::Entry *> E = lookupPath(Dir);
1054
39
  if (!E) {
1055
14
    EC = E.getError();
1056
14
    if (IsFallthrough && EC == errc::no_such_file_or_directory)
1057
14
      return ExternalFS->dir_begin(Dir, EC);
1058
0
    return {};
1059
0
  }
1060
25
  ErrorOr<Status> S = status(Dir, *E);
1061
25
  if (!S) {
1062
0
    EC = S.getError();
1063
0
    return {};
1064
0
  }
1065
25
  if (!S->isDirectory()) {
1066
0
    EC = std::error_code(static_cast<int>(errc::not_a_directory),
1067
0
                         std::system_category());
1068
0
    return {};
1069
0
  }
1070
25
1071
25
  auto *D = cast<RedirectingFileSystem::RedirectingDirectoryEntry>(*E);
1072
25
  return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(
1073
25
      Dir, D->contents_begin(), D->contents_end(),
1074
25
      /*IterateExternalFS=*/IsFallthrough, *ExternalFS, EC));
1075
25
}
1076
1077
63
void RedirectingFileSystem::setExternalContentsPrefixDir(StringRef PrefixDir) {
1078
63
  ExternalContentsPrefixDir = PrefixDir.str();
1079
63
}
1080
1081
32
StringRef RedirectingFileSystem::getExternalContentsPrefixDir() const {
1082
32
  return ExternalContentsPrefixDir;
1083
32
}
1084
1085
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1086
LLVM_DUMP_METHOD void RedirectingFileSystem::dump() const {
1087
  for (const auto &Root : Roots)
1088
    dumpEntry(Root.get());
1089
}
1090
1091
LLVM_DUMP_METHOD void
1092
RedirectingFileSystem::dumpEntry(RedirectingFileSystem::Entry *E,
1093
                                 int NumSpaces) const {
1094
  StringRef Name = E->getName();
1095
  for (int i = 0, e = NumSpaces; i < e; ++i)
1096
    dbgs() << " ";
1097
  dbgs() << "'" << Name.str().c_str() << "'"
1098
         << "\n";
1099
1100
  if (E->getKind() == RedirectingFileSystem::EK_Directory) {
1101
    auto *DE = dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(E);
1102
    assert(DE && "Should be a directory");
1103
1104
    for (std::unique_ptr<Entry> &SubEntry :
1105
         llvm::make_range(DE->contents_begin(), DE->contents_end()))
1106
      dumpEntry(SubEntry.get(), NumSpaces + 2);
1107
  }
1108
}
1109
#endif
1110
1111
/// A helper class to hold the common YAML parsing state.
1112
class llvm::vfs::RedirectingFileSystemParser {
1113
  yaml::Stream &Stream;
1114
1115
30
  void error(yaml::Node *N, const Twine &Msg) { Stream.printError(N, Msg); }
1116
1117
  // false on error
1118
  bool parseScalarString(yaml::Node *N, StringRef &Result,
1119
3.88k
                         SmallVectorImpl<char> &Storage) {
1120
3.88k
    const auto *S = dyn_cast<yaml::ScalarNode>(N);
1121
3.88k
1122
3.88k
    if (!S) {
1123
3
      error(N, "expected string");
1124
3
      return false;
1125
3
    }
1126
3.87k
    Result = S->getValue(Storage);
1127
3.87k
    return true;
1128
3.87k
  }
1129
1130
  // false on error
1131
56
  bool parseScalarBool(yaml::Node *N, bool &Result) {
1132
56
    SmallString<5> Storage;
1133
56
    StringRef Value;
1134
56
    if (!parseScalarString(N, Value, Storage))
1135
0
      return false;
1136
56
1137
56
    if (Value.equals_lower("true") || 
Value.equals_lower("on")37
||
1138
56
        
Value.equals_lower("yes")37
||
Value == "1"37
) {
1139
19
      Result = true;
1140
19
      return true;
1141
37
    } else if (Value.equals_lower("false") || 
Value.equals_lower("off")2
||
1142
37
               
Value.equals_lower("no")2
||
Value == "0"2
) {
1143
35
      Result = false;
1144
35
      return true;
1145
35
    }
1146
2
1147
2
    error(N, "expected boolean value");
1148
2
    return false;
1149
2
  }
1150
1151
  struct KeyStatus {
1152
    bool Required;
1153
    bool Seen = false;
1154
1155
3.71k
    KeyStatus(bool Required = false) : Required(Required) {}
1156
  };
1157
1158
  using KeyStatusPair = std::pair<StringRef, KeyStatus>;
1159
1160
  // false on error
1161
  bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1162
2.09k
                                  DenseMap<StringRef, KeyStatus> &Keys) {
1163
2.09k
    if (!Keys.count(Key)) {
1164
4
      error(KeyNode, "unknown key");
1165
4
      return false;
1166
4
    }
1167
2.09k
    KeyStatus &S = Keys[Key];
1168
2.09k
    if (S.Seen) {
1169
3
      error(KeyNode, Twine("duplicate key '") + Key + "'");
1170
3
      return false;
1171
3
    }
1172
2.08k
    S.Seen = true;
1173
2.08k
    return true;
1174
2.08k
  }
1175
1176
  // false on error
1177
679
  bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
1178
3.46k
    for (const auto &I : Keys) {
1179
3.46k
      if (I.second.Required && 
!I.second.Seen1.35k
) {
1180
4
        error(Obj, Twine("missing key '") + I.first + "'");
1181
4
        return false;
1182
4
      }
1183
3.46k
    }
1184
679
    
return true675
;
1185
679
  }
1186
1187
  RedirectingFileSystem::Entry *
1188
  lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1189
1.31k
                      RedirectingFileSystem::Entry *ParentEntry = nullptr) {
1190
1.31k
    if (!ParentEntry) { // Look for a existent root
1191
107
      for (const auto &Root : FS->Roots) {
1192
32
        if (Name.equals(Root->getName())) {
1193
31
          ParentEntry = Root.get();
1194
31
          return ParentEntry;
1195
31
        }
1196
32
      }
1197
1.20k
    } else { // Advance to the next component
1198
1.20k
      auto *DE = dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(
1199
1.20k
          ParentEntry);
1200
1.20k
      for (std::unique_ptr<RedirectingFileSystem::Entry> &Content :
1201
1.20k
           llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1202
679
        auto *DirContent =
1203
679
            dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(
1204
679
                Content.get());
1205
679
        if (DirContent && 
Name.equals(Content->getName())367
)
1206
216
          return DirContent;
1207
679
      }
1208
1.20k
    }
1209
1.31k
1210
1.31k
    // ... or create a new one
1211
1.31k
    std::unique_ptr<RedirectingFileSystem::Entry> E =
1212
1.06k
        llvm::make_unique<RedirectingFileSystem::RedirectingDirectoryEntry>(
1213
1.06k
            Name, Status("", getNextVirtualUniqueID(),
1214
1.06k
                         std::chrono::system_clock::now(), 0, 0, 0,
1215
1.06k
                         file_type::directory_file, sys::fs::all_all));
1216
1.06k
1217
1.06k
    if (!ParentEntry) { // Add a new root to the overlay
1218
76
      FS->Roots.push_back(std::move(E));
1219
76
      ParentEntry = FS->Roots.back().get();
1220
76
      return ParentEntry;
1221
76
    }
1222
989
1223
989
    auto *DE =
1224
989
        dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(ParentEntry);
1225
989
    DE->addContent(std::move(E));
1226
989
    return DE->getLastContent();
1227
989
  }
1228
1229
  void uniqueOverlayTree(RedirectingFileSystem *FS,
1230
                         RedirectingFileSystem::Entry *SrcE,
1231
1.71k
                         RedirectingFileSystem::Entry *NewParentE = nullptr) {
1232
1.71k
    StringRef Name = SrcE->getName();
1233
1.71k
    switch (SrcE->getKind()) {
1234
1.71k
    case RedirectingFileSystem::EK_Directory: {
1235
1.31k
      auto *DE =
1236
1.31k
          dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(SrcE);
1237
1.31k
      assert(DE && "Must be a directory");
1238
1.31k
      // Empty directories could be present in the YAML as a way to
1239
1.31k
      // describe a file for a current directory after some of its subdir
1240
1.31k
      // is parsed. This only leads to redundant walks, ignore it.
1241
1.31k
      if (!Name.empty())
1242
1.31k
        NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1243
1.31k
      for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
1244
1.31k
           llvm::make_range(DE->contents_begin(), DE->contents_end()))
1245
1.60k
        uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1246
1.31k
      break;
1247
1.71k
    }
1248
1.71k
    case RedirectingFileSystem::EK_File: {
1249
397
      auto *FE = dyn_cast<RedirectingFileSystem::RedirectingFileEntry>(SrcE);
1250
397
      assert(FE && "Must be a file");
1251
397
      assert(NewParentE && "Parent entry must exist");
1252
397
      auto *DE = dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(
1253
397
          NewParentE);
1254
397
      DE->addContent(
1255
397
          llvm::make_unique<RedirectingFileSystem::RedirectingFileEntry>(
1256
397
              Name, FE->getExternalContentsPath(), FE->getUseName()));
1257
397
      break;
1258
1.71k
    }
1259
1.71k
    }
1260
1.71k
  }
1261
1262
  std::unique_ptr<RedirectingFileSystem::Entry>
1263
615
  parseEntry(yaml::Node *N, RedirectingFileSystem *FS, bool IsRootEntry) {
1264
615
    auto *M = dyn_cast<yaml::MappingNode>(N);
1265
615
    if (!M) {
1266
2
      error(N, "expected mapping node for file or directory entry");
1267
2
      return nullptr;
1268
2
    }
1269
613
1270
613
    KeyStatusPair Fields[] = {
1271
613
        KeyStatusPair("name", true),
1272
613
        KeyStatusPair("type", true),
1273
613
        KeyStatusPair("contents", false),
1274
613
        KeyStatusPair("external-contents", false),
1275
613
        KeyStatusPair("use-external-name", false),
1276
613
    };
1277
613
1278
613
    DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
1279
613
1280
613
    bool HasContents = false; // external or otherwise
1281
613
    std::vector<std::unique_ptr<RedirectingFileSystem::Entry>>
1282
613
        EntryArrayContents;
1283
613
    std::string ExternalContentsPath;
1284
613
    std::string Name;
1285
613
    yaml::Node *NameValueNode = nullptr;
1286
613
    auto UseExternalName =
1287
613
        RedirectingFileSystem::RedirectingFileEntry::NK_NotSet;
1288
613
    RedirectingFileSystem::EntryKind Kind;
1289
613
1290
1.83k
    for (auto &I : *M) {
1291
1.83k
      StringRef Key;
1292
1.83k
      // Reuse the buffer for key and value, since we don't look at key after
1293
1.83k
      // parsing value.
1294
1.83k
      SmallString<256> Buffer;
1295
1.83k
      if (!parseScalarString(I.getKey(), Key, Buffer))
1296
0
        return nullptr;
1297
1.83k
1298
1.83k
      if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
1299
2
        return nullptr;
1300
1.83k
1301
1.83k
      StringRef Value;
1302
1.83k
      if (Key == "name") {
1303
610
        if (!parseScalarString(I.getValue(), Value, Buffer))
1304
1
          return nullptr;
1305
609
1306
609
        NameValueNode = I.getValue();
1307
609
        if (FS->UseCanonicalizedPaths) {
1308
609
          SmallString<256> Path(Value);
1309
609
          // Guarantee that old YAML files containing paths with ".." and "."
1310
609
          // are properly canonicalized before read into the VFS.
1311
609
          Path = sys::path::remove_leading_dotslash(Path);
1312
609
          sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1313
609
          Name = Path.str();
1314
609
        } else {
1315
0
          Name = Value;
1316
0
        }
1317
1.22k
      } else if (Key == "type") {
1318
609
        if (!parseScalarString(I.getValue(), Value, Buffer))
1319
0
          return nullptr;
1320
609
        if (Value == "file")
1321
404
          Kind = RedirectingFileSystem::EK_File;
1322
205
        else if (Value == "directory")
1323
204
          Kind = RedirectingFileSystem::EK_Directory;
1324
1
        else {
1325
1
          error(I.getValue(), "unknown value for 'type'");
1326
1
          return nullptr;
1327
1
        }
1328
612
      } else if (Key == "contents") {
1329
205
        if (HasContents) {
1330
0
          error(I.getKey(),
1331
0
                "entry already has 'contents' or 'external-contents'");
1332
0
          return nullptr;
1333
0
        }
1334
205
        HasContents = true;
1335
205
        auto *Contents = dyn_cast<yaml::SequenceNode>(I.getValue());
1336
205
        if (!Contents) {
1337
2
          // FIXME: this is only for directories, what about files?
1338
2
          error(I.getValue(), "expected array");
1339
2
          return nullptr;
1340
2
        }
1341
203
1342
491
        
for (auto &I : *Contents)203
{
1343
491
          if (std::unique_ptr<RedirectingFileSystem::Entry> E =
1344
490
                  parseEntry(&I, FS, /*IsRootEntry*/ false))
1345
490
            EntryArrayContents.push_back(std::move(E));
1346
1
          else
1347
1
            return nullptr;
1348
491
        }
1349
407
      } else if (Key == "external-contents") {
1350
403
        if (HasContents) {
1351
0
          error(I.getKey(),
1352
0
                "entry already has 'contents' or 'external-contents'");
1353
0
          return nullptr;
1354
0
        }
1355
403
        HasContents = true;
1356
403
        if (!parseScalarString(I.getValue(), Value, Buffer))
1357
2
          return nullptr;
1358
401
1359
401
        SmallString<256> FullPath;
1360
401
        if (FS->IsRelativeOverlay) {
1361
32
          FullPath = FS->getExternalContentsPrefixDir();
1362
32
          assert(!FullPath.empty() &&
1363
32
                 "External contents prefix directory must exist");
1364
32
          llvm::sys::path::append(FullPath, Value);
1365
369
        } else {
1366
369
          FullPath = Value;
1367
369
        }
1368
401
1369
401
        if (FS->UseCanonicalizedPaths) {
1370
401
          // Guarantee that old YAML files containing paths with ".." and "."
1371
401
          // are properly canonicalized before read into the VFS.
1372
401
          FullPath = sys::path::remove_leading_dotslash(FullPath);
1373
401
          sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
1374
401
        }
1375
401
        ExternalContentsPath = FullPath.str();
1376
401
      } else 
if (4
Key == "use-external-name"4
) {
1377
4
        bool Val;
1378
4
        if (!parseScalarBool(I.getValue(), Val))
1379
0
          return nullptr;
1380
4
        UseExternalName =
1381
4
            Val ? 
RedirectingFileSystem::RedirectingFileEntry::NK_External2
1382
4
                : 
RedirectingFileSystem::RedirectingFileEntry::NK_Virtual2
;
1383
4
      } else {
1384
0
        llvm_unreachable("key missing from Keys");
1385
0
      }
1386
1.83k
    }
1387
613
1388
613
    
if (604
Stream.failed()604
)
1389
0
      return nullptr;
1390
604
1391
604
    // check for missing keys
1392
604
    if (!HasContents) {
1393
1
      error(N, "missing key 'contents' or 'external-contents'");
1394
1
      return nullptr;
1395
1
    }
1396
603
    if (!checkMissingKeys(N, Keys))
1397
3
      return nullptr;
1398
600
1399
600
    // check invalid configuration
1400
600
    if (Kind == RedirectingFileSystem::EK_Directory &&
1401
600
        UseExternalName !=
1402
201
            RedirectingFileSystem::RedirectingFileEntry::NK_NotSet) {
1403
0
      error(N, "'use-external-name' is not supported for directories");
1404
0
      return nullptr;
1405
0
    }
1406
600
1407
600
    if (IsRootEntry && 
!sys::path::is_absolute(Name)110
) {
1408
3
      assert(NameValueNode && "Name presence should be checked earlier");
1409
3
      error(NameValueNode,
1410
3
            "entry with relative path at the root level is not discoverable");
1411
3
      return nullptr;
1412
3
    }
1413
597
1414
597
    // Remove trailing slash(es), being careful not to remove the root path
1415
597
    StringRef Trimmed(Name);
1416
597
    size_t RootPathLen = sys::path::root_path(Trimmed).size();
1417
597
    while (Trimmed.size() > RootPathLen &&
1418
597
           
sys::path::is_separator(Trimmed.back())582
)
1419
0
      Trimmed = Trimmed.slice(0, Trimmed.size() - 1);
1420
597
    // Get the last component
1421
597
    StringRef LastComponent = sys::path::filename(Trimmed);
1422
597
1423
597
    std::unique_ptr<RedirectingFileSystem::Entry> Result;
1424
597
    switch (Kind) {
1425
597
    case RedirectingFileSystem::EK_File:
1426
397
      Result = llvm::make_unique<RedirectingFileSystem::RedirectingFileEntry>(
1427
397
          LastComponent, std::move(ExternalContentsPath), UseExternalName);
1428
397
      break;
1429
597
    case RedirectingFileSystem::EK_Directory:
1430
200
      Result =
1431
200
          llvm::make_unique<RedirectingFileSystem::RedirectingDirectoryEntry>(
1432
200
              LastComponent, std::move(EntryArrayContents),
1433
200
              Status("", getNextVirtualUniqueID(),
1434
200
                     std::chrono::system_clock::now(), 0, 0, 0,
1435
200
                     file_type::directory_file, sys::fs::all_all));
1436
200
      break;
1437
597
    }
1438
597
1439
597
    StringRef Parent = sys::path::parent_path(Trimmed);
1440
597
    if (Parent.empty())
1441
431
      return Result;
1442
166
1443
166
    // if 'name' contains multiple components, create implicit directory entries
1444
166
    for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1445
166
                                     E = sys::path::rend(Parent);
1446
1.28k
         I != E; 
++I1.11k
) {
1447
1.11k
      std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> Entries;
1448
1.11k
      Entries.push_back(std::move(Result));
1449
1.11k
      Result =
1450
1.11k
          llvm::make_unique<RedirectingFileSystem::RedirectingDirectoryEntry>(
1451
1.11k
              *I, std::move(Entries),
1452
1.11k
              Status("", getNextVirtualUniqueID(),
1453
1.11k
                     std::chrono::system_clock::now(), 0, 0, 0,
1454
1.11k
                     file_type::directory_file, sys::fs::all_all));
1455
1.11k
    }
1456
166
    return Result;
1457
166
  }
1458
1459
public:
1460
109
  RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
1461
1462
  // false on error
1463
109
  bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
1464
109
    auto *Top = dyn_cast<yaml::MappingNode>(Root);
1465
109
    if (!Top) {
1466
0
      error(Root, "expected mapping node");
1467
0
      return false;
1468
0
    }
1469
109
1470
109
    KeyStatusPair Fields[] = {
1471
109
        KeyStatusPair("version", true),
1472
109
        KeyStatusPair("case-sensitive", false),
1473
109
        KeyStatusPair("use-external-names", false),
1474
109
        KeyStatusPair("overlay-relative", false),
1475
109
        KeyStatusPair("fallthrough", false),
1476
109
        KeyStatusPair("roots", true),
1477
109
    };
1478
109
1479
109
    DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
1480
109
    std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> RootEntries;
1481
109
1482
109
    // Parse configuration and 'roots'
1483
262
    for (auto &I : *Top) {
1484
262
      SmallString<10> KeyBuffer;
1485
262
      StringRef Key;
1486
262
      if (!parseScalarString(I.getKey(), Key, KeyBuffer))
1487
0
        return false;
1488
262
1489
262
      if (!checkDuplicateOrUnknownKey(I.getKey(), Key, Keys))
1490
5
        return false;
1491
257
1492
257
      if (Key == "roots") {
1493
97
        auto *Roots = dyn_cast<yaml::SequenceNode>(I.getValue());
1494
97
        if (!Roots) {
1495
2
          error(I.getValue(), "expected array");
1496
2
          return false;
1497
2
        }
1498
95
1499
124
        
for (auto &I : *Roots)95
{
1500
124
          if (std::unique_ptr<RedirectingFileSystem::Entry> E =
1501
107
                  parseEntry(&I, FS, /*IsRootEntry*/ true))
1502
107
            RootEntries.push_back(std::move(E));
1503
17
          else
1504
17
            return false;
1505
124
        }
1506
160
      } else if (Key == "version") {
1507
108
        StringRef VersionString;
1508
108
        SmallString<4> Storage;
1509
108
        if (!parseScalarString(I.getValue(), VersionString, Storage))
1510
0
          return false;
1511
108
        int Version;
1512
108
        if (VersionString.getAsInteger<int>(10, Version)) {
1513
1
          error(I.getValue(), "expected integer");
1514
1
          return false;
1515
1
        }
1516
107
        if (Version < 0) {
1517
1
          error(I.getValue(), "invalid version number");
1518
1
          return false;
1519
1
        }
1520
106
        if (Version != 0) {
1521
1
          error(I.getValue(), "version mismatch, expected 0");
1522
1
          return false;
1523
1
        }
1524
52
      } else if (Key == "case-sensitive") {
1525
17
        if (!parseScalarBool(I.getValue(), FS->CaseSensitive))
1526
2
          return false;
1527
35
      } else if (Key == "overlay-relative") {
1528
6
        if (!parseScalarBool(I.getValue(), FS->IsRelativeOverlay))
1529
0
          return false;
1530
29
      } else if (Key == "use-external-names") {
1531
25
        if (!parseScalarBool(I.getValue(), FS->UseExternalNames))
1532
0
          return false;
1533
4
      } else if (Key == "fallthrough") {
1534
4
        if (!parseScalarBool(I.getValue(), FS->IsFallthrough))
1535
0
          return false;
1536
0
      } else {
1537
0
        llvm_unreachable("key missing from Keys");
1538
0
      }
1539
257
    }
1540
109
1541
109
    
if (80
Stream.failed()80
)
1542
4
      return false;
1543
76
1544
76
    if (!checkMissingKeys(Top, Keys))
1545
1
      return false;
1546
75
1547
75
    // Now that we sucessefully parsed the YAML file, canonicalize the internal
1548
75
    // representation to a proper directory tree so that we can search faster
1549
75
    // inside the VFS.
1550
75
    for (auto &E : RootEntries)
1551
107
      uniqueOverlayTree(FS, E.get());
1552
75
1553
75
    return true;
1554
75
  }
1555
};
1556
1557
RedirectingFileSystem *
1558
RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1559
                              SourceMgr::DiagHandlerTy DiagHandler,
1560
                              StringRef YAMLFilePath, void *DiagContext,
1561
109
                              IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1562
109
  SourceMgr SM;
1563
109
  yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
1564
109
1565
109
  SM.setDiagHandler(DiagHandler, DiagContext);
1566
109
  yaml::document_iterator DI = Stream.begin();
1567
109
  yaml::Node *Root = DI->getRoot();
1568
109
  if (DI == Stream.end() || !Root) {
1569
0
    SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
1570
0
    return nullptr;
1571
0
  }
1572
109
1573
109
  RedirectingFileSystemParser P(Stream);
1574
109
1575
109
  std::unique_ptr<RedirectingFileSystem> FS(
1576
109
      new RedirectingFileSystem(std::move(ExternalFS)));
1577
109
1578
109
  if (!YAMLFilePath.empty()) {
1579
63
    // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1580
63
    // to each 'external-contents' path.
1581
63
    //
1582
63
    // Example:
1583
63
    //    -ivfsoverlay dummy.cache/vfs/vfs.yaml
1584
63
    // yields:
1585
63
    //  FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1586
63
    //
1587
63
    SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1588
63
    std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1589
63
    assert(!EC && "Overlay dir final path must be absolute");
1590
63
    (void)EC;
1591
63
    FS->setExternalContentsPrefixDir(OverlayAbsDir);
1592
63
  }
1593
109
1594
109
  if (!P.parse(Root, FS.get()))
1595
34
    return nullptr;
1596
75
1597
75
  return FS.release();
1598
75
}
1599
1600
ErrorOr<RedirectingFileSystem::Entry *>
1601
2.36k
RedirectingFileSystem::lookupPath(const Twine &Path_) const {
1602
2.36k
  SmallString<256> Path;
1603
2.36k
  Path_.toVector(Path);
1604
2.36k
1605
2.36k
  // Handle relative paths
1606
2.36k
  if (std::error_code EC = makeAbsolute(Path))
1607
0
    return EC;
1608
2.36k
1609
2.36k
  // Canonicalize path by removing ".", "..", "./", etc components. This is
1610
2.36k
  // a VFS request, do bot bother about symlinks in the path components
1611
2.36k
  // but canonicalize in order to perform the correct entry search.
1612
2.36k
  if (UseCanonicalizedPaths) {
1613
2.36k
    Path = sys::path::remove_leading_dotslash(Path);
1614
2.36k
    sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1615
2.36k
  }
1616
2.36k
1617
2.36k
  if (Path.empty())
1618
0
    return make_error_code(llvm::errc::invalid_argument);
1619
2.36k
1620
2.36k
  sys::path::const_iterator Start = sys::path::begin(Path);
1621
2.36k
  sys::path::const_iterator End = sys::path::end(Path);
1622
2.36k
  for (const auto &Root : Roots) {
1623
2.36k
    ErrorOr<RedirectingFileSystem::Entry *> Result =
1624
2.36k
        lookupPath(Start, End, Root.get());
1625
2.36k
    if (Result || 
Result.getError() != llvm::errc::no_such_file_or_directory1.74k
)
1626
624
      return Result;
1627
2.36k
  }
1628
2.36k
  
return make_error_code(llvm::errc::no_such_file_or_directory)1.73k
;
1629
2.36k
}
1630
1631
ErrorOr<RedirectingFileSystem::Entry *>
1632
RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1633
                                  sys::path::const_iterator End,
1634
24.8k
                                  RedirectingFileSystem::Entry *From) const {
1635
24.8k
#ifndef _WIN32
1636
24.8k
  assert(!isTraversalComponent(*Start) &&
1637
24.8k
         !isTraversalComponent(From->getName()) &&
1638
24.8k
         "Paths should not contain traversal components");
1639
#else
1640
  // FIXME: this is here to support windows, remove it once canonicalized
1641
  // paths become globally default.
1642
  if (Start->equals("."))
1643
    ++Start;
1644
#endif
1645
1646
24.8k
  StringRef FromName = From->getName();
1647
24.8k
1648
24.8k
  // Forward the search to the next component in case this is an empty one.
1649
24.8k
  if (!FromName.empty()) {
1650
24.8k
    if (CaseSensitive ? 
!Start->equals(FromName)18.6k
1651
24.8k
                      : 
!Start->equals_lower(FromName)6.14k
)
1652
3.46k
      // failure to match
1653
3.46k
      return make_error_code(llvm::errc::no_such_file_or_directory);
1654
21.3k
1655
21.3k
    ++Start;
1656
21.3k
1657
21.3k
    if (Start == End) {
1658
624
      // Match!
1659
624
      return From;
1660
624
    }
1661
20.7k
  }
1662
20.7k
1663
20.7k
  auto *DE = dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(From);
1664
20.7k
  if (!DE)
1665
0
    return make_error_code(llvm::errc::not_a_directory);
1666
20.7k
1667
20.7k
  for (const std::unique_ptr<RedirectingFileSystem::Entry> &DirEntry :
1668
22.4k
       llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1669
22.4k
    ErrorOr<RedirectingFileSystem::Entry *> Result =
1670
22.4k
        lookupPath(Start, End, DirEntry.get());
1671
22.4k
    if (Result || 
Result.getError() != llvm::errc::no_such_file_or_directory16.2k
)
1672
6.16k
      return Result;
1673
22.4k
  }
1674
20.7k
  
return make_error_code(llvm::errc::no_such_file_or_directory)14.5k
;
1675
20.7k
}
1676
1677
static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1678
188
                                      Status ExternalStatus) {
1679
188
  Status S = ExternalStatus;
1680
188
  if (!UseExternalNames)
1681
95
    S = Status::copyWithNewName(S, Path);
1682
188
  S.IsVFSMapped = true;
1683
188
  return S;
1684
188
}
1685
1686
ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path,
1687
493
                                              RedirectingFileSystem::Entry *E) {
1688
493
  assert(E != nullptr);
1689
493
  if (auto *F = dyn_cast<RedirectingFileSystem::RedirectingFileEntry>(E)) {
1690
111
    ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
1691
111
    assert(!S || S->getName() == F->getExternalContentsPath());
1692
111
    if (S)
1693
109
      return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1694
109
                                     *S);
1695
2
    return S;
1696
382
  } else { // directory
1697
382
    auto *DE = cast<RedirectingFileSystem::RedirectingDirectoryEntry>(E);
1698
382
    return Status::copyWithNewName(DE->getStatus(), Path);
1699
382
  }
1700
493
}
1701
1702
1.75k
ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
1703
1.75k
  ErrorOr<RedirectingFileSystem::Entry *> Result = lookupPath(Path);
1704
1.75k
  if (!Result) {
1705
1.28k
    if (IsFallthrough &&
1706
1.28k
        
Result.getError() == llvm::errc::no_such_file_or_directory1.27k
) {
1707
1.27k
      return ExternalFS->status(Path);
1708
1.27k
    }
1709
12
    return Result.getError();
1710
12
  }
1711
468
  return status(Path, *Result);
1712
468
}
1713
1714
namespace {
1715
1716
/// Provide a file wrapper with an overriden status.
1717
class FileWithFixedStatus : public File {
1718
  std::unique_ptr<File> InnerFile;
1719
  Status S;
1720
1721
public:
1722
  FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
1723
79
      : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
1724
1725
64
  ErrorOr<Status> status() override { return S; }
1726
  ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
1727
1728
  getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1729
72
            bool IsVolatile) override {
1730
72
    return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1731
72
                                IsVolatile);
1732
72
  }
1733
1734
0
  std::error_code close() override { return InnerFile->close(); }
1735
};
1736
1737
} // namespace
1738
1739
ErrorOr<std::unique_ptr<File>>
1740
477
RedirectingFileSystem::openFileForRead(const Twine &Path) {
1741
477
  ErrorOr<RedirectingFileSystem::Entry *> E = lookupPath(Path);
1742
477
  if (!E) {
1743
397
    if (IsFallthrough &&
1744
397
        
E.getError() == llvm::errc::no_such_file_or_directory391
) {
1745
391
      return ExternalFS->openFileForRead(Path);
1746
391
    }
1747
6
    return E.getError();
1748
6
  }
1749
80
1750
80
  auto *F = dyn_cast<RedirectingFileSystem::RedirectingFileEntry>(*E);
1751
80
  if (!F) // FIXME: errc::not_a_file?
1752
0
    return make_error_code(llvm::errc::invalid_argument);
1753
80
1754
80
  auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1755
80
  if (!Result)
1756
1
    return Result;
1757
79
1758
79
  auto ExternalStatus = (*Result)->status();
1759
79
  if (!ExternalStatus)
1760
0
    return ExternalStatus.getError();
1761
79
1762
79
  // FIXME: Update the status with the name and VFSMapped.
1763
79
  Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1764
79
                                     *ExternalStatus);
1765
79
  return std::unique_ptr<File>(
1766
79
      llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
1767
79
}
1768
1769
std::error_code
1770
RedirectingFileSystem::getRealPath(const Twine &Path,
1771
91
                                   SmallVectorImpl<char> &Output) const {
1772
91
  ErrorOr<RedirectingFileSystem::Entry *> Result = lookupPath(Path);
1773
91
  if (!Result) {
1774
42
    if (IsFallthrough &&
1775
42
        Result.getError() == llvm::errc::no_such_file_or_directory) {
1776
42
      return ExternalFS->getRealPath(Path, Output);
1777
42
    }
1778
0
    return Result.getError();
1779
0
  }
1780
49
1781
49
  if (auto *F =
1782
1
          dyn_cast<RedirectingFileSystem::RedirectingFileEntry>(*Result)) {
1783
1
    return ExternalFS->getRealPath(F->getExternalContentsPath(), Output);
1784
1
  }
1785
48
  // Even if there is a directory entry, fall back to ExternalFS if allowed,
1786
48
  // because directories don't have a single external contents path.
1787
48
  return IsFallthrough ? 
ExternalFS->getRealPath(Path, Output)47
1788
48
                       : 
llvm::errc::invalid_argument1
;
1789
48
}
1790
1791
IntrusiveRefCntPtr<FileSystem>
1792
vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1793
                    SourceMgr::DiagHandlerTy DiagHandler,
1794
                    StringRef YAMLFilePath, void *DiagContext,
1795
107
                    IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1796
107
  return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
1797
107
                                       YAMLFilePath, DiagContext,
1798
107
                                       std::move(ExternalFS));
1799
107
}
1800
1801
static void getVFSEntries(RedirectingFileSystem::Entry *SrcE,
1802
                          SmallVectorImpl<StringRef> &Path,
1803
30
                          SmallVectorImpl<YAMLVFSEntry> &Entries) {
1804
30
  auto Kind = SrcE->getKind();
1805
30
  if (Kind == RedirectingFileSystem::EK_Directory) {
1806
28
    auto *DE = dyn_cast<RedirectingFileSystem::RedirectingDirectoryEntry>(SrcE);
1807
28
    assert(DE && "Must be a directory");
1808
28
    for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
1809
28
         llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1810
28
      Path.push_back(SubEntry->getName());
1811
28
      getVFSEntries(SubEntry.get(), Path, Entries);
1812
28
      Path.pop_back();
1813
28
    }
1814
28
    return;
1815
28
  }
1816
2
1817
2
  assert(Kind == RedirectingFileSystem::EK_File && "Must be a EK_File");
1818
2
  auto *FE = dyn_cast<RedirectingFileSystem::RedirectingFileEntry>(SrcE);
1819
2
  assert(FE && "Must be a file");
1820
2
  SmallString<128> VPath;
1821
2
  for (auto &Comp : Path)
1822
30
    llvm::sys::path::append(VPath, Comp);
1823
2
  Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
1824
2
}
1825
1826
void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1827
                             SourceMgr::DiagHandlerTy DiagHandler,
1828
                             StringRef YAMLFilePath,
1829
                             SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
1830
                             void *DiagContext,
1831
2
                             IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1832
2
  RedirectingFileSystem *VFS = RedirectingFileSystem::create(
1833
2
      std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
1834
2
      std::move(ExternalFS));
1835
2
  ErrorOr<RedirectingFileSystem::Entry *> RootE = VFS->lookupPath("/");
1836
2
  if (!RootE)
1837
0
    return;
1838
2
  SmallVector<StringRef, 8> Components;
1839
2
  Components.push_back("/");
1840
2
  getVFSEntries(*RootE, Components, CollectedEntries);
1841
2
}
1842
1843
193k
UniqueID vfs::getNextVirtualUniqueID() {
1844
193k
  static std::atomic<unsigned> UID;
1845
193k
  unsigned ID = ++UID;
1846
193k
  // The following assumes that uint64_t max will never collide with a real
1847
193k
  // dev_t value from the OS.
1848
193k
  return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1849
193k
}
1850
1851
538
void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1852
538
  assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1853
538
  assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1854
538
  assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1855
538
  Mappings.emplace_back(VirtualPath, RealPath);
1856
538
}
1857
1858
namespace {
1859
1860
class JSONWriter {
1861
  llvm::raw_ostream &OS;
1862
  SmallVector<StringRef, 16> DirStack;
1863
1864
136
  unsigned getDirIndent() { return 4 * DirStack.size(); }
1865
538
  unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1866
  bool containedIn(StringRef Parent, StringRef Path);
1867
  StringRef containedPart(StringRef Parent, StringRef Path);
1868
  void startDirectory(StringRef Path);
1869
  void endDirectory();
1870
  void writeEntry(StringRef VPath, StringRef RPath);
1871
1872
public:
1873
24
  JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
1874
1875
  void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
1876
             Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
1877
             StringRef OverlayDir);
1878
};
1879
1880
} // namespace
1881
1882
63
bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
1883
63
  using namespace llvm::sys;
1884
63
1885
63
  // Compare each path component.
1886
63
  auto IParent = path::begin(Parent), EParent = path::end(Parent);
1887
63
  for (auto IChild = path::begin(Path), EChild = path::end(Path);
1888
852
       IParent != EParent && 
IChild != EChild822
;
++IParent, ++IChild789
) {
1889
803
    if (*IParent != *IChild)
1890
14
      return false;
1891
803
  }
1892
63
  // Have we exhausted the parent path?
1893
63
  
return IParent == EParent49
;
1894
63
}
1895
1896
30
StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1897
30
  assert(!Parent.empty());
1898
30
  assert(containedIn(Parent, Path));
1899
30
  return Path.slice(Parent.size() + 1, StringRef::npos);
1900
30
}
1901
1902
68
void JSONWriter::startDirectory(StringRef Path) {
1903
68
  StringRef Name =
1904
68
      DirStack.empty() ? 
Path38
:
containedPart(DirStack.back(), Path)30
;
1905
68
  DirStack.push_back(Path);
1906
68
  unsigned Indent = getDirIndent();
1907
68
  OS.indent(Indent) << "{\n";
1908
68
  OS.indent(Indent + 2) << "'type': 'directory',\n";
1909
68
  OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1910
68
  OS.indent(Indent + 2) << "'contents': [\n";
1911
68
}
1912
1913
68
void JSONWriter::endDirectory() {
1914
68
  unsigned Indent = getDirIndent();
1915
68
  OS.indent(Indent + 2) << "]\n";
1916
68
  OS.indent(Indent) << "}";
1917
68
1918
68
  DirStack.pop_back();
1919
68
}
1920
1921
538
void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1922
538
  unsigned Indent = getFileIndent();
1923
538
  OS.indent(Indent) << "{\n";
1924
538
  OS.indent(Indent + 2) << "'type': 'file',\n";
1925
538
  OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1926
538
  OS.indent(Indent + 2) << "'external-contents': \""
1927
538
                        << llvm::yaml::escape(RPath) << "\"\n";
1928
538
  OS.indent(Indent) << "}";
1929
538
}
1930
1931
void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
1932
                       Optional<bool> UseExternalNames,
1933
                       Optional<bool> IsCaseSensitive,
1934
                       Optional<bool> IsOverlayRelative,
1935
24
                       StringRef OverlayDir) {
1936
24
  using namespace llvm::sys;
1937
24
1938
24
  OS << "{\n"
1939
24
        "  'version': 0,\n";
1940
24
  if (IsCaseSensitive.hasValue())
1941
17
    OS << "  'case-sensitive': '"
1942
17
       << (IsCaseSensitive.getValue() ? 
"true"16
:
"false"1
) << "',\n";
1943
24
  if (UseExternalNames.hasValue())
1944
16
    OS << "  'use-external-names': '"
1945
16
       << (UseExternalNames.getValue() ? 
"true"0
: "false") << "',\n";
1946
24
  bool UseOverlayRelative = false;
1947
24
  if (IsOverlayRelative.hasValue()) {
1948
16
    UseOverlayRelative = IsOverlayRelative.getValue();
1949
16
    OS << "  'overlay-relative': '" << (UseOverlayRelative ? "true" : 
"false"0
)
1950
16
       << "',\n";
1951
16
  }
1952
24
  OS << "  'roots': [\n";
1953
24
1954
24
  if (!Entries.empty()) {
1955
23
    const YAMLVFSEntry &Entry = Entries.front();
1956
23
    startDirectory(path::parent_path(Entry.VPath));
1957
23
1958
23
    StringRef RPath = Entry.RPath;
1959
23
    if (UseOverlayRelative) {
1960
16
      unsigned OverlayDirLen = OverlayDir.size();
1961
16
      assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1962
16
             "Overlay dir must be contained in RPath");
1963
16
      RPath = RPath.slice(OverlayDirLen, RPath.size());
1964
16
    }
1965
23
1966
23
    writeEntry(path::filename(Entry.VPath), RPath);
1967
23
1968
515
    for (const auto &Entry : Entries.slice(1)) {
1969
515
      StringRef Dir = path::parent_path(Entry.VPath);
1970
515
      if (Dir == DirStack.back())
1971
470
        OS << ",\n";
1972
45
      else {
1973
78
        while (!DirStack.empty() && 
!containedIn(DirStack.back(), Dir)63
) {
1974
33
          OS << "\n";
1975
33
          endDirectory();
1976
33
        }
1977
45
        OS << ",\n";
1978
45
        startDirectory(Dir);
1979
45
      }
1980
515
      StringRef RPath = Entry.RPath;
1981
515
      if (UseOverlayRelative) {
1982
507
        unsigned OverlayDirLen = OverlayDir.size();
1983
507
        assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1984
507
               "Overlay dir must be contained in RPath");
1985
507
        RPath = RPath.slice(OverlayDirLen, RPath.size());
1986
507
      }
1987
515
      writeEntry(path::filename(Entry.VPath), RPath);
1988
515
    }
1989
23
1990
58
    while (!DirStack.empty()) {
1991
35
      OS << "\n";
1992
35
      endDirectory();
1993
35
    }
1994
23
    OS << "\n";
1995
23
  }
1996
24
1997
24
  OS << "  ]\n"
1998
24
     << "}\n";
1999
24
}
2000
2001
24
void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
2002
3.66k
  llvm::sort(Mappings, [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
2003
3.66k
    return LHS.VPath < RHS.VPath;
2004
3.66k
  });
2005
24
2006
24
  JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
2007
24
                       IsOverlayRelative, OverlayDir);
2008
24
}
2009
2010
VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
2011
    const Twine &_Path,
2012
    RedirectingFileSystem::RedirectingDirectoryEntry::iterator Begin,
2013
    RedirectingFileSystem::RedirectingDirectoryEntry::iterator End,
2014
    bool IterateExternalFS, FileSystem &ExternalFS, std::error_code &EC)
2015
    : Dir(_Path.str()), Current(Begin), End(End),
2016
25
      IterateExternalFS(IterateExternalFS), ExternalFS(ExternalFS) {
2017
25
  EC = incrementImpl(/*IsFirstTime=*/true);
2018
25
}
2019
2020
48
std::error_code VFSFromYamlDirIterImpl::increment() {
2021
48
  return incrementImpl(/*IsFirstTime=*/false);
2022
48
}
2023
2024
35
std::error_code VFSFromYamlDirIterImpl::incrementExternal() {
2025
35
  assert(!(IsExternalFSCurrent && ExternalDirIter == directory_iterator()) &&
2026
35
         "incrementing past end");
2027
35
  std::error_code EC;
2028
35
  if (IsExternalFSCurrent) {
2029
10
    ExternalDirIter.increment(EC);
2030
25
  } else if (IterateExternalFS) {
2031
23
    ExternalDirIter = ExternalFS.dir_begin(Dir, EC);
2032
23
    IsExternalFSCurrent = true;
2033
23
    if (EC && 
EC != errc::no_such_file_or_directory14
)
2034
0
      return EC;
2035
23
    EC = {};
2036
23
  }
2037
35
  if (EC || ExternalDirIter == directory_iterator()) {
2038
25
    CurrentEntry = directory_entry();
2039
25
  } else {
2040
10
    CurrentEntry = *ExternalDirIter;
2041
10
  }
2042
35
  return EC;
2043
35
}
2044
2045
69
std::error_code VFSFromYamlDirIterImpl::incrementContent(bool IsFirstTime) {
2046
69
  assert((IsFirstTime || Current != End) && "cannot iterate past end");
2047
69
  if (!IsFirstTime)
2048
44
    ++Current;
2049
69
  while (Current != End) {
2050
44
    SmallString<128> PathStr(Dir);
2051
44
    llvm::sys::path::append(PathStr, (*Current)->getName());
2052
44
    sys::fs::file_type Type;
2053
44
    switch ((*Current)->getKind()) {
2054
44
    case RedirectingFileSystem::EK_Directory:
2055
5
      Type = sys::fs::file_type::directory_file;
2056
5
      break;
2057
44
    case RedirectingFileSystem::EK_File:
2058
39
      Type = sys::fs::file_type::regular_file;
2059
39
      break;
2060
44
    }
2061
44
    CurrentEntry = directory_entry(PathStr.str(), Type);
2062
44
    return {};
2063
44
  }
2064
69
  
return incrementExternal()25
;
2065
69
}
2066
2067
73
std::error_code VFSFromYamlDirIterImpl::incrementImpl(bool IsFirstTime) {
2068
79
  while (true) {
2069
79
    std::error_code EC = IsExternalFSCurrent ? 
incrementExternal()10
2070
79
                                             : 
incrementContent(IsFirstTime)69
;
2071
79
    if (EC || CurrentEntry.path().empty())
2072
25
      return EC;
2073
54
    StringRef Name = llvm::sys::path::filename(CurrentEntry.path());
2074
54
    if (SeenNames.insert(Name).second)
2075
48
      return EC; // name not seen before
2076
54
  }
2077
73
  
llvm_unreachable0
("returned above");
2078
73
}
2079
2080
vfs::recursive_directory_iterator::recursive_directory_iterator(
2081
    FileSystem &FS_, const Twine &Path, std::error_code &EC)
2082
292
    : FS(&FS_) {
2083
292
  directory_iterator I = FS->dir_begin(Path, EC);
2084
292
  if (I != directory_iterator()) {
2085
289
    State = std::make_shared<detail::RecDirIterState>();
2086
289
    State->Stack.push(I);
2087
289
  }
2088
292
}
2089
2090
vfs::recursive_directory_iterator &
2091
1.15k
recursive_directory_iterator::increment(std::error_code &EC) {
2092
1.15k
  assert(FS && State && !State->Stack.empty() && "incrementing past end");
2093
1.15k
  assert(!State->Stack.top()->path().empty() && "non-canonical end iterator");
2094
1.15k
  vfs::directory_iterator End;
2095
1.15k
2096
1.15k
  if (State->HasNoPushRequest)
2097
7
    State->HasNoPushRequest = false;
2098
1.14k
  else {
2099
1.14k
    if (State->Stack.top()->type() == sys::fs::file_type::directory_file) {
2100
111
      vfs::directory_iterator I = FS->dir_begin(State->Stack.top()->path(), EC);
2101
111
      if (I != End) {
2102
106
        State->Stack.push(I);
2103
106
        return *this;
2104
106
      }
2105
1.04k
    }
2106
1.14k
  }
2107
1.04k
2108
1.44k
  
while (1.04k
!State->Stack.empty() &&
State->Stack.top().increment(EC) == End1.15k
)
2109
395
    State->Stack.pop();
2110
1.04k
2111
1.04k
  if (State->Stack.empty())
2112
289
    State.reset(); // end iterator
2113
1.04k
2114
1.04k
  return *this;
2115
1.04k
}