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:
faumaray committed 2026-12-05 14:06:50 +03:00
1 parent ca04975d54
commit da8003f6d4
310 files changed
+47552 -480

No files matched your search

@@ -0,0 +1,724 @@
// Local stock GCC 16.2 occurrence observer for VLS.
//
// The plugin publishes compiler-owned facts for resolved direct calls and
// actual function definitions in the captured file set. It reads a private
// manifest (fixed path or VLS_OBSERVER_INPUTS on the test leg), verifies every
// physical span against the captured UTF-8 bytes, and writes one strict JSON
// report (fixed path or VLS_OBSERVER_OUTPUT). No tree, line map or parser
// pointer escapes this process.
#include "gcc-plugin.h"
#include "plugin-version.h"
#include "cp/cp-tree.h"
#include "cpplib.h"
#include "diagnostic.h"
#include "function.h"
#include "input.h"
#include <cerrno>
#include <climits>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
int plugin_is_GPL_compatible;
namespace {
constexpr unsigned max_name = 64;
constexpr unsigned max_type = 160;
constexpr unsigned max_signature = 300;
constexpr unsigned max_path = 4095;
constexpr unsigned max_inputs = 1024;
constexpr unsigned max_occurrences = 256;
constexpr std::size_t max_file = 16U * 1024U * 1024U;
constexpr std::size_t max_total = 64U * 1024U * 1024U;
constexpr std::size_t max_manifest = 4U * 1024U * 1024U;
constexpr unsigned max_visited = 200000;
struct span {
unsigned line{};
unsigned start{};
unsigned end{};
bool same(const span &other) const {
return line == other.line && start == other.start && end == other.end;
}
};
struct file_entry {
char path[max_path + 1]{};
unsigned char *data{};
std::size_t size{};
};
struct body_entry {
unsigned uid{};
span where{};
char path[max_path + 1]{};
bool definition{};
bool conflict{};
};
struct use_entry {
unsigned uid{};
span where{};
char path[max_path + 1]{};
char name[max_name + 1]{};
char type[max_type + 1]{};
char canonical[max_type + 1]{};
char signature[max_signature + 1]{};
bool conflict{};
};
char nonce[33];
char primary_path[max_path + 1];
file_entry files[max_inputs];
unsigned file_count;
body_entry bodies[max_occurrences];
unsigned body_count;
use_entry uses[max_occurrences];
unsigned use_count;
std::size_t total_bytes;
unsigned visited;
bool at_capacity;
bool withheld_origin;
bool withheld_semantics;
bool withheld_conflict;
bool over_walk;
bool admitted(const char *path) {
if (!path) {
return false;
}
for (unsigned i = 0; i != file_count; ++i) {
if (!std::strcmp(files[i].path, path)) {
return true;
}
}
return false;
}
file_entry *file_for(const char *path) {
if (!path) {
return nullptr;
}
for (unsigned i = 0; i != file_count; ++i) {
if (!std::strcmp(files[i].path, path)) {
return &files[i];
}
}
return nullptr;
}
bool load_file(const char *path) {
if (file_count == max_inputs) {
return false;
}
const int fd = ::open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
if (fd < 0) {
return false;
}
struct stat st{};
if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_size < 0 ||
static_cast<std::uint64_t>(st.st_size) > max_file ||
total_bytes + static_cast<std::size_t>(st.st_size) > max_total) {
::close(fd);
return false;
}
const auto size = static_cast<std::size_t>(st.st_size);
auto *data = static_cast<unsigned char *>(xmalloc(size ? size : 1));
if (!data) {
::close(fd);
return false;
}
std::size_t done = 0;
while (done != size) {
const ssize_t n = ::read(fd, data + done, size - done);
if (n <= 0) {
free(data);
::close(fd);
return false;
}
done += static_cast<std::size_t>(n);
}
::close(fd);
file_entry &entry = files[file_count++];
std::strcpy(entry.path, path);
entry.data = data;
entry.size = size;
total_bytes += size;
return true;
}
bool parse_manifest() {
const char *input = std::getenv("VLS_OBSERVER_INPUTS");
if (!input || !*input) {
input = "/vls-observer/inputs";
}
const int fd = ::open(input, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
if (fd < 0) {
return false;
}
char *text = static_cast<char *>(xmalloc(max_manifest + 1));
if (!text) {
::close(fd);
return false;
}
std::size_t size = 0;
while (size != max_manifest) {
const ssize_t n = ::read(fd, text + size, max_manifest - size);
if (n == 0) {
break;
}
if (n < 0) {
free(text);
::close(fd);
return false;
}
size += static_cast<std::size_t>(n);
}
::close(fd);
if (size == max_manifest) {
free(text);
return false;
}
text[size] = '\0';
if (std::strlen(text) != size) {
free(text);
return false;
}
char *lines[max_inputs + 3];
unsigned count = 0;
char *cursor = text;
while (*cursor) {
if (count == max_inputs + 3) {
free(text);
return false;
}
lines[count++] = cursor;
char *end = std::strchr(cursor, '\n');
if (!end) {
break;
}
*end = '\0';
cursor = end + 1;
}
if (count < 3 || std::strcmp(lines[0], "VLS-OCCURRENCES-1") != 0 ||
std::strlen(lines[1]) != 32) {
free(text);
return false;
}
for (unsigned i = 0; i != 32; ++i) {
const char c = lines[1][i];
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) {
free(text);
return false;
}
}
std::strcpy(nonce, lines[1]);
std::strcpy(primary_path, lines[2]);
for (unsigned i = 2; i != count; ++i) {
const std::size_t length = std::strlen(lines[i]);
if (!length || length > max_path || lines[i][0] != '/') {
free(text);
return false;
}
if (!file_for(lines[i]) && !load_file(lines[i])) {
free(text);
return false;
}
}
free(text);
return true;
}
bool utf8_valid(const char *text) {
const auto *s = reinterpret_cast<const unsigned char *>(text);
while (*s) {
if (*s < 0x80) {
++s;
} else if ((*s & 0xE0) == 0xC0 && (s[1] & 0xC0) == 0x80) {
if (*s < 0xC2) {
return false;
}
s += 2;
} else if ((*s & 0xF0) == 0xE0 && (s[1] & 0xC0) == 0x80 && (s[2] & 0xC0) == 0x80) {
s += 3;
} else if ((*s & 0xF8) == 0xF0 && (s[1] & 0xC0) == 0x80 && (s[2] & 0xC0) == 0x80 &&
(s[3] & 0xC0) == 0x80) {
s += 4;
} else {
return false;
}
}
return true;
}
void json_string(std::FILE *out, const char *text) {
std::fputc('"', out);
for (const auto *s = reinterpret_cast<const unsigned char *>(text); *s; ++s) {
switch (*s) {
case '"':
std::fputs("\\\"", out);
break;
case '\\':
std::fputs("\\\\", out);
break;
case '\n':
std::fputs("\\n", out);
break;
case '\r':
std::fputs("\\r", out);
break;
case '\t':
std::fputs("\\t", out);
break;
default:
if (*s < 0x20) {
std::fprintf(out, "\\u%04x", unsigned(*s));
} else {
std::fputc(*s, out);
}
}
}
std::fputc('"', out);
}
bool plain_name(tree decl) {
if (!decl || TREE_CODE(decl) != FUNCTION_DECL || DECL_ARTIFICIAL(decl) || !DECL_NAME(decl)) {
return false;
}
if (fndecl_built_in_p(decl) || !TREE_TYPE(decl) ||
TREE_CODE(TREE_TYPE(decl)) != FUNCTION_TYPE) {
return false;
}
if (DECL_CONTEXT(decl) && TYPE_P(DECL_CONTEXT(decl))) {
return false;
}
if (DECL_LANG_SPECIFIC(decl) && DECL_TEMPLATE_INFO(decl)) {
return false;
}
tree id = DECL_NAME(decl);
const unsigned length = IDENTIFIER_LENGTH(id);
if (!length || length > max_name) {
return false;
}
const char *name = IDENTIFIER_POINTER(id);
for (unsigned i = 0; i != length; ++i) {
const char c = name[i];
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' ||
(i && c >= '0' && c <= '9'))) {
return false;
}
}
return true;
}
// One-based physical byte columns, end exclusive. GCC columns count bytes but
// a first-line UTF-8 BOM is not part of the column space, so it is restored.
bool token_span(location_t token, unsigned length, const char *expected, span &out,
const char **path_out) {
const location_t start = get_pure_location(get_start(token));
const location_t last = get_pure_location(get_finish(token));
if (RESERVED_LOCATION_P(start) || RESERVED_LOCATION_P(last) ||
get_pure_location(token) != start || from_macro_expansion_at(start) ||
from_macro_expansion_at(last)) {
return false;
}
const line_map *raw_map = linemap_lookup(line_table, start);
if (!raw_map || !MAP_ORDINARY_P(raw_map) || linemap_lookup(line_table, last) != raw_map) {
return false;
}
const line_map_ordinary *map = linemap_check_ordinary(raw_map);
if (map->sysp || !map->to_file) {
return false;
}
file_entry *file = file_for(map->to_file);
if (!file) {
return false;
}
const unsigned line = SOURCE_LINE(map, start);
const unsigned column = SOURCE_COLUMN(map, start);
const unsigned final = SOURCE_COLUMN(map, last);
if (!line || !column || SOURCE_LINE(map, last) != line || final == UINT_MAX || final < column ||
final - column + 1 != length) {
return false;
}
std::size_t line_start = 0;
for (unsigned current = 1; current != line; ++current) {
const void *newline = std::memchr(file->data + line_start, '\n', file->size - line_start);
if (!newline) {
return false;
}
line_start =
static_cast<std::size_t>(static_cast<const unsigned char *>(newline) - file->data) + 1;
}
const bool bom = line == 1 && file->size >= 3 && file->data[0] == 0xEF &&
file->data[1] == 0xBB && file->data[2] == 0xBF;
const std::size_t shift = bom ? 3 : 0;
const std::size_t begin = line_start + shift + column - 1;
if (begin + length > file->size || std::memcmp(file->data + begin, expected, length) != 0) {
return false;
}
out = {line, column + unsigned(shift), column + unsigned(shift) + length};
*path_out = file->path;
return true;
}
bool range_bytes(location_t location, file_entry *&file, std::size_t &begin, std::size_t &end) {
const location_t start = get_pure_location(get_start(location));
const location_t last = get_pure_location(get_finish(location));
if (RESERVED_LOCATION_P(start) || RESERVED_LOCATION_P(last) || from_macro_expansion_at(start) ||
from_macro_expansion_at(last)) {
return false;
}
const line_map *raw_map = linemap_lookup(line_table, start);
if (!raw_map || !MAP_ORDINARY_P(raw_map) || linemap_lookup(line_table, last) != raw_map) {
return false;
}
const line_map_ordinary *map = linemap_check_ordinary(raw_map);
if (map->sysp || !map->to_file) {
return false;
}
file = file_for(map->to_file);
if (!file) {
return false;
}
const unsigned line = SOURCE_LINE(map, start);
const unsigned column = SOURCE_COLUMN(map, start);
const unsigned final = SOURCE_COLUMN(map, last);
if (!line || !column || SOURCE_LINE(map, last) != line || final < column) {
return false;
}
std::size_t line_start = 0;
for (unsigned current = 1; current != line; ++current) {
const void *newline = std::memchr(file->data + line_start, '\n', file->size - line_start);
if (!newline) {
return false;
}
line_start =
static_cast<std::size_t>(static_cast<const unsigned char *>(newline) - file->data) + 1;
}
const bool bom = line == 1 && file->size >= 3 && file->data[0] == 0xEF &&
file->data[1] == 0xBB && file->data[2] == 0xBF;
const std::size_t shift = bom ? 3 : 0;
begin = line_start + shift + column - 1;
end = line_start + shift + final;
return begin < end && end <= file->size;
}
bool identifier_char(unsigned char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
}
// Isolate the terminal identifier before the first '(' inside the call range.
bool call_token(tree call, tree decl, span &out, const char **path_out) {
const location_t location = EXPR_LOCATION(call);
if (location == UNKNOWN_LOCATION) {
return false;
}
file_entry *file = nullptr;
std::size_t begin = 0;
std::size_t end = 0;
if (!range_bytes(location, file, begin, end)) {
return false;
}
std::size_t open = begin;
while (open != end && file->data[open] != '(') {
++open;
}
if (open == end) {
return false;
}
std::size_t stop = open;
while (stop != begin && (file->data[stop - 1] == ' ' || file->data[stop - 1] == '\t')) {
--stop;
}
std::size_t start = stop;
while (start != begin && identifier_char(file->data[start - 1])) {
--start;
}
const unsigned length = IDENTIFIER_LENGTH(DECL_NAME(decl));
if (stop - start != length ||
std::memcmp(file->data + start, IDENTIFIER_POINTER(DECL_NAME(decl)), length) != 0) {
return false;
}
// The conservative grammar admits one physical line for the callee prefix.
if (std::memchr(file->data + begin, '\n', start - begin)) {
return false;
}
unsigned line = 1;
std::size_t line_start = 0;
for (std::size_t i = 0; i != start; ++i) {
if (file->data[i] == '\n') {
++line;
line_start = i + 1;
}
}
if (line_start > start || start - line_start > UINT_MAX - 1) {
return false;
}
out = {line, unsigned(start - line_start + 1), unsigned(stop - line_start + 1)};
*path_out = file->path;
return true;
}
body_entry *find_body(unsigned uid) {
for (unsigned i = 0; i != body_count; ++i) {
if (bodies[i].uid == uid) {
return &bodies[i];
}
}
return nullptr;
}
void record_body(tree decl) {
if (!plain_name(decl) || at_capacity) {
return;
}
const location_t location = DECL_SOURCE_LOCATION(decl);
if (RESERVED_LOCATION_P(location) || from_macro_expansion_at(get_pure_location(location))) {
return;
}
span where;
const char *path = nullptr;
if (!token_span(location, IDENTIFIER_LENGTH(DECL_NAME(decl)),
IDENTIFIER_POINTER(DECL_NAME(decl)), where, &path)) {
withheld_origin = true;
return;
}
const unsigned uid = DECL_UID(decl);
if (body_entry *old = find_body(uid)) {
if (!old->where.same(where)) {
old->conflict = true;
withheld_conflict = true;
}
old->definition = true;
return;
}
if (body_count == max_occurrences) {
at_capacity = true;
return;
}
body_entry &entry = bodies[body_count++];
entry.uid = uid;
entry.where = where;
std::strcpy(entry.path, path);
entry.definition = true;
}
void record_use(tree call, tree decl) {
if (at_capacity) {
return;
}
if (!plain_name(decl)) {
withheld_semantics = true;
return;
}
const tree type = TREE_TYPE(call);
if (!type || type == error_mark_node) {
withheld_semantics = true;
return;
}
span where;
const char *path = nullptr;
if (!call_token(call, decl, where, &path)) {
withheld_origin = true;
return;
}
const char *type_text = type_as_string(type, TFF_SCOPE);
const tree canonical_type = TYPE_CANONICAL(type) ? TYPE_CANONICAL(type) : type;
const char *canonical_text = type_as_string(canonical_type, TFF_SCOPE);
if (!type_text || !canonical_text || std::strlen(type_text) > max_type ||
std::strlen(canonical_text) > max_type || !utf8_valid(type_text) ||
!utf8_valid(canonical_text) || !utf8_valid(path)) {
withheld_semantics = true;
return;
}
const unsigned uid = DECL_UID(decl);
for (unsigned i = 0; i != use_count; ++i) {
if (!uses[i].where.same(where)) {
continue;
}
if (uses[i].uid != uid || std::strcmp(uses[i].type, type_text) != 0 ||
std::strcmp(uses[i].canonical, canonical_text) != 0) {
uses[i].conflict = true;
withheld_conflict = true;
}
return;
}
if (use_count == max_occurrences) {
at_capacity = true;
return;
}
use_entry &entry = uses[use_count++];
entry.uid = uid;
entry.where = where;
std::strcpy(entry.path, path);
std::memcpy(entry.name, IDENTIFIER_POINTER(DECL_NAME(decl)),
IDENTIFIER_LENGTH(DECL_NAME(decl)));
std::strcpy(entry.type, type_text);
std::strcpy(entry.canonical, canonical_text);
const char *signature = decl_as_string(decl, TFF_SCOPE | TFF_RETURN_TYPE);
if (signature && std::strlen(signature) <= max_signature && utf8_valid(signature)) {
std::strcpy(entry.signature, signature);
}
}
tree scan(tree *slot, int *walk_subtrees, void *) {
tree node = *slot;
if (!node) {
return NULL_TREE;
}
if (over_walk || ++visited > max_visited) {
over_walk = true;
*walk_subtrees = 0;
return NULL_TREE;
}
if (TYPE_P(node) || DECL_P(node)) {
*walk_subtrees = 0;
return NULL_TREE;
}
if (TREE_CODE(node) != CALL_EXPR) {
return NULL_TREE;
}
tree decl = cp_get_callee_fndecl_nofold(node);
if (decl && plain_name(decl)) {
record_use(node, decl);
} else if (decl) {
withheld_semantics = true;
}
return NULL_TREE;
}
void started(void *data, void *) {
auto *decl = static_cast<tree>(data);
if (!decl || TREE_CODE(decl) != FUNCTION_DECL || !plain_name(decl)) {
return;
}
if (DECL_LANG_SPECIFIC(decl) && DECL_USE_TEMPLATE(decl)) {
return;
}
record_body(decl);
}
void pre_genericize(void *data, void *) {
auto *decl = static_cast<tree>(data);
if (!decl || TREE_CODE(decl) != FUNCTION_DECL || !plain_name(decl) || !DECL_SAVED_TREE(decl)) {
return;
}
if (DECL_LANG_SPECIFIC(decl) && DECL_USE_TEMPLATE(decl)) {
return;
}
if (body_entry *body = find_body(DECL_UID(decl))) {
body->definition = true;
}
const location_t location = DECL_SOURCE_LOCATION(decl);
if (RESERVED_LOCATION_P(location)) {
return;
}
const expanded_location expanded = expand_location(location);
if (!admitted(expanded.file)) {
return;
}
cp_walk_tree_without_duplicates(&DECL_SAVED_TREE(decl), scan, nullptr);
}
void finish(void *, void *) {
const char *output = std::getenv("VLS_OBSERVER_OUTPUT");
if (!output || !*output) {
output = "/vls-observer/report";
}
const char *reason = "";
bool complete = true;
if (line_table->seen_line_directive) {
reason = "lineDirective";
complete = false;
} else if (seen_error()) {
reason = "compileErrors";
complete = false;
} else if (at_capacity || over_walk) {
reason = "capacity";
complete = false;
}
const int fd = ::open(output, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (fd < 0) {
return;
}
std::FILE *out = ::fdopen(fd, "w");
if (!out) {
::close(fd);
return;
}
std::fputs("{\"schema\":1,\"nonce\":", out);
json_string(out, nonce);
std::fprintf(out, ",\"complete\":%s,\"partial\":%s,\"reason\":", complete ? "true" : "false",
(withheld_origin || withheld_semantics || withheld_conflict) ? "true" : "false");
json_string(out, reason);
std::fputs(",\"occurrences\":[", out);
bool first = true;
if (complete) {
for (unsigned i = 0; i != use_count; ++i) {
const use_entry &use = uses[i];
if (use.conflict) {
continue;
}
const body_entry *body = find_body(use.uid);
const bool known = body && !body->conflict;
if (!first) {
std::fputc(',', out);
}
first = false;
std::fputs("{\"name\":", out);
json_string(out, use.name);
std::fputs(",\"type\":", out);
json_string(out, use.type);
std::fputs(",\"canonicalType\":", out);
json_string(out, use.canonical);
if (use.signature[0]) {
std::fputs(",\"signature\":", out);
json_string(out, use.signature);
}
std::fputs(",\"use\":{\"path\":", out);
json_string(out, use.path);
std::fprintf(out, ",\"line\":%u,\"startByte\":%u,\"endByte\":%u},\"definition\":",
use.where.line, use.where.start, use.where.end);
if (known) {
std::fputs("{\"path\":", out);
json_string(out, body->path);
std::fprintf(out, ",\"line\":%u,\"startByte\":%u,\"endByte\":%u}", body->where.line,
body->where.start, body->where.end);
} else {
std::fputs("null", out);
}
std::fputc('}', out);
}
}
std::fputs("]}\n", out);
if (std::fflush(out) != 0 || std::ferror(out) || ::fsync(fd) != 0) {
std::fclose(out);
return;
}
std::fclose(out);
}
} // namespace
int plugin_init(struct plugin_name_args *info, struct plugin_gcc_version *version) {
if (!plugin_default_version_check(version, &gcc_version)) {
return 1;
}
if (!parse_manifest()) {
return 1;
}
register_callback(info->base_name, PLUGIN_START_PARSE_FUNCTION, started, nullptr);
register_callback(info->base_name, PLUGIN_PRE_GENERICIZE, pre_genericize, nullptr);
register_callback(info->base_name, PLUGIN_FINISH, finish, nullptr);
return 0;
}
+275
View File
@@ -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(&section, 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
+13
View File
@@ -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
+67
View File
@@ -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
+112
View File
@@ -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