blob: 5d1434bf6f0bf1673bd23f890c2f1de4a9a5a60e [file] [log] [blame]
//===--- FSProvider.cpp - VFS provider for ClangdServer -------------------===//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "FSProvider.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/VirtualFileSystem.h"
#include <memory>
namespace clang {
namespace clangd {
namespace {
/// Always opens files in the underlying filesystem as "volatile", meaning they
/// won't be memory-mapped. This avoid locking the files on Windows.
class VolatileFileSystem : public llvm::vfs::ProxyFileSystem {
explicit VolatileFileSystem(llvm::IntrusiveRefCntPtr<FileSystem> FS)
: ProxyFileSystem(std::move(FS)) {}
openFileForRead(const llvm::Twine &InPath) override {
llvm::SmallString<128> Path;
auto File = getUnderlyingFS().openFileForRead(Path);
if (!File)
return File;
// Try to guess preamble files, they can be memory-mapped even on Windows as
// clangd has exclusive access to those.
llvm::StringRef FileName = llvm::sys::path::filename(Path);
if (FileName.startswith("preamble-") && FileName.endswith(".pch"))
return File;
return std::unique_ptr<VolatileFile>(new VolatileFile(std::move(*File)));
class VolatileFile : public llvm::vfs::File {
VolatileFile(std::unique_ptr<llvm::vfs::File> Wrapped)
: Wrapped(std::move(Wrapped)) {
virtual llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
getBuffer(const llvm::Twine &Name, int64_t FileSize,
bool RequiresNullTerminator, bool /*IsVolatile*/) override {
return Wrapped->getBuffer(Name, FileSize, RequiresNullTerminator,
llvm::ErrorOr<llvm::vfs::Status> status() override {
return Wrapped->status();
llvm::ErrorOr<std::string> getName() override { return Wrapped->getName(); }
std::error_code close() override { return Wrapped->close(); }
std::unique_ptr<File> Wrapped;
} // namespace
clang::clangd::RealFileSystemProvider::getFileSystem() const {
// Avoid using memory-mapped files on Windows, they cause file locking issues.
// FIXME: Try to use a similar approach in Sema instead of relying on
// propagation of the 'isVolatile' flag through all layers.
#ifdef _WIN32
return new VolatileFileSystem(
return llvm::vfs::createPhysicalFileSystem().release();
} // namespace clangd
} // namespace clang