Files
Language-Server/experiments/frontend/gcc-worker/Supervisor.cpp
T
faumaray da8003f6d4 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.
2026-12-05 14:06:50 +03:00

375 lines
15 KiB
C++

#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