Files
Build-System/src/Toolchain/Driver.cpp
T
faumaray 9da1387031
VoidBuildSystem CI / 1 · Requirements (push) Successful in 9s
VoidBuildSystem CI / 2A · Linux build (debug) (push) Successful in 2m45s
VoidBuildSystem CI / 2B · Windows Wine build (debug) (push) Successful in 2m34s
VoidBuildSystem CI / 2A · Linux build (sanitizers) (push) Successful in 4m34s
VoidBuildSystem CI / 2B · Windows Wine build (relwithdebinfo) (push) Successful in 4m50s
VoidBuildSystem CI / 3B · Windows Wine test (relwithdebinfo) (push) Successful in 22s
VoidBuildSystem CI / 3B · Windows Wine test (debug) (push) Successful in 24s
VoidBuildSystem CI / 2A · Linux build (relwithdebinfo) (push) Successful in 5m41s
VoidBuildSystem CI / 3A · Linux test (sanitizers) (push) Successful in 1m36s
VoidBuildSystem CI / 3A · Linux test (relwithdebinfo) (push) Successful in 6m2s
VoidBuildSystem CI / 3A · Linux test (debug) (push) Successful in 6m8s
VoidBuildSystem CI / 4A2 · VBS installers (windows target) (push) Successful in 3m12s
VoidBuildSystem CI / 4A2 · VBS installers (linux target) (push) Successful in 3m17s
VoidBuildSystem CI / 5 · Release (push) Skipped
feat(perf,cli): shared per-user caches, generated completions and man pages
Cold builds in a fresh build directory now reuse content-addressed artifacts
from $XDG_CACHE_HOME/vbs (or ~/.cache/vbs): the compiled build descriptor and
the toolchain capability probes. Keys already cover the compiler identity, the
SDK, the generated driver source and every configuration source, and the
descriptor's discovered headers are re-verified on every run, so sharing cannot
change a result; VBS_SHARED_CACHE=0 keeps a build directory self-contained.

Measured on a 20-source fixture (Debug vbs): cold 3897 ms -> 755 ms in a fresh
build directory, warm 153 ms (config 1986 -> 128 ms, toolchain 562 -> 6.5 ms).

`vbs completions --shell bash|zsh|fish` and `vbs man [--output DIR]` generate
shell completion scripts and roff man pages from the live parser tree by
running `vbs <path> --help`, so they cannot drift from the CLI (86 man pages).

Verified: new FullV1Tests cases for the shared cache and for completions/man
(including `bash -n` on the generated script) pass, and the CLI contract suite
passes.
2026-12-06 16:58:04 +03:00

972 lines
40 KiB
C++

#include <Void/Build/Toolchain/Driver.hpp>
#include <Void/Build/Platform/FileOps.hpp>
#include <Void/Build/Platform/ProcessSupervisor.hpp>
#include <Void/Build/Util/Json.hpp>
#include <Void/Build/Util/Sha256.hpp>
#include <Void/Build/Util/UserCache.hpp>
#include <Void/Configuration/Env.hpp>
#include <Void/Data/StrictJson.hpp>
#include <Void/Log/Log.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/System/Types.hpp>
#include <Void/Text/Str.hpp>
#include <algorithm>
#include <cstdlib>
#include <format>
#if !defined(_WIN32)
#include <sys/utsname.h>
#endif
namespace Void::Build::Toolchain {
namespace {
Void::Result::Error make_error(std::string message) {
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
std::move(message));
}
std::string trim(std::string_view text) { return std::string{Void::Str::trim_ascii(text)}; }
std::map<std::string, std::string, std::less<>> capture_relevant_env() {
static constexpr const char *kKeys[] = {"CPATH",
"C_INCLUDE_PATH",
"CPLUS_INCLUDE_PATH",
"LIBRARY_PATH",
"COMPILER_PATH",
"GCC_EXEC_PREFIX",
"NIX_CFLAGS_COMPILE",
"NIX_LDFLAGS",
"NIX_CXXSTDLIB_COMPILE",
"NIX_CXXSTDLIB_LINK"};
std::map<std::string, std::string, std::less<>> env;
for (const char *key : kKeys) {
if (auto val = Void::Configuration::get_env(key); val) {
env[key] = std::move(*val);
}
}
return env;
}
bool probe_compile_flag(const std::filesystem::path &compiler, const std::string &sysroot,
const std::vector<std::string> &extra_flags, std::string_view source_code,
std::string_view language = "c++") {
Platform::ProcessRequest req;
req.executable = compiler;
req.arguments = {"-x", std::string{language}, "-fsyntax-only"};
if (!sysroot.empty()) {
req.arguments.push_back("--sysroot=" + sysroot);
}
req.arguments.insert(req.arguments.end(), extra_flags.begin(), extra_flags.end());
req.arguments.push_back("-");
req.stdin_data = std::string{source_code};
req.timeout = std::chrono::seconds{15};
auto res = Platform::run_supervised(req);
return res.has_value() && res->succeeded();
}
std::size_t estimate_argv_bytes(const std::vector<std::string> &args) {
std::size_t total = 0;
for (const auto &arg : args) {
total += arg.size() + 1;
}
return total;
}
std::string c_standard_flag(CStandard standard) {
switch (standard) {
case CStandard::Default:
return {};
case CStandard::C11:
return "-std=c11";
case CStandard::C17:
return "-std=c17";
case CStandard::C23:
return "-std=c23";
}
return {};
}
std::string cxx_standard_flag(CxxStandard standard) {
switch (standard) {
case CxxStandard::Default:
return {};
case CxxStandard::Cxx17:
return "-std=c++17";
case CxxStandard::Cxx20:
return "-std=c++20";
case CxxStandard::Cxx23:
return "-std=c++23";
case CxxStandard::Cxx26:
return "-std=c++26";
}
return {};
}
std::string sanitizer_flag_value(Sanitizer s) {
switch (s) {
case Sanitizer::Address:
return "address";
case Sanitizer::Undefined:
return "undefined";
case Sanitizer::Thread:
return "thread";
case Sanitizer::Memory:
return "memory";
case Sanitizer::Leak:
return "leak";
}
return {};
}
std::string serialize_capabilities(const ToolchainCapabilities &cap) {
using Util::json_array;
using Util::json_quote;
std::string out = "{";
out += "\"family\":" + json_quote(compiler_name(cap.family));
out += ",\"cxx_compiler\":" + json_quote(cap.cxx_compiler.string());
out += ",\"c_compiler\":" + json_quote(cap.c_compiler.string());
out += ",\"archiver\":" + json_quote(cap.archiver.string());
out += ",\"module_scanner\":" +
json_quote(cap.module_scanner ? cap.module_scanner->string() : std::string{});
out += ",\"version_banner\":" + json_quote(cap.version_banner);
out += ",\"target_triple\":" + json_quote(cap.target_triple);
out += ",\"sysroot\":" + json_quote(cap.sysroot);
out += ",\"compiler_sha256\":" + json_quote(cap.compiler_sha256);
out += ",\"c_compiler_sha256\":" + json_quote(cap.c_compiler_sha256);
out += ",\"archiver_sha256\":" + json_quote(cap.archiver_sha256);
out += ",\"default_include_dirs\":" + json_array(cap.default_include_dirs, json_quote);
out += ",\"supports_c11\":" + std::string{cap.supports_c11 ? "true" : "false"};
out += ",\"supports_c17\":" + std::string{cap.supports_c17 ? "true" : "false"};
out += ",\"supports_c23\":" + std::string{cap.supports_c23 ? "true" : "false"};
out += ",\"supports_cxx17\":" + std::string{cap.supports_cxx17 ? "true" : "false"};
out += ",\"supports_cxx20\":" + std::string{cap.supports_cxx20 ? "true" : "false"};
out += ",\"supports_cxx23\":" + std::string{cap.supports_cxx23 ? "true" : "false"};
out += ",\"supports_cxx26\":" + std::string{cap.supports_cxx26 ? "true" : "false"};
out += ",\"supports_reflection\":" + std::string{cap.supports_reflection ? "true" : "false"};
out += ",\"supports_file_prefix_map\":" +
std::string{cap.supports_file_prefix_map ? "true" : "false"};
out += ",\"supports_macro_prefix_map\":" +
std::string{cap.supports_macro_prefix_map ? "true" : "false"};
out += ",\"supports_debug_prefix_map\":" +
std::string{cap.supports_debug_prefix_map ? "true" : "false"};
out += ",\"supports_p1689_scan\":" + std::string{cap.supports_p1689_scan ? "true" : "false"};
out += ",\"supports_pch\":" + std::string{cap.supports_pch ? "true" : "false"};
out += ",\"supports_lto_full\":" + std::string{cap.supports_lto_full ? "true" : "false"};
out += ",\"supports_lto_thin\":" + std::string{cap.supports_lto_thin ? "true" : "false"};
out += ",\"supports_asan\":" + std::string{cap.supports_asan ? "true" : "false"};
out += ",\"supports_ubsan\":" + std::string{cap.supports_ubsan ? "true" : "false"};
out += ",\"supports_tsan\":" + std::string{cap.supports_tsan ? "true" : "false"};
out += ",\"is_cross_toolchain\":" + std::string{cap.is_cross_toolchain ? "true" : "false"};
out += ",\"identity_hash\":" + json_quote(cap.identity_hash);
out += "}";
return out;
}
std::optional<ToolchainCapabilities> deserialize_capabilities(std::string_view text) {
const auto parsed = Void::Json::Strict::parse(text);
if (!parsed) {
return std::nullopt;
}
const auto *obj = std::get_if<Void::Json::Strict::Value::Object>(&parsed->value);
if (!obj) {
return std::nullopt;
}
auto get_str = [&](const std::string &k) -> std::optional<std::string> {
const auto it = obj->find(k);
if (it == obj->end()) {
return std::nullopt;
}
const auto *s = std::get_if<std::string>(&it->second.value);
return s ? std::optional<std::string>{*s} : std::nullopt;
};
auto get_bool = [&](const std::string &k) -> std::optional<bool> {
const auto it = obj->find(k);
if (it == obj->end()) {
return std::nullopt;
}
const auto *b = std::get_if<bool>(&it->second.value);
return b ? std::optional<bool>{*b} : std::nullopt;
};
try {
ToolchainCapabilities cap;
cap.family = parse_compiler(get_str("family").value_or(""));
cap.cxx_compiler = get_str("cxx_compiler").value_or("");
cap.c_compiler = get_str("c_compiler").value_or("");
cap.archiver = get_str("archiver").value_or("");
if (auto scanner = get_str("module_scanner"); scanner && !scanner->empty()) {
cap.module_scanner = *scanner;
}
cap.version_banner = get_str("version_banner").value_or("");
cap.target_triple = get_str("target_triple").value_or("");
cap.sysroot = get_str("sysroot").value_or("");
cap.compiler_sha256 = get_str("compiler_sha256").value_or("");
cap.c_compiler_sha256 = get_str("c_compiler_sha256").value_or("");
cap.archiver_sha256 = get_str("archiver_sha256").value_or("");
if (const auto dit = obj->find("default_include_dirs"); dit != obj->end()) {
if (const auto *darr =
std::get_if<Void::Json::Strict::Value::Array>(&dit->second.value)) {
for (const auto &item : *darr) {
if (const auto *ds = std::get_if<std::string>(&item.value);
ds && !ds->empty()) {
cap.default_include_dirs.push_back(*ds);
}
}
}
}
cap.supports_c11 = get_bool("supports_c11").value_or(false);
cap.supports_c17 = get_bool("supports_c17").value_or(false);
cap.supports_c23 = get_bool("supports_c23").value_or(false);
cap.supports_cxx17 = get_bool("supports_cxx17").value_or(false);
cap.supports_cxx20 = get_bool("supports_cxx20").value_or(false);
cap.supports_cxx23 = get_bool("supports_cxx23").value_or(false);
cap.supports_cxx26 = get_bool("supports_cxx26").value_or(false);
cap.supports_reflection = get_bool("supports_reflection").value_or(false);
cap.supports_file_prefix_map = get_bool("supports_file_prefix_map").value_or(false);
cap.supports_macro_prefix_map = get_bool("supports_macro_prefix_map").value_or(false);
cap.supports_debug_prefix_map = get_bool("supports_debug_prefix_map").value_or(false);
cap.supports_p1689_scan = get_bool("supports_p1689_scan").value_or(false);
cap.supports_pch = get_bool("supports_pch").value_or(true);
cap.supports_lto_full = get_bool("supports_lto_full").value_or(false);
cap.supports_lto_thin = get_bool("supports_lto_thin").value_or(false);
cap.supports_asan = get_bool("supports_asan").value_or(false);
cap.supports_ubsan = get_bool("supports_ubsan").value_or(false);
cap.supports_tsan = get_bool("supports_tsan").value_or(false);
cap.is_cross_toolchain = get_bool("is_cross_toolchain").value_or(false);
cap.identity_hash = get_str("identity_hash").value_or("");
if (cap.identity_hash.empty() || cap.cxx_compiler.empty()) {
return std::nullopt;
}
return cap;
} catch (...) {
return std::nullopt;
}
}
// Shader compilers come from PATH and are intentionally not part of the toolchain identity:
// each shader action's key includes its exact command line.
void attach_shader_tools(ToolchainCapabilities &cap) {
const auto resolve = [](const char *name) { return Platform::resolve_executable(name); };
if (auto glslang = resolve("glslangValidator"); glslang) {
cap.glslang_validator = *glslang;
}
if (auto slangc = resolve("slangc"); slangc) {
cap.slangc = *slangc;
}
if (auto dxc = resolve("dxc"); dxc) {
cap.dxc = *dxc;
}
}
} // namespace
std::string host_os_name() {
#if defined(_WIN32)
return "Windows";
#elif defined(__APPLE__)
return "macOS";
#else
struct utsname u{};
if (::uname(&u) == 0) {
return std::string{u.sysname};
}
return "Linux";
#endif
}
std::string host_architecture_name() {
#if defined(__aarch64__) || defined(_M_ARM64)
return "aarch64";
#elif defined(_WIN32)
return "x86_64";
#else
struct utsname u{};
if (::uname(&u) == 0) {
return std::string{u.machine};
}
return "x86_64";
#endif
}
namespace {
// Cross toolchain prefix for a non-host target (Track C: Windows via MinGW-w64 under Wine).
std::string cross_compiler_prefix(const ProfileContext &context) {
const std::string target_os = Void::Str::to_lower_ascii(context.os);
if (target_os != "windows" || Void::Str::to_lower_ascii(host_os_name()) == "windows") {
return {};
}
if (context.architecture == "aarch64" || context.architecture == "arm64") {
return "aarch64-w64-mingw32-";
}
return "x86_64-w64-mingw32-";
}
} // namespace
Void::Result::Result<ToolchainCapabilities, Void::Result::Error>
discover_and_probe(const ProfileContext &context,
const std::optional<std::filesystem::path> &cache_dir) {
const std::string cross_prefix = cross_compiler_prefix(context);
std::filesystem::path requested_compiler;
if (!context.compiler_path.empty()) {
requested_compiler = context.compiler_path;
} else if (!cross_prefix.empty()) {
requested_compiler =
cross_prefix + (context.compiler == CompilerFamily::Gcc ? "g++" : "clang++");
} else if (context.compiler == CompilerFamily::Gcc) {
requested_compiler = "g++";
} else {
requested_compiler = "clang++";
}
auto resolved_compiler = Platform::resolve_executable(requested_compiler);
if (!resolved_compiler) {
return std::unexpected{
make_error(std::format("toolchain compiler '{}' for family '{}' was not found in PATH",
requested_compiler.string(), compiler_name(context.compiler)))};
}
std::filesystem::path requested_c_compiler =
!cross_prefix.empty()
? std::filesystem::path{cross_prefix +
(context.compiler == CompilerFamily::Gcc ? "gcc" : "clang")}
: (context.compiler == CompilerFamily::Gcc ? std::filesystem::path{"gcc"}
: std::filesystem::path{"clang"});
if (!context.compiler_path.empty()) {
const std::filesystem::path cp_path{context.compiler_path};
const std::string fname = cp_path.filename().string();
if (fname == "g++" || fname.ends_with("-g++")) {
const std::string c_name = fname.substr(0, fname.size() - 3) + "gcc";
requested_c_compiler = cp_path.parent_path().empty() ? std::filesystem::path{c_name}
: (cp_path.parent_path() / c_name);
} else if (fname == "clang++" || fname.ends_with("-clang++")) {
const std::string c_name = fname.substr(0, fname.size() - 7) + "clang";
requested_c_compiler = cp_path.parent_path().empty() ? std::filesystem::path{c_name}
: (cp_path.parent_path() / c_name);
}
}
auto resolved_c_compiler = Platform::resolve_executable(requested_c_compiler);
if (!resolved_c_compiler && !context.compiler_path.empty()) {
resolved_c_compiler =
Platform::resolve_executable(context.compiler == CompilerFamily::Gcc ? "gcc" : "clang");
}
std::string c_comp_hash;
if (resolved_c_compiler) {
if (auto ch = Util::sha256_file_hex(*resolved_c_compiler); ch) {
c_comp_hash = *ch;
}
}
std::optional<std::filesystem::path> resolved_ar;
if (!cross_prefix.empty()) {
resolved_ar = Platform::resolve_executable(cross_prefix + "ar");
}
if (!resolved_ar && context.compiler == CompilerFamily::Clang) {
resolved_ar = Platform::resolve_executable("llvm-ar");
}
if (!resolved_ar) {
resolved_ar = Platform::resolve_executable("ar");
}
if (!resolved_ar) {
return std::unexpected{make_error("archiver ('ar' or 'llvm-ar') was not found in PATH")};
}
if (!context.sysroot.empty() && !std::filesystem::is_directory(context.sysroot)) {
return std::unexpected{
make_error(std::format("configured sysroot '{}' does not exist", context.sysroot))};
}
auto comp_hash = Util::sha256_file_hex(*resolved_compiler);
if (!comp_hash) {
return std::unexpected{comp_hash.error()};
}
auto ar_hash = Util::sha256_file_hex(*resolved_ar);
if (!ar_hash) {
return std::unexpected{ar_hash.error()};
}
const auto relevant_env = capture_relevant_env();
// Compute cache key BEFORE expensive compiler probes.
Util::Sha256Hasher key_hasher;
key_hasher.update_length_prefixed("vbs-probe-v2");
key_hasher.update_length_prefixed(compiler_name(context.compiler));
key_hasher.update_length_prefixed(resolved_compiler->string());
key_hasher.update_length_prefixed(*comp_hash);
if (resolved_c_compiler) {
key_hasher.update_length_prefixed(resolved_c_compiler->string());
key_hasher.update_length_prefixed(c_comp_hash);
}
key_hasher.update_length_prefixed(resolved_ar->string());
key_hasher.update_length_prefixed(*ar_hash);
key_hasher.update_length_prefixed(context.sysroot);
key_hasher.update_length_prefixed(context.os);
key_hasher.update_length_prefixed(context.architecture);
for (const auto &[k, v] : relevant_env) {
key_hasher.update_length_prefixed(k);
key_hasher.update_length_prefixed(v);
}
const std::string probe_cache_key = key_hasher.finalize_hex();
// Probe results are content-addressed by compiler identity, sysroot, target and the relevant
// environment, so a shared per-user cache can serve fresh build directories (CI jobs, new
// clones) without re-running ~20 compiler probes.
const auto shared_probe_dir = Util::user_cache_dir("probes");
const auto load_cached = [&](const std::filesystem::path &file)
-> std::optional<ToolchainCapabilities> {
auto cached_text = Void::FileSystem::read_file(file);
if (!cached_text) {
return std::nullopt;
}
auto cached = deserialize_capabilities(*cached_text);
if (!cached) {
return std::nullopt;
}
cached->relevant_env = relevant_env;
attach_shader_tools(*cached);
return *cached;
};
if (cache_dir) {
if (auto cached = load_cached(*cache_dir / (probe_cache_key + ".json"))) {
return *cached;
}
}
if (shared_probe_dir) {
if (auto cached = load_cached(*shared_probe_dir / (probe_cache_key + ".json"))) {
if (cache_dir) {
// Seed the build-local cache so later runs never touch the shared one.
(void)Platform::atomic_write_file(*cache_dir / (probe_cache_key + ".json"),
serialize_capabilities(*cached), false);
}
Void::Log::debug("Toolchain", "probe capabilities reused from the shared cache");
return *cached;
}
}
ToolchainCapabilities cap;
cap.family = context.compiler;
cap.cxx_compiler = *resolved_compiler;
cap.c_compiler = resolved_c_compiler.value_or(std::filesystem::path{});
cap.archiver = *resolved_ar;
cap.sysroot = context.sysroot;
cap.compiler_sha256 = *comp_hash;
cap.c_compiler_sha256 = c_comp_hash;
cap.archiver_sha256 = *ar_hash;
cap.relevant_env = relevant_env;
// Query version banner and target triple (never executes target code).
{
Platform::ProcessRequest req;
req.executable = cap.cxx_compiler;
req.arguments = {"--version"};
req.timeout = std::chrono::seconds{10};
auto res = Platform::run_supervised(req);
if (!res || !res->succeeded()) {
return std::unexpected{make_error(
std::format("failed querying version of '{}'", cap.cxx_compiler.string()))};
}
const auto nl = res->stdout_data.find('\n');
cap.version_banner =
trim(nl == std::string::npos ? std::string_view{res->stdout_data}
: std::string_view{res->stdout_data}.substr(0, nl));
}
{
Platform::ProcessRequest req;
req.executable = cap.cxx_compiler;
req.arguments = {"-dumpmachine"};
req.timeout = std::chrono::seconds{10};
auto res = Platform::run_supervised(req);
if (res && res->succeeded()) {
cap.target_triple = trim(res->stdout_data);
}
}
cap.is_cross_toolchain =
(!context.architecture.empty() && context.architecture != host_architecture_name()) ||
(!context.os.empty() && context.os != host_os_name());
if (cap.family == CompilerFamily::Clang) {
cap.module_scanner = Platform::resolve_executable("clang-scan-deps");
cap.supports_p1689_scan = cap.module_scanner.has_value();
}
// Record the compiler's implicit include search list (GCC and Clang both
// print it for `-E -v`): explicitly passing those directories, e.g. as
// `-isystem /usr/include`, makes GCC drop its implicit entry and breaks the
// `#include_next` chain in libstdc++.
{
Platform::ProcessRequest ireq;
ireq.executable = cap.cxx_compiler;
ireq.arguments = {"-x", "c++", "-E", "-v"};
if (!cap.sysroot.empty()) {
ireq.arguments.push_back("--sysroot=" + cap.sysroot);
}
ireq.arguments.push_back("-");
ireq.timeout = std::chrono::seconds{10};
if (auto ires = Platform::run_supervised(ireq); ires) {
const std::string combined = ires->stderr_data + "\n" + ires->stdout_data;
bool in_search = false;
std::size_t pos = 0;
while (pos < combined.size()) {
const auto nl = combined.find('\n', pos);
const std::string line = trim(std::string_view{combined}.substr(
pos, nl == std::string::npos ? std::string::npos : nl - pos));
pos = (nl == std::string::npos) ? combined.size() : (nl + 1);
if (line.find("#include <...> search starts here:") != std::string::npos) {
in_search = true;
continue;
}
if (in_search) {
if (line.starts_with("End of search list")) {
break;
}
if (!line.empty() && line.find("(framework directory)") == std::string::npos) {
cap.default_include_dirs.push_back(line);
}
}
}
}
}
// Syntax-only capability probes (safe for cross-toolchains).
constexpr std::string_view kTrivialC = "int vbs_c_probe(void) { return 0; }\n";
if (!cap.c_compiler.empty()) {
cap.supports_c11 =
probe_compile_flag(cap.c_compiler, cap.sysroot, {"-std=c11"}, kTrivialC, "c");
cap.supports_c17 =
probe_compile_flag(cap.c_compiler, cap.sysroot, {"-std=c17"}, kTrivialC, "c");
cap.supports_c23 =
probe_compile_flag(cap.c_compiler, cap.sysroot, {"-std=c23"}, kTrivialC, "c");
}
constexpr std::string_view kTrivialCpp = "int vbs_probe() { return 0; }\n";
cap.supports_cxx17 =
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-std=c++17"}, kTrivialCpp);
cap.supports_cxx20 =
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-std=c++20"}, kTrivialCpp);
cap.supports_cxx23 =
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-std=c++23"}, kTrivialCpp);
cap.supports_cxx26 =
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-std=c++26"}, kTrivialCpp);
cap.supports_reflection =
cap.supports_cxx26 &&
probe_compile_flag(
cap.cxx_compiler, cap.sysroot, {"-std=c++26", "-freflection"},
"#include <meta>\nconsteval bool ok(){return true;}\nstatic_assert(ok());\n");
cap.supports_file_prefix_map =
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-ffile-prefix-map=/a=/b"}, kTrivialCpp);
cap.supports_macro_prefix_map = probe_compile_flag(cap.cxx_compiler, cap.sysroot,
{"-fmacro-prefix-map=/a=/b"}, kTrivialCpp);
cap.supports_debug_prefix_map = probe_compile_flag(cap.cxx_compiler, cap.sysroot,
{"-fdebug-prefix-map=/a=/b"}, kTrivialCpp);
if (cap.family == CompilerFamily::Gcc) {
cap.supports_p1689_scan = probe_compile_flag(
cap.cxx_compiler, cap.sysroot,
{"-std=c++20", "-fmodules", "-E", "-M", "-fdeps-format=p1689r5",
"-fdeps-file=/dev/null", "-fdeps-target=probe.o", "-o", "/dev/null"},
kTrivialCpp);
}
cap.supports_lto_full =
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-flto"}, kTrivialCpp);
cap.supports_lto_thin =
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-flto=thin"}, kTrivialCpp);
cap.supports_asan =
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-fsanitize=address"}, kTrivialCpp);
cap.supports_ubsan =
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-fsanitize=undefined"}, kTrivialCpp);
cap.supports_tsan =
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-fsanitize=thread"}, kTrivialCpp);
Util::Sha256Hasher id_hasher;
id_hasher.update_length_prefixed(probe_cache_key);
id_hasher.update_length_prefixed(cap.version_banner);
id_hasher.update_length_prefixed(cap.target_triple);
cap.identity_hash = id_hasher.finalize_hex();
if (cache_dir) {
const auto cache_file = *cache_dir / (probe_cache_key + ".json");
(void)Platform::atomic_write_file(cache_file, serialize_capabilities(cap), false);
}
if (shared_probe_dir) {
(void)Platform::atomic_write_file(*shared_probe_dir / (probe_cache_key + ".json"),
serialize_capabilities(cap), false);
}
attach_shader_tools(cap);
return cap;
}
std::string compute_profile_identity(const ProfileContext &context,
const ToolchainCapabilities &toolchain) {
Util::Sha256Hasher hasher;
hasher.update_length_prefixed("vbs-profile-v1");
hasher.update_length_prefixed(context.name);
hasher.update_length_prefixed(compiler_name(context.compiler));
hasher.update_length_prefixed(context.os);
hasher.update_length_prefixed(context.architecture);
hasher.update_length_prefixed(toolchain.identity_hash);
hasher.update_length_prefixed(c_standard_name(context.c_standard));
hasher.update_length_prefixed(cxx_standard_name(context.cxx_standard));
hasher.update_length_prefixed(lto_mode_name(context.lto));
hasher.update_length_prefixed(context.sysroot);
hasher.update_u64(static_cast<std::uint64_t>(context.reproducibility_epoch));
hasher.update_u64(context.nondeterministic ? 1u : 0u);
hasher.update_u64(context.compile_options.size());
for (const auto &opt : context.compile_options) {
hasher.update_length_prefixed(opt);
}
hasher.update_u64(context.link_options.size());
for (const auto &opt : context.link_options) {
hasher.update_length_prefixed(opt);
}
hasher.update_u64(context.defines.size());
for (const auto &def : context.defines) {
hasher.update_length_prefixed(def);
}
hasher.update_u64(context.sanitizers.size());
for (const auto s : context.sanitizers) {
hasher.update_length_prefixed(sanitizer_name(s));
}
return hasher.finalize_hex();
}
std::string escape_response_file_arg(std::string_view arg) {
bool needs_quote = arg.empty();
for (const char c : arg) {
if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '"' || c == '\\' || c == '\'') {
needs_quote = true;
break;
}
}
if (!needs_quote) {
return std::string{arg};
}
std::string out{"\""};
for (const char c : arg) {
if (c == '"' || c == '\\') {
out.push_back('\\');
}
out.push_back(c);
}
out.push_back('"');
return out;
}
Void::Result::Result<LoweredCommand, Void::Result::Error>
lower_compile_command(const ToolchainCapabilities &toolchain, const CompileRequest &request) {
if (request.source_file.empty() || request.output_object.empty()) {
return std::unexpected{make_error("compile request requires source and output paths")};
}
// Validate requested capabilities explicitly (never silently downgrade).
if (request.is_c_source) {
if (toolchain.c_compiler.empty()) {
return std::unexpected{make_error("target C compiler was not discovered")};
}
if (request.c_standard == CStandard::C11 && !toolchain.supports_c11) {
return std::unexpected{make_error("target C compiler does not support -std=c11")};
}
if (request.c_standard == CStandard::C17 && !toolchain.supports_c17) {
return std::unexpected{make_error("target C compiler does not support -std=c17")};
}
if (request.c_standard == CStandard::C23 && !toolchain.supports_c23) {
return std::unexpected{make_error("target C compiler does not support -std=c23")};
}
} else {
if (request.cxx_standard == CxxStandard::Cxx17 && !toolchain.supports_cxx17) {
return std::unexpected{make_error("target compiler does not support -std=c++17")};
}
if (request.cxx_standard == CxxStandard::Cxx20 && !toolchain.supports_cxx20) {
return std::unexpected{make_error("target compiler does not support -std=c++20")};
}
if (request.cxx_standard == CxxStandard::Cxx23 && !toolchain.supports_cxx23) {
return std::unexpected{make_error("target compiler does not support -std=c++23")};
}
if (request.cxx_standard == CxxStandard::Cxx26 && !toolchain.supports_cxx26) {
return std::unexpected{make_error("target compiler does not support -std=c++26")};
}
}
if (request.lto == LtoMode::Full && !toolchain.supports_lto_full) {
return std::unexpected{make_error("target compiler does not support full LTO (-flto)")};
}
if (request.lto == LtoMode::Thin && !toolchain.supports_lto_thin) {
return std::unexpected{
make_error("target compiler does not support thin LTO (-flto=thin)")};
}
for (const auto s : request.sanitizers) {
if (s == Sanitizer::Address && !toolchain.supports_asan) {
return std::unexpected{make_error("target compiler does not support AddressSanitizer")};
}
if (s == Sanitizer::Undefined && !toolchain.supports_ubsan) {
return std::unexpected{
make_error("target compiler does not support UndefinedBehaviorSanitizer")};
}
if (s == Sanitizer::Thread && !toolchain.supports_tsan) {
return std::unexpected{make_error("target compiler does not support ThreadSanitizer")};
}
}
if (!request.prefix_maps.empty() && !toolchain.supports_file_prefix_map &&
!(toolchain.supports_macro_prefix_map && toolchain.supports_debug_prefix_map)) {
return std::unexpected{make_error("target compiler lacks deterministic path-prefix-map "
"support required by snapshot mode")};
}
LoweredCommand cmd;
cmd.executable =
request.is_asm_source
? (toolchain.c_compiler.empty() ? toolchain.cxx_compiler : toolchain.c_compiler)
: (request.is_c_source ? toolchain.c_compiler : toolchain.cxx_compiler);
std::vector<std::string> args;
if (!toolchain.sysroot.empty()) {
args.push_back("--sysroot=" + toolchain.sysroot);
}
if (request.is_asm_source) {
// Assembly takes no language standard; `.S` is run through the C preprocessor by the
// driver based on its extension.
} else if (request.is_c_source) {
if (const auto std_flag = c_standard_flag(request.c_standard); !std_flag.empty()) {
args.push_back(std_flag);
}
} else {
if (const auto std_flag = cxx_standard_flag(request.cxx_standard); !std_flag.empty()) {
args.push_back(std_flag);
}
}
if (request.position_independent) {
args.push_back("-fPIC");
}
if (!request.is_asm_source && request.lto == LtoMode::Full) {
args.push_back("-flto");
} else if (!request.is_asm_source && request.lto == LtoMode::Thin) {
args.push_back("-flto=thin");
}
if (!request.is_asm_source && !request.sanitizers.empty()) {
std::string list;
for (std::size_t i = 0; i < request.sanitizers.size(); ++i) {
if (i > 0) {
list += ',';
}
list += sanitizer_flag_value(request.sanitizers[i]);
}
args.push_back("-fsanitize=" + list);
args.push_back("-fno-omit-frame-pointer");
}
if (request.is_module_interface || !request.module_bmi_imports.empty() ||
request.module_mapper_file) {
if (toolchain.family == CompilerFamily::Gcc) {
args.push_back("-fmodules");
if (request.module_mapper_file) {
args.push_back("-fmodule-mapper=" + request.module_mapper_file->string());
}
} else {
if (request.is_module_interface && request.bmi_output) {
args.push_back("--precompile");
}
for (const auto &[mod_name, bmi_path] : request.module_bmi_imports) {
if (mod_name.empty()) {
args.push_back("-fmodule-file=" + bmi_path.string());
} else {
args.push_back("-fmodule-file=" + mod_name + "=" + bmi_path.string());
}
}
}
}
if (request.precompiled_header) {
args.push_back("-include");
args.push_back(request.precompiled_header->string());
}
for (const auto &pm : request.prefix_maps) {
const std::string spec = pm.from.string() + "=" + pm.to.string();
if (toolchain.supports_file_prefix_map) {
args.push_back("-ffile-prefix-map=" + spec);
} else {
args.push_back("-fmacro-prefix-map=" + spec);
args.push_back("-fdebug-prefix-map=" + spec);
}
}
if (toolchain.family == CompilerFamily::Gcc && !request.nondeterministic) {
args.push_back("-frandom-seed=" + request.output_object.filename().string());
}
// Directories the compiler already searches implicitly are skipped: passing
// them explicitly (especially as -isystem) makes GCC drop its own entry and
// breaks #include_next in the standard library headers.
const auto is_implicit_include = [&](const std::filesystem::path &dir) {
const auto normalized = dir.lexically_normal();
for (const auto &implicit : toolchain.default_include_dirs) {
if (std::filesystem::path{implicit}.lexically_normal() == normalized) {
return true;
}
}
return false;
};
for (const auto &[inc, is_system] : request.include_dirs) {
if (is_implicit_include(inc)) {
continue;
}
args.push_back(is_system ? "-isystem" : "-I");
args.push_back(inc.string());
}
for (const auto &def : request.defines) {
args.push_back("-D" + def);
}
for (const auto &opt : request.compile_options) {
args.push_back(opt);
}
const bool clang_precompile = (toolchain.family == CompilerFamily::Clang &&
request.is_module_interface && request.bmi_output.has_value());
const std::string final_output =
clang_precompile ? request.bmi_output->string() : request.output_object.string();
if (request.depfile) {
args.push_back("-MMD");
args.push_back("-MF");
args.push_back(request.depfile->string());
args.push_back("-MT");
args.push_back(final_output);
}
if (request.compile_only && !clang_precompile) {
args.push_back("-c");
}
args.push_back(request.source_file.string());
args.push_back("-o");
args.push_back(final_output);
// Deterministic compiler metadata environment (Plan 05).
if (!request.nondeterministic) {
cmd.environment["SOURCE_DATE_EPOCH"] = std::to_string(request.reproducibility_epoch);
cmd.environment["TZ"] = "UTC";
cmd.environment["LC_ALL"] = "C";
}
if (request.response_file_dir && estimate_argv_bytes(args) > request.response_file_threshold) {
std::string rsp;
for (const auto &arg : args) {
rsp += escape_response_file_arg(arg);
rsp.push_back('\n');
}
const auto rsp_hash = Util::sha256_hex(rsp).substr(0, 16);
const auto rsp_path = *request.response_file_dir /
(request.output_object.filename().string() + "." + rsp_hash + ".rsp");
cmd.response_file = rsp_path;
cmd.response_file_content = std::move(rsp);
cmd.arguments = {"@" + rsp_path.string()};
} else {
cmd.arguments = std::move(args);
}
return cmd;
}
Void::Result::Result<LoweredCommand, Void::Result::Error>
lower_archive_command(const ToolchainCapabilities &toolchain,
const std::filesystem::path &output_archive,
const std::vector<std::filesystem::path> &object_files,
const std::optional<std::filesystem::path> &response_file_dir,
std::size_t response_file_threshold) {
if (output_archive.empty()) {
return std::unexpected{make_error("archive command requires output path")};
}
LoweredCommand cmd;
cmd.executable = toolchain.archiver;
std::vector<std::string> args;
args.push_back("rcsD");
args.push_back(output_archive.string());
for (const auto &obj : object_files) {
args.push_back(obj.string());
}
cmd.environment["TZ"] = "UTC";
cmd.environment["LC_ALL"] = "C";
if (response_file_dir && estimate_argv_bytes(args) > response_file_threshold) {
std::string rsp;
for (std::size_t i = 2; i < args.size(); ++i) {
rsp += escape_response_file_arg(args[i]);
rsp.push_back('\n');
}
const auto rsp_hash = Util::sha256_hex(rsp).substr(0, 16);
const auto rsp_path =
*response_file_dir / (output_archive.filename().string() + "." + rsp_hash + ".ar.rsp");
cmd.response_file = rsp_path;
cmd.response_file_content = std::move(rsp);
cmd.arguments = {"rcsD", output_archive.string(), "@" + rsp_path.string()};
} else {
cmd.arguments = std::move(args);
}
return cmd;
}
Void::Result::Result<LoweredCommand, Void::Result::Error>
lower_link_command(const ToolchainCapabilities &toolchain, const LinkRequest &request) {
if (request.output_file.empty()) {
return std::unexpected{make_error("link command requires output path")};
}
LoweredCommand cmd;
cmd.executable = toolchain.cxx_compiler;
cmd.environment["TZ"] = "UTC";
cmd.environment["LC_ALL"] = "C";
std::vector<std::string> args;
if (!toolchain.sysroot.empty()) {
args.push_back("--sysroot=" + toolchain.sysroot);
}
if (request.kind == TargetKind::SharedLibrary) {
args.push_back("-shared");
}
if (request.lto == LtoMode::Full) {
args.push_back("-flto");
} else if (request.lto == LtoMode::Thin) {
args.push_back("-flto=thin");
}
if (!request.sanitizers.empty()) {
std::string list;
for (std::size_t i = 0; i < request.sanitizers.size(); ++i) {
if (i > 0) {
list += ',';
}
list += sanitizer_flag_value(request.sanitizers[i]);
}
args.push_back("-fsanitize=" + list);
}
args.push_back("-o");
args.push_back(request.output_file.string());
for (const auto &obj : request.object_files) {
args.push_back(obj.string());
}
for (const auto &lib : request.static_libraries) {
args.push_back(lib.string());
}
for (const auto &lib : request.shared_libraries) {
args.push_back(lib.string());
}
for (const auto &rpath : request.rpaths) {
args.push_back("-Wl,-rpath," + rpath.string());
}
for (const auto &opt : request.link_options) {
args.push_back(opt);
}
if (request.response_file_dir && estimate_argv_bytes(args) > request.response_file_threshold) {
std::string rsp;
for (const auto &arg : args) {
rsp += escape_response_file_arg(arg);
rsp.push_back('\n');
}
const auto rsp_hash = Util::sha256_hex(rsp).substr(0, 16);
const auto rsp_path =
*request.response_file_dir /
(request.output_file.filename().string() + "." + rsp_hash + ".ld.rsp");
cmd.response_file = rsp_path;
cmd.response_file_content = std::move(rsp);
cmd.arguments = {"@" + rsp_path.string()};
} else {
cmd.arguments = std::move(args);
}
return cmd;
}
} // namespace Void::Build::Toolchain