File: CASFileSystem.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (366 lines) | stat: -rw-r--r-- 12,114 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
//===- CASFileSystem.cpp ----------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "llvm/CAS/CASFileSystem.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/CAS/FileSystemCache.h"
#include "llvm/CAS/ObjectStore.h"
#include "llvm/CAS/TreeSchema.h"
#include "llvm/Support/AlignOf.h"
#include "llvm/Support/Allocator.h"

using namespace llvm;
using namespace llvm::cas;

namespace {
class CASFileSystem : public ThreadSafeFileSystem {
  struct WorkingDirectoryType {
    FileSystemCache::DirectoryEntry *Entry;

    /// Mimics shell behaviour on directory changes. Not necessarily the same
    /// as \c Entry->getTreePath().
    std::string Path;
  };

public:
  using File = FileSystemCache::File;
  using Symlink = FileSystemCache::Symlink;
  using Directory = FileSystemCache::Directory;
  using DirectoryEntry = FileSystemCache::DirectoryEntry;

  class VFSFile; // Return type for vfs::FileSystem::openFileForRead().

  Error loadDirectory(DirectoryEntry &Entry);
  Error loadFile(DirectoryEntry &Entry);
  Error loadSymlink(DirectoryEntry &Entry);

  /// Look up a directory entry in the CAS, navigating trees and resolving
  /// symlinks in the parent path. If \p FollowSymlinks is true, also follows
  /// symlinks in the filename.
  Expected<DirectoryEntry *> lookupPath(StringRef Path,
                                        bool FollowSymlinks = true);

  ErrorOr<vfs::Status> status(const Twine &Path) final;
  ErrorOr<std::unique_ptr<vfs::File>> openFileForRead(const Twine &Path) final;

  Expected<const vfs::CachedDirectoryEntry *>
  getDirectoryEntry(const Twine &Path, bool FollowSymlinks) const final;

  vfs::directory_iterator dir_begin(const Twine &Dir,
                                    std::error_code &EC) final {
    auto IterOr = getDirectoryIterator(Dir);
    if (IterOr)
      return *IterOr;
    EC = IterOr.getError();
    return vfs::directory_iterator();
  }

  ErrorOr<vfs::directory_iterator> getDirectoryIterator(const Twine &Dir);

  std::error_code setCurrentWorkingDirectory(const Twine &Path) final;

  ErrorOr<std::string> getCurrentWorkingDirectory() const final {
    return WorkingDirectory.Path;
  }

  Error initialize(ObjectRef Root);

  CASFileSystem(std::shared_ptr<ObjectStore> DB)
      : DB(*DB), OwnedDB(std::move(DB)) {}
  CASFileSystem(ObjectStore &DB) : DB(DB) {}

  IntrusiveRefCntPtr<ThreadSafeFileSystem> createThreadSafeProxyFS() final {
    return makeIntrusiveRefCnt<CASFileSystem>(*this);
  }
  CASFileSystem(const CASFileSystem &FS) = default;

  ObjectStore &getCAS() const { return DB; }

private:
  ObjectStore &DB;
  std::shared_ptr<ObjectStore> OwnedDB;

  IntrusiveRefCntPtr<FileSystemCache> Cache;
  WorkingDirectoryType WorkingDirectory;
};
} // namespace

class CASFileSystem::VFSFile : public vfs::File {
public:
  ErrorOr<vfs::Status> status() final { return Entry->getStatus(Name); }

  ErrorOr<std::string> getName() final { return Name; }

  /// Get the contents of the file as a \p MemoryBuffer.
  ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name, int64_t,
                                                   bool, bool) final {
    Expected<ObjectProxy> Object = DB.getProxy(*Entry->getRef());
    if (!Object)
      return errorToErrorCode(Object.takeError());
    assert(Object->getNumReferences() == 0 && "Expected a leaf node");
    SmallString<256> Storage;
    return Object->getMemoryBuffer(Name.toStringRef(Storage));
  }

  llvm::ErrorOr<std::optional<cas::ObjectRef>> getObjectRefForContent() final {
    return Entry->getRef();
  }

  /// Closes the file.
  std::error_code close() final { return std::error_code(); }

  VFSFile() = delete;
  explicit VFSFile(ObjectStore &DB, DirectoryEntry &Entry, StringRef Name)
      : DB(DB), Name(Name.str()), Entry(&Entry) {
    assert(Entry.isFile());
    assert(Entry.hasNode());
  }

private:
  ObjectStore &DB;
  std::string Name;
  DirectoryEntry *Entry;
};

Error CASFileSystem::initialize(ObjectRef Root) {
  Cache = makeIntrusiveRefCnt<FileSystemCache>(Root);

  // Initial working directory is the root.
  WorkingDirectory.Entry = &Cache->getRoot();
  WorkingDirectory.Path = WorkingDirectory.Entry->getTreePath().str();

  // Load the root to confirm it's really a tree.
  return loadDirectory(*WorkingDirectory.Entry);
}

std::error_code CASFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
  SmallString<128> Storage;
  StringRef CanonicalPath = FileSystemCache::canonicalizeWorkingDirectory(
      Path, WorkingDirectory.Path, Storage);

  // Read and cache all the symlinks in the path by looking it up. Return any
  // error encountered.
  Expected<DirectoryEntry *> ExpectedEntry = lookupPath(CanonicalPath);
  if (!ExpectedEntry)
    return errorToErrorCode(ExpectedEntry.takeError());

  WorkingDirectory.Path = CanonicalPath.str();
  WorkingDirectory.Entry = *ExpectedEntry;
  return std::error_code();
}

Error CASFileSystem::loadDirectory(DirectoryEntry &Parent) {
  Directory &D = Parent.asDirectory();
  if (D.isComplete())
    return Error::success();

  SmallString<128> Path = Parent.getTreePath();
  size_t ParentPathSize = Path.size();
  auto makeCachedEntry =
      [&](const NamedTreeEntry &NewEntry) -> DirectoryEntry & {
    Path.resize(ParentPathSize);
    sys::path::append(Path, sys::path::Style::posix, NewEntry.getName());
    switch (NewEntry.getKind()) {
    case TreeEntry::Regular:
    case TreeEntry::Executable:
      return Cache->makeLazyFileAlreadyLocked(Parent, Path, NewEntry.getRef(),
                                              NewEntry.getKind() ==
                                                  TreeEntry::Executable);
    case TreeEntry::Symlink:
      return Cache->makeLazySymlinkAlreadyLocked(Parent, Path,
                                                 NewEntry.getRef());
    case TreeEntry::Tree:
      return Cache->makeDirectoryAlreadyLocked(Parent, Path, NewEntry.getRef());
    }
    llvm_unreachable("invalid tree type");
  };
  Expected<ObjectProxy> Object = DB.getProxy(*Parent.getRef());
  if (!Object)
    return Object.takeError();

  TreeSchema Schema(DB);
  if (!Schema.isNode(*Object))
    report_fatal_error(createStringError(
        inconvertibleErrorCode(),
        "invalid tree '" + Object->getID().toString() + "'"));

  // Lock and check for a race.
  Directory::Writer W(D);
  if (D.isComplete())
    return Error::success();

  Expected<TreeProxy> Tree = Schema.load(*Object);
  if (!Tree)
    return Tree.takeError();

  if (Error E = Tree->forEachEntry([&](const NamedTreeEntry &NewEntry) {
        D.add(makeCachedEntry(NewEntry));
        return Error::success();
      }))
    return E;
  D.IsComplete = true;
  return Error::success();
}

Error CASFileSystem::loadFile(DirectoryEntry &Entry) {
  assert(Entry.isFile());

  Expected<ObjectProxy> File = DB.getProxy(*Entry.getRef());
  if (!File)
    return File.takeError();

  Cache->finishLazyFile(Entry, File->getData().size());
  return Error::success();
}

Error CASFileSystem::loadSymlink(DirectoryEntry &Entry) {
  assert(Entry.isSymlink());

  Expected<ObjectProxy> File = DB.getProxy(*Entry.getRef());
  if (!File)
    return File.takeError();

  Cache->finishLazySymlink(Entry, File->getData());
  return Error::success();
}

ErrorOr<vfs::Status> CASFileSystem::status(const Twine &Path) {
  SmallString<128> Storage;
  StringRef PathRef = Path.toStringRef(Storage);

  // Lookup only returns an Error if there's a problem communicating with the
  // CAS, or there's data corruption.
  //
  // FIXME: Translate the error to a filesystem-like error to encapsulate the
  // user from CAS issues.
  Expected<DirectoryEntry *> ExpectedEntry = lookupPath(PathRef);
  if (!ExpectedEntry)
    return errorToErrorCode(ExpectedEntry.takeError());
  DirectoryEntry *Entry = *ExpectedEntry;

  if (!Entry->hasNode()) {
    assert(!Entry->isDirectory());
    if (Error E = Entry->isSymlink() ? loadSymlink(*Entry) : loadFile(*Entry))
      return errorToErrorCode(std::move(E));
  }

  return Entry->getStatus(PathRef);
}

Expected<const vfs::CachedDirectoryEntry *>
CASFileSystem::getDirectoryEntry(const Twine &Path, bool FollowSymlinks) const {
  SmallString<128> Storage;
  StringRef PathRef = Path.toStringRef(Storage);

  // It's not a const operation, but it's thread-safe.
  return const_cast<CASFileSystem *>(this)->lookupPath(PathRef, FollowSymlinks);
}

ErrorOr<std::unique_ptr<vfs::File>>
CASFileSystem::openFileForRead(const Twine &Path) {
  SmallString<128> Storage;
  StringRef PathRef = Path.toStringRef(Storage);

  Expected<DirectoryEntry *> ExpectedEntry = lookupPath(PathRef);
  if (!ExpectedEntry)
    return errorToErrorCode(ExpectedEntry.takeError());

  DirectoryEntry *Entry = *ExpectedEntry;
  if (!Entry->isFile())
    return std::errc::invalid_argument;

  if (!Entry->hasNode())
    if (Error E = loadFile(*Entry))
      return errorToErrorCode(std::move(E));

  return std::make_unique<VFSFile>(DB, *Entry, PathRef);
}

ErrorOr<vfs::directory_iterator>
CASFileSystem::getDirectoryIterator(const Twine &Path) {
  SmallString<128> Storage;
  StringRef PathRef = Path.toStringRef(Storage);

  Expected<DirectoryEntry *> ExpectedEntry = lookupPath(PathRef);
  if (!ExpectedEntry)
    return errorToErrorCode(ExpectedEntry.takeError());
  DirectoryEntry *Entry = *ExpectedEntry;

  if (!Entry->isDirectory())
    return std::errc::not_a_directory;

  if (Error E = loadDirectory(*Entry))
    return errorToErrorCode(std::move(E));

  return Cache->getCachedVFSDirIter(
      Entry->asDirectory(), [this](StringRef Path) { return lookupPath(Path); },
      WorkingDirectory.Path, PathRef);
}

namespace {
class DiscoveryInstanceImpl final : public FileSystemCache::DiscoveryInstance {
public:
  DiscoveryInstanceImpl(CASFileSystem &FS) : FS(FS) {}
  ~DiscoveryInstanceImpl() {}

private:
  using DirectoryEntry = FileSystemCache::DirectoryEntry;

  Expected<DirectoryEntry *> requestDirectoryEntry(DirectoryEntry &Parent,
                                                   StringRef Name) override {
    if (Parent.asDirectory().isComplete())
      return errorCodeToError(
          std::make_error_code(std::errc::no_such_file_or_directory));

    if (Error E = FS.loadDirectory(Parent))
      return std::move(E);

    CASFileSystem::Directory &D = Parent.asDirectory();
    assert(D.isComplete() && "Loaded directory should be complete");
    if (DirectoryEntry *Entry = D.lookup(Name))
      return Entry;
    return errorCodeToError(
        std::make_error_code(std::errc::no_such_file_or_directory));
  }
  Error requestSymlinkTarget(DirectoryEntry &Symlink) override {
    return FS.loadSymlink(Symlink);
  }

private:
  CASFileSystem &FS;
};
} // end anonymous namespace

Expected<CASFileSystem::DirectoryEntry *>
CASFileSystem::lookupPath(StringRef Path, bool FollowSymlinks) {
  DiscoveryInstanceImpl DI(*this);
  return Cache->lookupPath(DI, Path, *WorkingDirectory.Entry, FollowSymlinks);
}

static Expected<std::unique_ptr<CASFileSystem>>
initializeCASFileSystem(std::unique_ptr<CASFileSystem> FS,
                        const CASID &RootID) {
  std::optional<ObjectRef> Root = FS->getCAS().getReference(RootID);
  if (!Root)
    return createStringError(inconvertibleErrorCode(),
                             "cannot get reference to root FS");
  if (Error E = FS->initialize(*Root))
    return std::move(E);
  return std::move(FS);
}

Expected<std::unique_ptr<vfs::FileSystem>>
cas::createCASFileSystem(std::shared_ptr<ObjectStore> DB, const CASID &RootID) {
  return initializeCASFileSystem(std::make_unique<CASFileSystem>(std::move(DB)),
                                 RootID);
}

Expected<std::unique_ptr<vfs::FileSystem>>
cas::createCASFileSystem(ObjectStore &DB, const CASID &RootID) {
  return initializeCASFileSystem(std::make_unique<CASFileSystem>(DB), RootID);
}