Implement the VLS roadmap on the native VBS build
Native VBS and CMake builds of the server and every registered suite: protocol and document sync, VBS/compdb providers, stock GCC diagnostics (including in-process default profile preparation), the stock occurrence observer and hover/definition, the bounded Scheduler, C++ module graph, scan and artifact cache with real CMI production, the context-aware symbol index with schema-2 snapshot migration, navigation and guarded rename, reflection provenance with splice-origin extraction, index-backed completion and signature help, live GCC worker control with a registered DAP suite, and the Neovim and VS Code clients. VoidLibrary follows main. The private GCC 16.2.0 frontend is reproduced from the versioned patches and verified stepping reflection/template code with projected values 17/34 and 41/82.
This commit is contained in:
1 parent
ca04975d54
commit
da8003f6d4
310 files changed
+47552
-480
No files matched your search
@@ -0,0 +1,275 @@
|
||||
#include "Leaf.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
#ifdef __linux__
|
||||
#include <Void/Crypto/Crypto.hpp>
|
||||
#include <Void/LanguageServer/Support/RegularFile.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <climits>
|
||||
#include <csignal>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <span>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <link.h>
|
||||
#include <linux/openat2.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/resource.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/sysmacros.h>
|
||||
#include <unistd.h>
|
||||
|
||||
// GNU ELF linkers expose the native executable header, including class, byte order and machine.
|
||||
extern "C" const ElfW(Ehdr) __ehdr_start;
|
||||
|
||||
namespace vls::gcc {
|
||||
namespace {
|
||||
using Void::System::OwnedFd;
|
||||
namespace File = Void::LanguageServer::Detail;
|
||||
|
||||
constexpr std::size_t mib = 1024 * 1024;
|
||||
constexpr std::size_t max_image = 256 * mib;
|
||||
constexpr int control_fd = 3;
|
||||
constexpr int events_fd = 4;
|
||||
constexpr int setup_failure = 126;
|
||||
|
||||
bool lower_hex(std::string_view text, std::size_t size) {
|
||||
return text.size() == size && std::ranges::all_of(text, [](char c) {
|
||||
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
|
||||
});
|
||||
}
|
||||
|
||||
bool pipe_end(int fd, int mode, struct stat &st) {
|
||||
const int flags = ::fcntl(fd, F_GETFL);
|
||||
return flags >= 0 && (flags & (O_ACCMODE | O_PATH)) == mode && ::fstat(fd, &st) == 0 &&
|
||||
S_ISFIFO(st.st_mode);
|
||||
}
|
||||
|
||||
bool same_object(const struct stat &a, const struct stat &b) {
|
||||
return a.st_dev == b.st_dev && a.st_ino == b.st_ino;
|
||||
}
|
||||
|
||||
int fail(const char *reason, int error = 0) noexcept {
|
||||
// Even an invalid stdio setup must never put diagnostic bytes on the event/control channel.
|
||||
struct stat err{}, other{};
|
||||
if (!pipe_end(STDERR_FILENO, O_WRONLY, err))
|
||||
return setup_failure;
|
||||
for (int fd : {STDIN_FILENO, STDOUT_FILENO}) {
|
||||
if (::fstat(fd, &other) == 0 && same_object(err, other))
|
||||
return setup_failure;
|
||||
}
|
||||
// The supervisor may have already closed or stopped draining its diagnostics pipe.
|
||||
const int flags = ::fcntl(STDERR_FILENO, F_GETFL);
|
||||
if (flags >= 0 && ::fcntl(STDERR_FILENO, F_SETFL, flags | O_NONBLOCK) == 0 &&
|
||||
::signal(SIGPIPE, SIG_IGN) != SIG_ERR) {
|
||||
char message[160];
|
||||
const int n = error ? std::snprintf(message, sizeof message, "gcc leaf: %s (errno %d)\n",
|
||||
reason, error)
|
||||
: std::snprintf(message, sizeof message, "gcc leaf: %s\n", reason);
|
||||
if (n > 0 && static_cast<std::size_t>(n) < sizeof message)
|
||||
(void)::write(STDERR_FILENO, message, static_cast<std::size_t>(n));
|
||||
}
|
||||
return setup_failure;
|
||||
}
|
||||
|
||||
bool reset_signals() {
|
||||
struct sigaction action{};
|
||||
action.sa_handler = SIG_DFL;
|
||||
::sigemptyset(&action.sa_mask);
|
||||
for (int sig : {SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGPIPE, SIGXCPU, SIGXFSZ}) {
|
||||
if (::sigaction(sig, &action, nullptr) != 0)
|
||||
return false;
|
||||
}
|
||||
return ::sigprocmask(SIG_SETMASK, &action.sa_mask, nullptr) == 0;
|
||||
}
|
||||
|
||||
bool cap_resource(int resource, rlim_t soft, rlim_t hard) {
|
||||
struct rlimit limit{};
|
||||
if (::getrlimit(resource, &limit) != 0)
|
||||
return false;
|
||||
limit.rlim_cur = std::min(limit.rlim_cur, soft);
|
||||
limit.rlim_max = std::min(limit.rlim_max, hard);
|
||||
return ::setrlimit(resource, &limit) == 0;
|
||||
}
|
||||
|
||||
bool write_chunk(int fd, std::span<const std::byte> bytes) {
|
||||
while (!bytes.empty()) {
|
||||
const ssize_t count = ::write(fd, bytes.data(), bytes.size());
|
||||
if (count < 0 && errno == EINTR)
|
||||
continue;
|
||||
if (count <= 0)
|
||||
return false;
|
||||
bytes = bytes.subspan(static_cast<std::size_t>(count));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool complete_native_elf(std::span<const std::byte> image) {
|
||||
const auto fits = [&](std::uint64_t offset, std::uint64_t size) {
|
||||
return offset <= image.size() && size <= image.size() - offset;
|
||||
};
|
||||
ElfW(Ehdr) header{};
|
||||
if (image.size() < sizeof header)
|
||||
return false;
|
||||
std::memcpy(&header, image.data(), sizeof header);
|
||||
if (std::memcmp(header.e_ident, __ehdr_start.e_ident, EI_VERSION + 1) != 0 ||
|
||||
header.e_machine != __ehdr_start.e_machine || header.e_version != EV_CURRENT ||
|
||||
(header.e_type != ET_EXEC && header.e_type != ET_DYN) || header.e_ehsize != sizeof header ||
|
||||
header.e_phoff < sizeof header || header.e_phentsize != sizeof(ElfW(Phdr)) ||
|
||||
!header.e_phnum || header.e_phnum == PN_XNUM ||
|
||||
!fits(header.e_phoff, sizeof(ElfW(Phdr)) * header.e_phnum))
|
||||
return false;
|
||||
|
||||
// A truncated section table can leave an otherwise runnable prefix of the file.
|
||||
if (header.e_shoff || header.e_shnum || header.e_shstrndx) {
|
||||
if (header.e_shoff < sizeof header || !header.e_shnum ||
|
||||
header.e_shstrndx >= header.e_shnum || header.e_shentsize != sizeof(ElfW(Shdr)) ||
|
||||
!fits(header.e_shoff, sizeof(ElfW(Shdr)) * header.e_shnum))
|
||||
return false;
|
||||
for (unsigned i = 0; i < header.e_shnum; ++i) {
|
||||
ElfW(Shdr) section{};
|
||||
std::memcpy(§ion, image.data() + header.e_shoff + i * sizeof section,
|
||||
sizeof section);
|
||||
if (section.sh_type != SHT_NOBITS && !fits(section.sh_offset, section.sh_size))
|
||||
return false;
|
||||
}
|
||||
}
|
||||
bool has_entry = false;
|
||||
for (unsigned i = 0; i < header.e_phnum; ++i) {
|
||||
ElfW(Phdr) segment{};
|
||||
std::memcpy(&segment, image.data() + header.e_phoff + i * sizeof segment, sizeof segment);
|
||||
if (segment.p_filesz && !fits(segment.p_offset, segment.p_filesz))
|
||||
return false;
|
||||
if (segment.p_type != PT_LOAD)
|
||||
continue;
|
||||
if (segment.p_filesz > segment.p_memsz)
|
||||
return false;
|
||||
if ((segment.p_flags & PF_X) && header.e_entry >= segment.p_vaddr &&
|
||||
header.e_entry - segment.p_vaddr < segment.p_filesz)
|
||||
has_entry = true;
|
||||
}
|
||||
return has_entry;
|
||||
}
|
||||
|
||||
const char *verify_bytes(std::span<const std::byte> image, std::string_view expected) {
|
||||
if (!complete_native_elf(image))
|
||||
return "incomplete or unsupported native ELF";
|
||||
const auto digest = Void::Crypto::hash(Void::Crypto::HashAlgorithm::Sha256, image,
|
||||
{.prefer_builtin = true});
|
||||
if (!digest || digest->size() != 32)
|
||||
return "SHA-256 unavailable";
|
||||
constexpr std::string_view alphabet = "0123456789abcdef";
|
||||
for (std::size_t i = 0; i < digest->size(); ++i) {
|
||||
const auto byte = std::to_integer<unsigned>((*digest)[i]);
|
||||
if (expected[2 * i] != alphabet[byte >> 4] || expected[2 * i + 1] != alphabet[byte & 15])
|
||||
return "compiler SHA-256 mismatch";
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
int prepare_image(int image, const std::filesystem::path &compiler, std::string_view expected) {
|
||||
const open_how how{.flags = O_PATH | O_CLOEXEC, .mode = 0, .resolve = RESOLVE_NO_SYMLINKS};
|
||||
const OwnedFd source{static_cast<int>(::syscall(SYS_openat2, AT_FDCWD, compiler.c_str(),
|
||||
&how, sizeof how))};
|
||||
struct stat before{};
|
||||
if (!source || ::fstat(source.get(), &before) != 0)
|
||||
return fail("cannot open direct compiler path with openat2", errno);
|
||||
if (!S_ISREG(before.st_mode) || before.st_size <= 0 ||
|
||||
static_cast<std::uint64_t>(before.st_size) > max_image)
|
||||
return fail("expected a nonempty regular compiler within the image limit");
|
||||
struct rlimit file_limit{};
|
||||
if (::getrlimit(RLIMIT_FSIZE, &file_limit) != 0 ||
|
||||
static_cast<std::uint64_t>(before.st_size) > file_limit.rlim_cur)
|
||||
return fail("inherited file-size limit cannot hold the compiler");
|
||||
const auto copied = File::stream_regular_fd(source, before, max_image, true, [&](auto chunk) {
|
||||
return write_chunk(image, chunk);
|
||||
});
|
||||
if (!copied)
|
||||
return fail("failed to capture stable executable compiler");
|
||||
|
||||
constexpr int seals = F_SEAL_WRITE | F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_EXEC | F_SEAL_SEAL;
|
||||
if (::fchmod(image, S_IRUSR | S_IXUSR) != 0 || ::fcntl(image, F_ADD_SEALS, seals) != 0)
|
||||
return fail("kernel refused to seal the compiler memfd", errno);
|
||||
struct stat sealed{};
|
||||
if (::fstat(image, &sealed) != 0 || sealed.st_size != before.st_size)
|
||||
return fail("sealed compiler size changed");
|
||||
|
||||
// Hash the sealed object itself. A concurrent source rewrite or pathname exchange cannot
|
||||
// change the bytes inspected here or the ELF the kernel will load.
|
||||
const auto size = static_cast<std::size_t>(sealed.st_size);
|
||||
void *mapping = ::mmap(nullptr, size, PROT_READ, MAP_PRIVATE, image, 0);
|
||||
if (mapping == MAP_FAILED)
|
||||
return fail("cannot map sealed compiler", errno);
|
||||
struct Mapping {
|
||||
void *address;
|
||||
std::size_t size;
|
||||
~Mapping() { ::munmap(address, size); }
|
||||
} view{mapping, size};
|
||||
const auto *error = verify_bytes({static_cast<const std::byte *>(mapping), size}, expected);
|
||||
return error ? fail(error) : 0;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int run_leaf(std::filesystem::path compiler, std::string_view expected_sha256,
|
||||
std::string_view nonce, bool stepping) try {
|
||||
struct stat in{}, out{}, err{};
|
||||
if (!pipe_end(STDIN_FILENO, O_RDONLY, in) || !pipe_end(STDOUT_FILENO, O_WRONLY, out) ||
|
||||
!pipe_end(STDERR_FILENO, O_WRONLY, err) || same_object(in, out) || same_object(in, err) ||
|
||||
same_object(out, err))
|
||||
return fail("expected three distinct directed pipes");
|
||||
if (!lower_hex(nonce, 32) || !lower_hex(expected_sha256, 64))
|
||||
return fail("invalid nonce or SHA-256");
|
||||
if (!File::valid_path(compiler) || !compiler.is_absolute())
|
||||
return fail("expected an absolute compiler path");
|
||||
|
||||
const OwnedFd control{::dup2(STDIN_FILENO, control_fd)};
|
||||
const OwnedFd events{::dup2(STDOUT_FILENO, events_fd)};
|
||||
if (!control || !events || ::fcntl(STDERR_FILENO, F_SETFD, 0) != 0 ||
|
||||
::close_range(events_fd + 1, UINT_MAX, 0) != 0)
|
||||
return fail("cannot isolate inherited descriptors", errno);
|
||||
const OwnedFd null{::open("/dev/null", O_RDWR | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)};
|
||||
struct stat device{};
|
||||
if (!null || ::fstat(null.get(), &device) != 0 || !S_ISCHR(device.st_mode) ||
|
||||
device.st_rdev != makedev(1, 3) || ::dup2(null.get(), STDIN_FILENO) < 0 ||
|
||||
::dup2(null.get(), STDOUT_FILENO) < 0)
|
||||
return fail("cannot isolate raw compiler stdio");
|
||||
if (!reset_signals() || !cap_resource(RLIMIT_CORE, 0, 0) ||
|
||||
!cap_resource(RLIMIT_AS, 768 * mib, 768 * mib) || !cap_resource(RLIMIT_CPU, 15, 20) ||
|
||||
!cap_resource(RLIMIT_NOFILE, 32, 32))
|
||||
return fail("cannot set compiler signals or resource limits", errno);
|
||||
|
||||
const OwnedFd image{::memfd_create("vls-cc1plus", MFD_CLOEXEC | MFD_ALLOW_SEALING | MFD_EXEC)};
|
||||
if (!image)
|
||||
return fail("executable memfd unsupported or denied", errno);
|
||||
if (const int status = prepare_image(image.get(), compiler, expected_sha256))
|
||||
return status;
|
||||
if (!cap_resource(RLIMIT_FSIZE, mib, mib))
|
||||
return fail("cannot set compiler output limit", errno);
|
||||
|
||||
char nonce_env[] = "VLS_GCC_NONCE=00000000000000000000000000000000";
|
||||
std::memcpy(nonce_env + sizeof("VLS_GCC_NONCE=") - 1, nonce.data(), nonce.size());
|
||||
const char *environment[] = {"LC_ALL=C", "PATH=", nonce_env, nullptr};
|
||||
const char *arguments[] = {"cc1plus", "-quiet", "-std=c++26", "-freflection", "-fsyntax-only",
|
||||
"-nostdinc", "-o", "/dev/null", "-fvls-observe",
|
||||
stepping ? "-fvls-step" : "input.cpp", stepping ? "input.cpp" : nullptr,
|
||||
nullptr};
|
||||
::execveat(image.get(), "", const_cast<char *const *>(arguments),
|
||||
const_cast<char *const *>(environment), AT_EMPTY_PATH);
|
||||
return fail("execveat of sealed compiler failed", errno);
|
||||
} catch (...) {
|
||||
return fail("compiler image setup failed");
|
||||
}
|
||||
} // namespace vls::gcc
|
||||
#else
|
||||
int vls::gcc::run_leaf(std::filesystem::path, std::string_view, std::string_view, bool) {
|
||||
std::fputs("gcc leaf: Linux executable memfd support is required\n", stderr);
|
||||
return 126;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include <filesystem>
|
||||
#include <string_view>
|
||||
|
||||
namespace vls::gcc {
|
||||
|
||||
// Call only in the dedicated --leaf child, with cwd set to the private input.cpp directory.
|
||||
// Success replaces the process. On setup failure the child must exit with the returned status.
|
||||
[[nodiscard]] int run_leaf(std::filesystem::path compiler, std::string_view expected_sha256,
|
||||
std::string_view nonce, bool stepping);
|
||||
|
||||
} // namespace vls::gcc
|
||||
@@ -0,0 +1,67 @@
|
||||
#include "Leaf.hpp"
|
||||
#include "Supervisor.hpp"
|
||||
#include "Trace.hpp"
|
||||
|
||||
#include <charconv>
|
||||
#include <csignal>
|
||||
#include <iostream>
|
||||
|
||||
namespace {
|
||||
constexpr std::string_view usage =
|
||||
"vls_gcc_probe run COMPILER SHA256 SOURCE NEW_TRACE [--step]\n"
|
||||
"vls_gcc_probe replay TRACE [EVENT_SEQUENCE]\n"
|
||||
"At a stop, send NONCE STOP inspect|step|continue|cancel and a newline.\n"
|
||||
"During a stepped run, NONCE cancel cancels the running frontend.\n";
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) try {
|
||||
using namespace vls::gcc;
|
||||
const std::string_view mode = argc >= 2 ? argv[1] : "";
|
||||
if (mode == "--leaf" && argc == 6) {
|
||||
const std::string_view action{argv[5]};
|
||||
if (action != "step" && action != "observe")
|
||||
return 126;
|
||||
return run_leaf(argv[2], argv[3], argv[4], action == "step");
|
||||
}
|
||||
if (mode == "--help" && argc == 2) {
|
||||
std::cout << usage;
|
||||
return 0;
|
||||
}
|
||||
std::signal(SIGPIPE, SIG_IGN);
|
||||
if (mode == "run" && (argc == 6 || (argc == 7 && std::string_view(argv[6]) == "--step"))) {
|
||||
RunOptions options{std::filesystem::absolute(argv[2]), argv[3],
|
||||
std::filesystem::absolute(argv[4]), std::filesystem::absolute(argv[5]),
|
||||
argc == 7};
|
||||
auto result = run_session(options);
|
||||
if (!result) {
|
||||
std::cerr << "vls_gcc_probe: " << result.error() << '\n';
|
||||
return 1;
|
||||
}
|
||||
return *result;
|
||||
}
|
||||
if (mode == "replay" && (argc == 3 || argc == 4)) {
|
||||
std::optional<std::uint32_t> sequence;
|
||||
if (argc == 4) {
|
||||
const std::string_view text{argv[3]};
|
||||
const auto end = text.data() + text.size();
|
||||
auto [last, error] = std::from_chars(text.data(), end, sequence.emplace());
|
||||
if (error != std::errc{} || last != end)
|
||||
return 2;
|
||||
}
|
||||
auto snapshot = replay(std::filesystem::absolute(argv[2]), sequence);
|
||||
if (!snapshot) {
|
||||
std::cerr << "vls_gcc_probe: " << snapshot.error() << '\n';
|
||||
return 1;
|
||||
}
|
||||
auto json = Protocol::serialize_json(*snapshot);
|
||||
if (!json)
|
||||
return 1;
|
||||
std::cout << *json << '\n';
|
||||
return std::cout ? 0 : 1;
|
||||
}
|
||||
std::cerr << usage;
|
||||
return 2;
|
||||
} catch (const std::exception &error) {
|
||||
std::cerr << "vls_gcc_probe: " << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
#include "Supervisor.hpp"
|
||||
#include "Trace.hpp"
|
||||
|
||||
#include <Void/LanguageServer/Support/RegularFile.hpp>
|
||||
#include <Void/System/Process.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <csignal>
|
||||
#include <fstream>
|
||||
#include <poll.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/random.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace vls::gcc {
|
||||
namespace {
|
||||
using namespace std::chrono_literals;
|
||||
using Clock = std::chrono::steady_clock;
|
||||
using Protocol::Json;
|
||||
using Void::Process::Child;
|
||||
constexpr std::size_t source_limit = 256 * 1024;
|
||||
constexpr std::size_t diagnostic_limit = 256 * 1024;
|
||||
volatile std::sig_atomic_t interrupted = 0;
|
||||
void interrupt(int) { interrupted = 1; }
|
||||
|
||||
std::expected<std::string, std::string> make_nonce() {
|
||||
std::array<unsigned char, 16> bytes{};
|
||||
for (std::size_t used = 0; used < bytes.size();) {
|
||||
const auto n = ::getrandom(bytes.data() + used, bytes.size() - used, 0);
|
||||
if (n < 0 && errno == EINTR)
|
||||
continue;
|
||||
if (n <= 0)
|
||||
return std::unexpected{"cannot create a session nonce"};
|
||||
used += static_cast<std::size_t>(n);
|
||||
}
|
||||
std::string nonce;
|
||||
constexpr std::string_view alphabet = "0123456789abcdef";
|
||||
for (const auto byte : bytes) {
|
||||
nonce += alphabet[byte >> 4];
|
||||
nonce += alphabet[byte & 15];
|
||||
}
|
||||
return nonce;
|
||||
}
|
||||
|
||||
class Nonblocking {
|
||||
public:
|
||||
explicit Nonblocking(int fd) : fd_(fd), flags_(::fcntl(fd, F_GETFL)) {
|
||||
ok = flags_ >= 0 && ::fcntl(fd, F_SETFL, flags_ | O_NONBLOCK) == 0;
|
||||
}
|
||||
~Nonblocking() {
|
||||
if (ok)
|
||||
::fcntl(fd_, F_SETFL, flags_);
|
||||
}
|
||||
Nonblocking(const Nonblocking &) = delete;
|
||||
bool ok{};
|
||||
private:
|
||||
int fd_, flags_;
|
||||
};
|
||||
|
||||
bool write_bounded(int fd, std::string_view bytes) {
|
||||
const auto deadline = Clock::now() + 200ms;
|
||||
while (!bytes.empty() && Clock::now() < deadline) {
|
||||
const auto n = ::write(fd, bytes.data(), bytes.size());
|
||||
if (n > 0) {
|
||||
bytes.remove_prefix(static_cast<std::size_t>(n));
|
||||
continue;
|
||||
}
|
||||
if (n < 0 && errno == EINTR)
|
||||
continue;
|
||||
if (n >= 0 || (errno != EAGAIN && errno != EWOULDBLOCK))
|
||||
return false;
|
||||
pollfd p{fd, POLLOUT, 0};
|
||||
if (::poll(&p, 1, 10) < 0 && errno != EINTR)
|
||||
return false;
|
||||
}
|
||||
return bytes.empty();
|
||||
}
|
||||
|
||||
bool notice(Json::Object fields) {
|
||||
auto encoded = Protocol::serialize_json(Json{std::move(fields)});
|
||||
if (!encoded || encoded->size() > 65535)
|
||||
return false;
|
||||
encoded->push_back('\n');
|
||||
return write_bounded(STDOUT_FILENO, *encoded);
|
||||
}
|
||||
|
||||
struct Pump {
|
||||
Child &child;
|
||||
Trace &trace;
|
||||
const std::string &nonce;
|
||||
const bool interactive;
|
||||
std::string diagnostics, event_line, control_line, error;
|
||||
std::optional<Void::Process::ExitStatus> status;
|
||||
std::optional<std::uint32_t> control_origin;
|
||||
std::optional<Clock::time_point> stopped_at, reaped_at, command_deadline;
|
||||
Clock::time_point running_since = Clock::now();
|
||||
Clock::duration running_time{};
|
||||
bool saw_hello{}, events_open{true}, diagnostics_open{true}, controls_open{interactive};
|
||||
std::string outcome;
|
||||
unsigned rejected{};
|
||||
|
||||
Pump(Child &child, Trace &trace, const std::string &nonce, bool interactive)
|
||||
: child(child), trace(trace), nonce(nonce), interactive(interactive) {}
|
||||
|
||||
void stop(std::string_view state, std::string reason) {
|
||||
if (outcome.empty()) {
|
||||
outcome = state;
|
||||
error = std::move(reason);
|
||||
}
|
||||
}
|
||||
|
||||
void accept_event() {
|
||||
auto accepted = trace.event(event_line);
|
||||
if (!accepted)
|
||||
return stop("truncated", accepted.error());
|
||||
auto json = Protocol::parse_json(event_line);
|
||||
const auto *obj = json ? Protocol::as_object(&*json) : nullptr;
|
||||
const auto *kind = obj ? Protocol::as_string(Protocol::find_member(*obj, "kind")) : nullptr;
|
||||
if (!kind)
|
||||
return stop("truncated", "event lacks a kind");
|
||||
if (*kind == "hello") {
|
||||
saw_hello = true;
|
||||
if (!notice({{"kind", Json{std::string{"started"}}}, {"nonce", Json{nonce}},
|
||||
{"pid", Json{static_cast<std::int64_t>(child.pid())}}}))
|
||||
stop("cancelled", "client output closed");
|
||||
} else if (*kind == "stopped") {
|
||||
const auto seq = trace.stopped();
|
||||
if (!interactive || !seq || stopped_at)
|
||||
return stop("truncated", "unexpected compiler stop");
|
||||
const auto now = Clock::now();
|
||||
running_time += now - running_since;
|
||||
stopped_at = now;
|
||||
if (!notice({{"kind", Json{std::string{"stopped"}}}, {"nonce", Json{nonce}},
|
||||
{"stop", Json{static_cast<std::int64_t>(*seq)}}}))
|
||||
stop("cancelled", "client output closed");
|
||||
} else if (*kind == "resumed" || *kind == "terminal") {
|
||||
command_deadline.reset();
|
||||
if (stopped_at) {
|
||||
stopped_at.reset();
|
||||
running_since = Clock::now();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void reject() {
|
||||
if (++rejected >= 32 || !notice({{"kind", Json{std::string{"rejected"}}}}))
|
||||
stop("cancelled", "control limit or client disconnect");
|
||||
}
|
||||
|
||||
void control(std::string_view line) {
|
||||
const auto space = line.find(' ');
|
||||
if (space == line.npos || line.substr(0, space) != nonce)
|
||||
return reject();
|
||||
line.remove_prefix(space + 1);
|
||||
if (line == "cancel" && !stopped_at)
|
||||
return stop("cancelled", "cancelled while running");
|
||||
const auto split = line.find(' ');
|
||||
if (split == line.npos || !stopped_at || command_deadline)
|
||||
return reject();
|
||||
std::uint32_t seq{};
|
||||
const auto [end, ec] = std::from_chars(line.data(), line.data() + split, seq);
|
||||
const auto action = line.substr(split + 1);
|
||||
if (ec != std::errc{} || end != line.data() + split || seq != control_origin ||
|
||||
seq != trace.stopped() || (split > 1 && line.front() == '0'))
|
||||
return reject();
|
||||
if (action == "inspect") {
|
||||
auto snapshot = trace.inspection();
|
||||
auto encoded = Protocol::serialize_json(snapshot);
|
||||
if (!encoded || encoded->size() > 64000) {
|
||||
if (!notice({{"kind", Json{std::string{"inspectionLimit"}}},
|
||||
{"stop", Json{static_cast<std::int64_t>(seq)}}}))
|
||||
stop("cancelled", "client output closed");
|
||||
} else if (!notice({{"kind", Json{std::string{"inspection"}}},
|
||||
{"snapshot", std::move(snapshot)}})) {
|
||||
stop("cancelled", "client output closed");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action != "step" && action != "continue" && action != "cancel")
|
||||
return reject();
|
||||
auto accepted = trace.authorize(seq, action);
|
||||
if (!accepted)
|
||||
return stop("failed", accepted.error());
|
||||
command_deadline = Clock::now() + 2s;
|
||||
if (!write_bounded(child.stdin_fd(), nonce + " " + std::string{line} + "\n"))
|
||||
stop("truncated", "compiler control pipe closed");
|
||||
}
|
||||
|
||||
enum class Channel { client, events, diagnostics };
|
||||
void read_ready(Channel channel, int fd) {
|
||||
std::array<char, 8192> bytes{};
|
||||
const auto n = ::read(fd, bytes.data(), bytes.size());
|
||||
if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
|
||||
return;
|
||||
if (n < 0)
|
||||
return stop("truncated", "failed to read session pipe");
|
||||
if (n == 0) {
|
||||
if (channel == Channel::client) {
|
||||
controls_open = false;
|
||||
if (!status && !trace.ended() && trace.terminal().empty())
|
||||
stop("cancelled", "control client disconnected");
|
||||
} else if (channel == Channel::events) {
|
||||
events_open = false;
|
||||
if (!event_line.empty())
|
||||
stop("truncated", "incomplete compiler event");
|
||||
} else {
|
||||
diagnostics_open = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
const std::string_view data{bytes.data(), static_cast<std::size_t>(n)};
|
||||
if (channel == Channel::diagnostics) {
|
||||
const auto room = diagnostic_limit - diagnostics.size();
|
||||
diagnostics.append(data.substr(0, room));
|
||||
if (data.size() > room)
|
||||
stop("truncated", "compiler diagnostic limit exceeded");
|
||||
return;
|
||||
}
|
||||
auto &line = channel == Channel::client ? control_line : event_line;
|
||||
const std::size_t limit = channel == Channel::client ? 127 : 4095;
|
||||
for (const auto c : data) {
|
||||
if (channel == Channel::client && line.empty())
|
||||
control_origin = trace.stopped();
|
||||
if (c == '\n') {
|
||||
if (channel == Channel::client)
|
||||
control(line);
|
||||
else
|
||||
accept_event();
|
||||
line.clear();
|
||||
} else if (line.size() == limit) {
|
||||
return stop("truncated", "line exceeds the channel limit");
|
||||
} else {
|
||||
line.push_back(c);
|
||||
}
|
||||
if (!outcome.empty())
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void reap() {
|
||||
if (status)
|
||||
return;
|
||||
auto waited = child.try_wait();
|
||||
if (!waited)
|
||||
return stop("failed", "cannot wait for compiler");
|
||||
if (!*waited)
|
||||
return;
|
||||
status = **waited;
|
||||
reaped_at = Clock::now();
|
||||
if (child.process_group_alive()) {
|
||||
auto group = child.terminate(50ms);
|
||||
if (!group || child.process_group_alive())
|
||||
stop("failed", "compiler descendants survived termination");
|
||||
}
|
||||
}
|
||||
|
||||
void check_deadlines() {
|
||||
const auto now = Clock::now();
|
||||
if (interrupted)
|
||||
return stop("cancelled", "session interrupted");
|
||||
if (command_deadline && now >= *command_deadline)
|
||||
return stop("expired", "compiler failed to acknowledge the command");
|
||||
if (reaped_at && now - *reaped_at > 2s)
|
||||
return stop("truncated", "compiler pipes remained open after exit");
|
||||
if (stopped_at && now - *stopped_at > 55s)
|
||||
return stop("expired", "paused session expired");
|
||||
if (!stopped_at && running_time + now - running_since > 30s)
|
||||
stop("expired", "running session expired");
|
||||
}
|
||||
|
||||
std::expected<int, std::string> run() {
|
||||
while (outcome.empty() && (!status || events_open || diagnostics_open)) {
|
||||
check_deadlines();
|
||||
if (!outcome.empty())
|
||||
break;
|
||||
pollfd pipes[]{{controls_open ? STDIN_FILENO : -1, POLLIN, 0},
|
||||
{events_open ? child.stdout_fd() : -1, POLLIN, 0},
|
||||
{diagnostics_open ? child.stderr_fd() : -1, POLLIN, 0}};
|
||||
const int count = ::poll(pipes, 3, 25);
|
||||
if (count < 0 && errno != EINTR)
|
||||
stop("failed", "cannot poll compiler pipes");
|
||||
// Reject commands observed while running before accepting a new compiler stop.
|
||||
for (unsigned i = 0; i < 3 && outcome.empty(); ++i)
|
||||
if (count > 0 && pipes[i].revents != 0)
|
||||
read_ready(static_cast<Channel>(i), pipes[i].fd);
|
||||
reap();
|
||||
}
|
||||
if (!status || child.process_group_alive()) {
|
||||
auto done = child.terminate(50ms);
|
||||
if (!done)
|
||||
return std::unexpected{"failed to reap the compiler process group"};
|
||||
status = *done;
|
||||
}
|
||||
const auto code = status->exited ? status->code : 128 + status->signal;
|
||||
if (outcome.empty()) {
|
||||
if (trace.terminal() == "cancelled" && code == 125)
|
||||
outcome = "cancelled";
|
||||
else if (!saw_hello && code != 0)
|
||||
outcome = "failed";
|
||||
else if (!trace.terminal().empty() || !trace.ended())
|
||||
outcome = "truncated";
|
||||
else
|
||||
outcome = code == 0 ? "completed" : "failed";
|
||||
}
|
||||
auto saved = trace.finish(outcome, code, diagnostics);
|
||||
if (!saved)
|
||||
return std::unexpected{saved.error()};
|
||||
if (!notice({{"kind", Json{std::string{"finished"}}}, {"outcome", Json{outcome}},
|
||||
{"exitCode", Json{static_cast<std::int64_t>(code)}}, {"reason", Json{error}}}))
|
||||
return std::unexpected{"cannot deliver the final session status"};
|
||||
if (outcome == "completed")
|
||||
return 0;
|
||||
if (outcome == "cancelled")
|
||||
return 125;
|
||||
if (outcome == "expired")
|
||||
return 124;
|
||||
return outcome == "truncated" ? 126 : 1;
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
std::expected<int, std::string> run_session(const RunOptions &options) {
|
||||
if (options.compiler_sha256.size() != 64 ||
|
||||
options.compiler_sha256.find_first_not_of("0123456789abcdef") != std::string::npos)
|
||||
return std::unexpected{"expected a lowercase SHA-256"};
|
||||
std::string source;
|
||||
auto read = Void::LanguageServer::Detail::read_regular(options.source, source_limit, false, [&](auto part) {
|
||||
source.append(reinterpret_cast<const char *>(part.data()), part.size());
|
||||
return true;
|
||||
});
|
||||
if (!read || !Protocol::serialize_json(Json{source}))
|
||||
return std::unexpected{"input requires a stable UTF-8 source file within 256 KiB"};
|
||||
auto nonce = make_nonce();
|
||||
if (!nonce)
|
||||
return std::unexpected{nonce.error()};
|
||||
auto directory = Void::FileSystem::TempDir::open("vls-gcc-session-");
|
||||
if (!directory)
|
||||
return std::unexpected{"cannot create private compiler directory"};
|
||||
std::ofstream snapshot{directory->path() / "input.cpp", std::ios::binary};
|
||||
snapshot.write(source.data(), static_cast<std::streamsize>(source.size()));
|
||||
snapshot.close();
|
||||
if (!snapshot)
|
||||
return std::unexpected{"cannot write the compiler input"};
|
||||
if (::prctl(PR_SET_CHILD_SUBREAPER, 1) != 0)
|
||||
return std::unexpected{"cannot supervise compiler descendants"};
|
||||
interrupted = 0;
|
||||
std::signal(SIGTERM, interrupt);
|
||||
std::signal(SIGINT, interrupt);
|
||||
Void::Process::SpawnOptions launch;
|
||||
launch.executable = "/proc/self/exe";
|
||||
launch.arguments = {"--leaf", options.compiler.string(), options.compiler_sha256,
|
||||
*nonce, options.stepping ? "step" : "observe"};
|
||||
launch.working_directory = directory->path();
|
||||
launch.environment.mode = Void::Process::EnvMode::explicit_only;
|
||||
launch.search_path = false;
|
||||
launch.new_process_group = true;
|
||||
launch.kill_grace = 50ms;
|
||||
auto child = Void::Process::spawn(launch);
|
||||
if (!child)
|
||||
return std::unexpected{"cannot launch the private compiler worker"};
|
||||
auto trace = Trace::create(options.trace, source, options.compiler_sha256, *nonce, child->pid());
|
||||
if (!trace)
|
||||
return std::unexpected{trace.error()};
|
||||
Nonblocking output{STDOUT_FILENO}, controls{child->stdin_fd()};
|
||||
if (!output.ok || !controls.ok)
|
||||
return std::unexpected{"cannot set bounded session I/O"};
|
||||
Pump pump{*child, **trace, *nonce, options.stepping};
|
||||
return pump.run();
|
||||
}
|
||||
} // namespace vls::gcc
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include <expected>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
|
||||
namespace vls::gcc {
|
||||
|
||||
struct RunOptions {
|
||||
std::filesystem::path compiler;
|
||||
std::string compiler_sha256;
|
||||
std::filesystem::path source, trace;
|
||||
bool stepping{};
|
||||
};
|
||||
|
||||
[[nodiscard]] std::expected<int, std::string> run_session(const RunOptions &);
|
||||
|
||||
} // namespace vls::gcc
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,112 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/LanguageServer/Protocol/Json.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace vls::gcc {
|
||||
|
||||
namespace Protocol = Void::LanguageServer::Protocol;
|
||||
using TraceResult = std::expected<void, std::string>;
|
||||
|
||||
// The journal is exclusively created and binds the immutable input to this invocation.
|
||||
// Commands are journalled before dispatch. Acknowledgement is a separate compiler event.
|
||||
class Trace {
|
||||
public:
|
||||
static std::expected<std::unique_ptr<Trace>, std::string>
|
||||
create(const std::filesystem::path &output, std::string_view source,
|
||||
std::string_view compiler_sha, std::string_view nonce, std::int64_t pid);
|
||||
~Trace();
|
||||
[[nodiscard]] TraceResult event(std::string_view line);
|
||||
[[nodiscard]] TraceResult authorize(std::uint32_t stop, std::string_view action);
|
||||
[[nodiscard]] std::optional<std::uint32_t> stopped() const;
|
||||
[[nodiscard]] bool ended() const;
|
||||
[[nodiscard]] std::string_view terminal() const;
|
||||
[[nodiscard]] Protocol::Json inspection() const;
|
||||
[[nodiscard]] TraceResult finish(std::string_view outcome, int exit_code,
|
||||
std::string_view diagnostics);
|
||||
|
||||
private:
|
||||
struct State;
|
||||
explicit Trace(std::unique_ptr<State>);
|
||||
std::unique_ptr<State> state_;
|
||||
};
|
||||
|
||||
struct ReplayEvent {
|
||||
std::uint32_t sequence;
|
||||
std::string_view kind;
|
||||
std::optional<std::uint32_t> frame;
|
||||
std::optional<std::uint32_t> parent;
|
||||
// Present together on a compiler resumed event.
|
||||
std::optional<std::uint32_t> acknowledged_stop;
|
||||
std::optional<std::string_view> acknowledged_action;
|
||||
};
|
||||
|
||||
struct ReplayValuePoint {
|
||||
std::uint32_t value_sequence;
|
||||
std::optional<std::uint32_t> stop_sequence;
|
||||
};
|
||||
|
||||
struct ReplayMetadata {
|
||||
std::string_view backend;
|
||||
std::string_view nonce;
|
||||
std::int64_t pid;
|
||||
std::string_view compiler_sha256;
|
||||
std::string_view source_sha256;
|
||||
bool partial;
|
||||
bool corrupt;
|
||||
std::optional<std::string_view> journal_error;
|
||||
std::optional<std::string_view> outcome;
|
||||
std::optional<int> exit_code;
|
||||
};
|
||||
|
||||
// Views borrow this recording. A shared owner keeps its validated prefix and raw bytes alive.
|
||||
class ReplayRecording {
|
||||
public:
|
||||
static std::expected<std::shared_ptr<const ReplayRecording>, std::string>
|
||||
open(const std::filesystem::path &absolute_path);
|
||||
~ReplayRecording();
|
||||
|
||||
[[nodiscard]] ReplayMetadata metadata() const;
|
||||
[[nodiscard]] std::string_view source_bytes() const;
|
||||
[[nodiscard]] std::optional<std::string_view> diagnostic_bytes() const;
|
||||
[[nodiscard]] std::size_t event_count() const;
|
||||
|
||||
// Zero-based offset; offset == event_count() is an empty page. Larger offsets or
|
||||
// requests above max_page_size return an error. The span is an O(1) immutable slice.
|
||||
static constexpr std::size_t max_page_size = 256;
|
||||
[[nodiscard]] std::expected<std::span<const ReplayEvent>, std::string>
|
||||
event_page(std::size_t offset, std::size_t count) const;
|
||||
|
||||
// Strictly beyond the entire value/optional-stop pair. Omit the anchor for first/last.
|
||||
// A boundary returns an empty optional; a sequence outside the verified prefix is an error.
|
||||
[[nodiscard]] std::expected<std::optional<ReplayValuePoint>, std::string>
|
||||
next_value(std::optional<std::uint32_t> after = {}) const;
|
||||
[[nodiscard]] std::expected<std::optional<ReplayValuePoint>, std::string>
|
||||
previous_value(std::optional<std::uint32_t> before = {}) const;
|
||||
|
||||
// Owned JSON uses Trace's frame schema. Historical state is immediately after the event.
|
||||
// final_cursor also sees subsequent command authorization and final stop consumption.
|
||||
// Each query copies only its active frames, last leave and identity, at most 4096 events deep.
|
||||
[[nodiscard]] std::expected<Protocol::Json, std::string>
|
||||
cursor_at(std::uint32_t sequence) const;
|
||||
[[nodiscard]] Protocol::Json final_cursor() const;
|
||||
|
||||
private:
|
||||
struct State;
|
||||
explicit ReplayRecording(std::unique_ptr<State>);
|
||||
std::unique_ptr<const State> state_;
|
||||
};
|
||||
|
||||
[[nodiscard]] std::expected<Protocol::Json, std::string>
|
||||
replay(const std::filesystem::path &journal, std::optional<std::uint32_t> sequence);
|
||||
|
||||
} // namespace vls::gcc
|
||||
Reference in new issue
Block a user