blob: d94be5bb12ce14d227591c689c0650e81431e8f4 [file] [log] [blame]
Ilya Biryukov1712bc72018-12-03 15:21:49 +00001//===--- FSProvider.cpp - VFS provider for ClangdServer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "FSProvider.h"
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/ADT/SmallString.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/Support/Path.h"
15#include "llvm/Support/VirtualFileSystem.h"
16#include <memory>
17
18using namespace llvm;
19
20namespace clang {
21namespace clangd {
22
23namespace {
24/// Always opens files in the underlying filesystem as "volatile", meaning they
25/// won't be memory-mapped. This avoid locking the files on Windows.
26class VolatileFileSystem : public llvm::vfs::ProxyFileSystem {
27public:
28 explicit VolatileFileSystem(llvm::IntrusiveRefCntPtr<FileSystem> FS)
29 : ProxyFileSystem(std::move(FS)) {}
30
31 llvm::ErrorOr<std::unique_ptr<vfs::File>>
32 openFileForRead(const Twine &InPath) override {
33 SmallString<128> Path;
34 InPath.toVector(Path);
35
36 auto File = getUnderlyingFS().openFileForRead(Path);
37 if (!File)
38 return File;
39 // Try to guess preamble files, they can be memory-mapped even on Windows as
40 // clangd has exclusive access to those.
41 StringRef FileName = llvm::sys::path::filename(Path);
42 if (FileName.startswith("preamble-") && FileName.endswith(".pch"))
43 return File;
44 return std::unique_ptr<VolatileFile>(
45 new VolatileFile(std::move(*File)));
46 }
47
48private:
49 class VolatileFile : public vfs::File {
50 public:
51 VolatileFile(std::unique_ptr<vfs::File> Wrapped)
52 : Wrapped(std::move(Wrapped)) {
53 assert(this->Wrapped);
54 }
55
56 virtual llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
57 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
58 bool /*IsVolatile*/) override {
59 return Wrapped->getBuffer(Name, FileSize, RequiresNullTerminator,
60 /*IsVolatile=*/true);
61 }
62
63 llvm::ErrorOr<vfs::Status> status() override { return Wrapped->status(); }
64 llvm::ErrorOr<std::string> getName() override { return Wrapped->getName(); }
65 std::error_code close() override { return Wrapped->close(); }
66
67 private:
68 std::unique_ptr<File> Wrapped;
69 };
70};
71} // namespace
72
73llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>
74clang::clangd::RealFileSystemProvider::getFileSystem() const {
75// Avoid using memory-mapped files on Windows, they cause file locking issues.
76// FIXME: Try to use a similar approach in Sema instead of relying on
77// propagation of the 'isVolatile' flag through all layers.
78#ifdef _WIN32
79 return new VolatileFSProvider(vfs::getRealFileSystem());
80#else
81 return vfs::getRealFileSystem();
82#endif
83}
84} // namespace clangd
85} // namespace clang