#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Void::Build::Config { namespace { using JsonVal = Void::Json::Strict::Value; std::atomic g_req_seq{0}; Void::Result::Error make_error(std::string msg) { return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument, std::move(msg)); } bool is_cpp_file(const std::filesystem::path &p) { const auto ext = p.extension().string(); return ext == ".cpp" || ext == ".cc" || ext == ".cxx"; } // Cheap identity of a header file: content hashing is only needed when this changes. struct HeaderFingerprint { std::int64_t size{0}; std::int64_t mtime{0}; bool operator==(const HeaderFingerprint &) const = default; }; std::optional stat_fingerprint(const std::filesystem::path &path) { std::error_code ec; if (!std::filesystem::is_regular_file(path, ec)) { return std::nullopt; } const auto size = std::filesystem::file_size(path, ec); if (ec) { return std::nullopt; } const auto mtime = std::filesystem::last_write_time(path, ec); if (ec) { return std::nullopt; } return HeaderFingerprint{static_cast(size), static_cast(mtime.time_since_epoch().count())}; } std::string generate_driver_source(bool has_profiles_file, bool has_build_file, bool has_workspace_file) { std::string code = R"cpp(#include #include #include #include #include #include #include #include #include )cpp"; if (!has_profiles_file) { code += R"cpp(void profiles(Void::Build::Profiles &descriptions) { descriptions = Void::Build::default_profiles(); } )cpp"; } if (!has_build_file) { code += R"cpp(void build(Void::Build::Project &) { throw std::runtime_error{"this descriptor declares no build() entry point"}; } )cpp"; } if (!has_workspace_file) { code += R"cpp(void workspace(Void::Build::Workspace &) { throw std::runtime_error{"this descriptor declares no workspace() entry point"}; } )cpp"; } code += R"cpp( namespace { std::string read_text(const std::string &path) { std::ifstream in(path, std::ios::binary); if (!in) { throw std::runtime_error{"cannot open context file: " + path}; } std::ostringstream ss; ss << in.rdbuf(); return ss.str(); } void write_text(const std::string &path, const std::string &content) { std::ofstream out(path, std::ios::binary | std::ios::trunc); if (!out) { throw std::runtime_error{"cannot write result file: " + path}; } out << content; out.flush(); if (!out) { throw std::runtime_error{"failed flushing result file: " + path}; } } std::vector split_lines(std::string_view text) { std::vector out; std::size_t pos = 0; while (pos < text.size()) { const auto nl = text.find('\n', pos); const auto line = text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos); if (!line.empty()) { out.emplace_back(line); } if (nl == std::string_view::npos) { break; } pos = nl + 1; } return out; } Void::Build::ProfileContext parse_kv_context(std::string_view text) { Void::Build::ProfileContext ctx; for (const auto &line : split_lines(text)) { const auto eq = line.find('='); if (eq == std::string::npos) { continue; } const auto key = line.substr(0, eq); const auto val = line.substr(eq + 1); if (key == "name") ctx.name = val; else if (key == "compiler") ctx.compiler = Void::Build::parse_compiler(val); else if (key == "os") ctx.os = val; else if (key == "architecture") ctx.architecture = val; else if (key == "c_standard") ctx.c_standard = Void::Build::parse_c_standard(val); else if (key == "cxx_standard") ctx.cxx_standard = Void::Build::parse_cxx_standard(val); else if (key == "lto") ctx.lto = Void::Build::parse_lto_mode(val); else if (key == "sysroot") ctx.sysroot = val; else if (key == "compiler_path") ctx.compiler_path = val; else if (key == "reproducibility_epoch") ctx.reproducibility_epoch = std::stoll(val); else if (key == "nondeterministic") ctx.nondeterministic = (val == "1" || val == "true"); else if (key == "compile_option") ctx.compile_options.push_back(val); else if (key == "link_option") ctx.link_options.push_back(val); else if (key == "define") ctx.defines.push_back(val); else if (key == "sanitizer") ctx.sanitizers.push_back(Void::Build::parse_sanitizer(val)); } return ctx; } } // namespace int main(int argc, char **argv) { try { std::string mode; std::string output_path; std::string request_id; std::string context_file; std::string context_hash; for (int i = 1; i < argc; ++i) { const std::string_view arg{argv[i]}; if (arg == "--mode" && i + 1 < argc) mode = argv[++i]; else if (arg == "--output" && i + 1 < argc) output_path = argv[++i]; else if (arg == "--request-id" && i + 1 < argc) request_id = argv[++i]; else if (arg == "--context-file" && i + 1 < argc) context_file = argv[++i]; else if (arg == "--context-hash" && i + 1 < argc) context_hash = argv[++i]; else { std::cerr << "vbs-config-driver: unknown argument: " << arg << '\n'; return 2; } } if (output_path.empty() || request_id.empty()) { std::cerr << "vbs-config-driver: --output and --request-id are required\n"; return 2; } if (mode == "profiles") { Void::Build::Profiles descriptions; profiles(descriptions); const std::string payload = "{\"protocol_version\":1,\"request_id\":" + Void::Build::Util::json_quote(request_id) + ",\"payload\":" + descriptions.to_json() + "}\n"; write_text(output_path, payload); return 0; } if (mode == "describe") { auto ctx = parse_kv_context(read_text(context_file)); Void::Build::Project project{ctx}; build(project); const std::string payload = "{\"protocol_version\":1,\"request_id\":" + Void::Build::Util::json_quote(request_id) + ",\"context_hash\":" + Void::Build::Util::json_quote(context_hash) + ",\"payload\":" + project.to_json() + "}\n"; write_text(output_path, payload); return 0; } if (mode == "workspace") { Void::Build::Workspace ws; workspace(ws); const std::string payload = "{\"protocol_version\":1,\"request_id\":" + Void::Build::Util::json_quote(request_id) + ",\"payload\":" + ws.to_json() + "}\n"; write_text(output_path, payload); return 0; } std::cerr << "vbs-config-driver: unknown mode '" << mode << "'\n"; return 2; } catch (const std::exception &err) { std::cerr << "vbs-config-driver: " << err.what() << '\n'; return 2; } } )cpp"; return code; } std::string serialize_kv_context(const ProfileContext &ctx) { std::string out; out += "name=" + ctx.name + "\n"; out += "compiler=" + std::string{compiler_name(ctx.compiler)} + "\n"; out += "os=" + ctx.os + "\n"; out += "architecture=" + ctx.architecture + "\n"; out += "c_standard=" + std::string{Void::Build::c_standard_name(ctx.c_standard)} + "\n"; out += "cxx_standard=" + std::string{cxx_standard_name(ctx.cxx_standard)} + "\n"; out += "lto=" + std::string{lto_mode_name(ctx.lto)} + "\n"; out += "sysroot=" + ctx.sysroot + "\n"; out += "compiler_path=" + ctx.compiler_path + "\n"; out += "reproducibility_epoch=" + std::to_string(ctx.reproducibility_epoch) + "\n"; out += std::string{"nondeterministic="} + (ctx.nondeterministic ? "1" : "0") + "\n"; for (const auto &opt : ctx.compile_options) { out += "compile_option=" + opt + "\n"; } for (const auto &opt : ctx.link_options) { out += "link_option=" + opt + "\n"; } for (const auto &def : ctx.defines) { out += "define=" + def + "\n"; } for (const auto s : ctx.sanitizers) { out += "sanitizer=" + std::string{sanitizer_name(s)} + "\n"; } return out; } const JsonVal *find_key(const JsonVal::Object &obj, const std::string &k) { const auto it = obj.find(k); return it == obj.end() ? nullptr : &it->second; } std::optional get_str(const JsonVal::Object &obj, const std::string &k) { const auto *v = find_key(obj, k); if (!v) { return std::nullopt; } const auto *s = std::get_if(&v->value); return s ? std::optional{*s} : std::nullopt; } std::optional get_i64(const JsonVal::Object &obj, const std::string &k) { const auto *v = find_key(obj, k); if (!v) { return std::nullopt; } const auto *i = std::get_if(&v->value); return i ? std::optional{*i} : std::nullopt; } std::vector get_str_array(const JsonVal::Object &obj, const std::string &k) { std::vector out; const auto *v = find_key(obj, k); if (!v) { return out; } if (const auto *arr = std::get_if(&v->value)) { for (const auto &item : *arr) { if (const auto *s = std::get_if(&item.value)) { out.push_back(*s); } } } return out; } // Persisted stat-fingerprint -> content-hash memo for descriptor identity inputs. Large SDK // artifacts are hashed once and then trusted until their size or mtime changes. class FileHashMemo { public: explicit FileHashMemo(std::filesystem::path cache_file) : cache_file_{std::move(cache_file)} { auto text = Void::FileSystem::read_file(cache_file_); if (!text) { return; } auto parsed = Void::Json::Strict::parse(*text); if (!parsed) { return; } const auto *root = std::get_if(&parsed->value); if (root == nullptr) { return; } const auto *files_v = find_key(*root, "files"); const auto *files = files_v ? std::get_if(&files_v->value) : nullptr; if (files == nullptr) { return; } for (const auto &[path, value] : *files) { const auto *entry = std::get_if(&value.value); if (entry == nullptr) { continue; } auto sha = get_str(*entry, "sha256"); auto size = get_i64(*entry, "size"); auto mtime = get_i64(*entry, "mtime"); if (sha && size && mtime) { entries_[path] = Entry{std::move(*sha), HeaderFingerprint{*size, *mtime}}; } } } [[nodiscard]] std::optional lookup(const std::filesystem::path &path, const HeaderFingerprint &fingerprint) const { const auto it = entries_.find(path.string()); if (it != entries_.end() && it->second.fingerprint == fingerprint) { return it->second.sha256; } return std::nullopt; } void store(const std::filesystem::path &path, const HeaderFingerprint &fingerprint, std::string sha256) { const auto key = path.string(); const auto it = entries_.find(key); if (it != entries_.end() && it->second.fingerprint == fingerprint && it->second.sha256 == sha256) { return; } entries_[key] = Entry{std::move(sha256), fingerprint}; dirty_ = true; } void flush() { if (!dirty_) { return; } std::string json = "{\"files\":{"; bool first = true; for (const auto &[path, entry] : entries_) { if (!first) { json += ','; } first = false; json += Util::json_quote(path) + ":{\"sha256\":" + Util::json_quote(entry.sha256) + ",\"size\":" + std::to_string(entry.fingerprint.size) + ",\"mtime\":" + std::to_string(entry.fingerprint.mtime) + '}'; } json += "}}\n"; (void)Platform::atomic_write_file(cache_file_, json, false); dirty_ = false; } private: struct Entry { std::string sha256; HeaderFingerprint fingerprint; }; std::filesystem::path cache_file_; std::map> entries_; bool dirty_{false}; }; } // namespace Void::Result::Result, Void::Result::Error> discover_config_sources(const std::filesystem::path &project_root, const std::vector &extra_build_sources) { std::error_code ec; const auto canonical_root = std::filesystem::weakly_canonical(project_root, ec); if (ec || !std::filesystem::is_directory(canonical_root)) { return std::unexpected{ make_error(std::format("project root '{}' is not a directory", project_root.string()))}; } const auto root_build = canonical_root / "build.cpp"; const auto root_workspace = canonical_root / "workspace.cpp"; const bool has_build = std::filesystem::is_regular_file(root_build, ec); const bool has_workspace = std::filesystem::is_regular_file(root_workspace, ec); if (!has_build && !has_workspace) { return std::unexpected{ make_error(std::format("missing required root description '{}' or '{}'", root_build.string(), root_workspace.string()))}; } std::vector sources; std::set seen; auto push = [&](const std::filesystem::path &p) { const auto norm = p.lexically_normal(); if (seen.insert(norm).second) { sources.push_back(norm); } }; if (has_build) { push(root_build); } if (has_workspace) { push(root_workspace); } const auto profiles_cpp = canonical_root / "build.profiles.cpp"; if (std::filesystem::is_regular_file(profiles_cpp, ec)) { push(profiles_cpp); } // Filesystem-discovered build-support/**/*.cpp (works identically without .git!). const auto support_dir = canonical_root / "build-support"; if (std::filesystem::is_directory(support_dir, ec)) { std::vector helpers; for (const auto &entry : std::filesystem::recursive_directory_iterator(support_dir, ec)) { if (entry.is_regular_file(ec) && is_cpp_file(entry.path())) { helpers.push_back(entry.path().lexically_normal()); } } std::ranges::sort(helpers); for (const auto &h : helpers) { push(h); } } // Explicit --build-source inputs. for (const auto &extra : extra_build_sources) { const auto abs = extra.is_absolute() ? extra : (canonical_root / extra); if (!std::filesystem::is_regular_file(abs, ec)) { return std::unexpected{make_error( std::format("explicit --build-source '{}' does not exist", extra.string()))}; } push(abs); } return sources; } Void::Result::Result compile_descriptor(const FrontendOptions &options) { const auto phase_sw = Void::Time::Stopwatch::started(); auto sources_res = discover_config_sources(options.project_root, options.extra_build_sources); if (!sources_res) { return std::unexpected{sources_res.error()}; } Void::Log::debug("Config", "descriptor sources discovered in {:.1f} ms ({} source(s))", phase_sw.elapsed_ms(), sources_res->size()); std::error_code ec; const auto canonical_root = std::filesystem::weakly_canonical(options.project_root, ec); const auto config_dir = std::filesystem::weakly_canonical(options.build_root, ec) / ".vbs" / "config"; std::filesystem::create_directories(config_dir, ec); auto lock = Platform::FileLock::acquire(config_dir / "seed.lock", Platform::LockMode::Exclusive); if (!lock) { return std::unexpected{lock.error()}; } std::filesystem::path host_cxx; if (options.host_compiler && !options.host_compiler->empty()) { auto resolved = Platform::resolve_executable(*options.host_compiler); if (!resolved) { return std::unexpected{make_error(std::format( "configured host compiler '{}' was not found", options.host_compiler->string()))}; } host_cxx = *resolved; } else { auto resolved = Platform::resolve_executable("g++"); if (!resolved) { return std::unexpected{ make_error("host compiler 'g++' not found in PATH for compiling build.cpp")}; } host_cxx = *resolved; } // Memoized hashing: identity inputs are re-hashed only when their stat fingerprint changes. FileHashMemo hash_memo{config_dir / "identity_cache.json"}; const auto memoized_hash = [&](const std::filesystem::path &path) -> std::optional { const auto fingerprint = stat_fingerprint(path); if (fingerprint) { if (auto cached = hash_memo.lookup(path, *fingerprint)) { return cached; } } auto hash = Util::sha256_file_hex(path); if (!hash) { return std::nullopt; } if (fingerprint) { hash_memo.store(path, *fingerprint, *hash); } return *hash; }; auto host_hash = memoized_hash(host_cxx); if (!host_hash) { return std::unexpected{ make_error(std::format("cannot hash host compiler '{}'", host_cxx.string()))}; } const bool has_profiles = std::filesystem::is_regular_file(canonical_root / "build.profiles.cpp", ec); const bool has_build = std::filesystem::is_regular_file(canonical_root / "build.cpp", ec); const bool has_workspace = std::filesystem::is_regular_file(canonical_root / "workspace.cpp", ec); const std::string driver_src = generate_driver_source(has_profiles, has_build, has_workspace); const auto driver_cpp = config_dir / "Driver.cpp"; if (auto wrote = Platform::atomic_write_file(driver_cpp, driver_src, false); !wrote) { return std::unexpected{wrote.error()}; } // Compute seed identity over host compiler, SDK header/library, driver source, and config // sources. Util::Sha256Hasher id_hasher; id_hasher.update_length_prefixed("vbs-seed-v1"); id_hasher.update_length_prefixed(host_cxx.string()); id_hasher.update_length_prefixed(*host_hash); id_hasher.update_length_prefixed(driver_src); if (!options.sdk_include_dir.empty()) { if (auto hdr_h = memoized_hash(options.sdk_include_dir / "Void" / "Build.hpp"); hdr_h) { id_hasher.update_length_prefixed(*hdr_h); } } if (!options.sdk_library_path.empty() && std::filesystem::exists(options.sdk_library_path, ec)) { if (auto lib_h = memoized_hash(options.sdk_library_path); lib_h) { id_hasher.update_length_prefixed(*lib_h); } } for (const auto &src : *sources_res) { auto h = memoized_hash(src); if (!h) { return std::unexpected{ make_error(std::format("cannot hash configuration source '{}'", src.string()))}; } id_hasher.update_length_prefixed(src.string()); id_hasher.update_length_prefixed(*h); } const std::string seed_id = id_hasher.finalize_hex(); hash_memo.flush(); Void::Log::debug("Config", "descriptor identity hashed in {:.1f} ms", phase_sw.elapsed_ms()); const auto exe_path = config_dir / ("descriptor_" + seed_id.substr(0, 16)); const auto meta_path = config_dir / ("descriptor_" + seed_id.substr(0, 16) + ".headers.json"); // Check if cached descriptor executable exists AND all previously discovered headers match! // Header entries carry a stat fingerprint (size + mtime) beside the SHA-256: when the // fingerprint is unchanged the content hash is trusted and no file is read. Legacy entries // (plain hash strings) are still accepted and upgraded in place. struct HeaderMeta { std::string sha256; HeaderFingerprint fingerprint; }; bool up_to_date = false; bool metadata_stale = false; std::vector cached_headers; std::map> verified_headers; const auto write_meta = [&](const std::map> &headers) { std::string meta_json = "{\"seed_id\":" + Util::json_quote(seed_id) + ",\"headers\":{"; bool first = true; for (const auto &[hpath, meta] : headers) { if (!first) { meta_json += ','; } first = false; meta_json += Util::json_quote(hpath) + ":{\"sha256\":" + Util::json_quote(meta.sha256) + ",\"size\":" + std::to_string(meta.fingerprint.size) + ",\"mtime\":" + std::to_string(meta.fingerprint.mtime) + '}'; } meta_json += "}}\n"; (void)Platform::atomic_write_file(meta_path, meta_json, false); }; if (std::filesystem::is_regular_file(exe_path, ec) && std::filesystem::is_regular_file(meta_path, ec)) { if (auto meta_text = Void::FileSystem::read_file(meta_path); meta_text) { if (auto parsed = Void::Json::Strict::parse(*meta_text); parsed) { if (const auto *obj = std::get_if(&parsed->value)) { if (get_str(*obj, "seed_id").value_or("") == seed_id) { bool headers_ok = true; if (const auto *hv = find_key(*obj, "headers")) { if (const auto *hobj = std::get_if(&hv->value)) { for (const auto &[hpath, hval] : *hobj) { const std::filesystem::path header{hpath}; const auto fingerprint = stat_fingerprint(header); if (!fingerprint) { headers_ok = false; break; } std::string expected_sha; std::optional expected_fp; if (const auto *sha = std::get_if(&hval.value)) { expected_sha = *sha; // legacy entry metadata_stale = true; } else if (const auto *entry = std::get_if(&hval.value)) { expected_sha = get_str(*entry, "sha256").value_or(""); if (const auto size = get_i64(*entry, "size"); size && get_i64(*entry, "mtime")) { expected_fp = HeaderFingerprint{*size, *get_i64(*entry, "mtime")}; } } std::string actual_sha = expected_sha; if (expected_fp && *expected_fp == *fingerprint && !expected_sha.empty()) { // Unchanged stat fingerprint: trust the stored hash. } else { auto hashed = Util::sha256_file_hex(header); if (!hashed || (expected_sha.empty() && !expected_fp)) { headers_ok = false; break; } if (!expected_sha.empty() && *hashed != expected_sha) { headers_ok = false; break; } actual_sha = std::move(*hashed); metadata_stale = true; } verified_headers[hpath] = HeaderMeta{actual_sha, *fingerprint}; cached_headers.emplace_back(hpath); } } } up_to_date = headers_ok; } } } } } if (up_to_date && metadata_stale) { write_meta(verified_headers); } Void::Log::debug("Config", "descriptor check: seed identity + cache in {:.1f} ms", phase_sw.elapsed_ms()); if (up_to_date) { CompiledDescriptor desc; desc.executable_path = exe_path; desc.seed_identity_hash = seed_id; desc.config_sources = *sources_res; desc.discovered_headers = std::move(cached_headers); desc.recompiled = false; return desc; } // Compile each translation unit with depfiles so included headers enter configuration identity! const auto obj_dir = config_dir / ("obj_" + seed_id.substr(0, 16)); std::filesystem::create_directories(obj_dir, ec); std::vector compile_units = *sources_res; compile_units.push_back(driver_cpp); const bool use_prebuilt_sdk = !options.sdk_library_path.empty() && std::filesystem::is_regular_file(options.sdk_library_path, ec); if (!use_prebuilt_sdk && !options.sdk_source_dir.empty()) { compile_units.push_back(options.sdk_source_dir / "Build.cpp"); compile_units.push_back(options.sdk_source_dir / "Json.cpp"); } std::vector objects; std::map> header_hashes; for (std::size_t i = 0; i < compile_units.size(); ++i) { const auto &tu = compile_units[i]; const auto obj = obj_dir / std::format("tu_{}_{}.o", i, tu.stem().string()); const auto dep = obj_dir / std::format("tu_{}_{}.d", i, tu.stem().string()); Platform::ProcessRequest req; req.executable = host_cxx; req.arguments = {"-std=c++26", "-O1", "-I", canonical_root.string()}; if (!options.sdk_include_dir.empty()) { req.arguments.push_back("-I"); req.arguments.push_back(options.sdk_include_dir.string()); } req.arguments.push_back("-MMD"); req.arguments.push_back("-MF"); req.arguments.push_back(dep.string()); req.arguments.push_back("-c"); req.arguments.push_back(tu.string()); req.arguments.push_back("-o"); req.arguments.push_back(obj.string()); req.working_directory = canonical_root; req.timeout = std::chrono::seconds{60}; auto res = Platform::run_supervised(req); if (!res || !res->succeeded()) { const std::string detail = res ? (res->stderr_data.empty() ? res->exec_error_message : res->stderr_data) : res.error().message(); return std::unexpected{make_error( std::format("failed compiling configuration source '{}' (note: unresolved project " "package headers cannot be required during seed compilation):\n{}", tu.string(), detail))}; } objects.push_back(obj); if (auto deps = Execution::parse_depfile(dep); deps) { for (const auto &d : *deps) { const auto abs = d.is_absolute() ? d.lexically_normal() : (canonical_root / d).lexically_normal(); if (Platform::path_is_within(canonical_root, abs) || (!options.sdk_include_dir.empty() && Platform::path_is_within(options.sdk_include_dir, abs))) { if (auto hh = Util::sha256_file_hex(abs); hh) { header_hashes[abs.string()] = std::move(*hh); } } } } } // Link host descriptor executable atomically into staging then rename. const auto staged_exe = config_dir / std::format("descriptor_{}.stage_{}", seed_id.substr(0, 16), static_cast(::getpid())); { Platform::ProcessRequest req; req.executable = host_cxx; req.arguments = {"-std=c++26", "-o", staged_exe.string()}; for (const auto &o : objects) { req.arguments.push_back(o.string()); } if (use_prebuilt_sdk) { req.arguments.push_back(options.sdk_library_path.string()); } req.working_directory = canonical_root; req.timeout = std::chrono::seconds{60}; auto res = Platform::run_supervised(req); if (!res || !res->succeeded()) { std::filesystem::remove(staged_exe, ec); const std::string detail = res ? (res->stderr_data.empty() ? res->exec_error_message : res->stderr_data) : res.error().message(); return std::unexpected{ make_error(std::format("failed linking configuration descriptor:\n{}", detail))}; } } std::filesystem::rename(staged_exe, exe_path, ec); if (ec) { std::filesystem::remove(staged_exe, ec); return std::unexpected{make_error("failed publishing compiled descriptor executable")}; } // Persist discovered header hashes (with stat fingerprints) atomically. std::map> persisted_headers; std::vector headers_list; for (const auto &[hpath, hsha] : header_hashes) { const auto fingerprint = stat_fingerprint(hpath); persisted_headers[hpath] = HeaderMeta{hsha, fingerprint.value_or(HeaderFingerprint{})}; headers_list.emplace_back(hpath); } write_meta(persisted_headers); CompiledDescriptor desc; desc.executable_path = exe_path; desc.seed_identity_hash = seed_id; desc.config_sources = *sources_res; desc.discovered_headers = std::move(headers_list); desc.recompiled = true; return desc; } bool is_workspace_root(const std::filesystem::path &project_root) { std::error_code ec; return std::filesystem::is_regular_file(project_root / "workspace.cpp", ec); } Void::Result::Result discover_profiles(const CompiledDescriptor &descriptor, const FrontendOptions &options) { std::error_code ec; const auto run_dir = std::filesystem::weakly_canonical(options.build_root, ec) / ".vbs" / "config" / "eval"; std::filesystem::create_directories(run_dir, ec); const std::string req_id = std::format("prof_{}_{}", static_cast(::getpid()), g_req_seq.fetch_add(1, std::memory_order_relaxed)); const auto out_file = run_dir / (req_id + ".json"); Platform::ProcessRequest req; req.executable = descriptor.executable_path; req.arguments = {"--mode", "profiles", "--output", out_file.string(), "--request-id", req_id}; req.working_directory = options.project_root; req.timeout = options.eval_timeout; for (const auto &[key, value] : options.extra_environment) { req.environment.set_vars[key] = value; } auto proc = Platform::run_supervised(req); auto cleanup = [&] { std::filesystem::remove(out_file, ec); }; if (!proc) { cleanup(); return std::unexpected{proc.error()}; } if (!proc->succeeded()) { cleanup(); return std::unexpected{ make_error(std::format("profile discovery failed (exit={}, signal={}): {}", proc->exit_code, proc->term_signal, proc->stderr_data))}; } auto text = Void::FileSystem::read_file_bounded(out_file, {16ULL * 1024ULL * 1024ULL}); cleanup(); if (!text) { return std::unexpected{make_error("profile discovery did not write a valid result file")}; } if (!Util::is_valid_utf8(*text)) { return std::unexpected{make_error("profile discovery result contains invalid UTF-8")}; } auto parsed = Void::Json::Strict::parse(*text); if (!parsed) { return std::unexpected{make_error("profile discovery emitted malformed JSON")}; } const auto *root = std::get_if(&parsed->value); if (!root) { return std::unexpected{make_error("profile discovery envelope must be a JSON object")}; } if (get_i64(*root, "protocol_version").value_or(0) != kFrontendProtocolVersion) { return std::unexpected{make_error("profile discovery protocol version mismatch")}; } if (get_str(*root, "request_id").value_or("") != req_id) { return std::unexpected{make_error("profile discovery request_id mismatch")}; } const auto *payload_v = find_key(*root, "payload"); const auto *payload = payload_v ? std::get_if(&payload_v->value) : nullptr; if (!payload) { return std::unexpected{make_error("profile discovery missing payload")}; } const auto *profs_v = find_key(*payload, "profiles"); const auto *arr = profs_v ? std::get_if(&profs_v->value) : nullptr; if (!arr) { return std::unexpected{make_error("profile discovery payload missing profiles array")}; } try { Profiles result; for (const auto &pv : *arr) { const auto *po = std::get_if(&pv.value); if (!po) { continue; } ProfileDescription pd; pd.name = get_str(*po, "name").value_or(""); if (auto parent = get_str(*po, "parent"); parent && !parent->empty()) { pd.parent = *parent; } if (auto comp = get_str(*po, "compiler"); comp && !comp->empty()) { pd.compiler = parse_compiler(*comp); } if (auto std_str = get_str(*po, "c_standard"); std_str && !std_str->empty()) { pd.c_standard = Void::Build::parse_c_standard(*std_str); } if (auto std_str = get_str(*po, "cxx_standard"); std_str && !std_str->empty()) { pd.cxx_standard = parse_cxx_standard(*std_str); } if (auto lto_str = get_str(*po, "lto"); lto_str && !lto_str->empty()) { pd.lto = parse_lto_mode(*lto_str); } pd.sysroot = get_str(*po, "sysroot").value_or(""); pd.compiler_path = get_str(*po, "compiler_path").value_or(""); if (auto ep = get_i64(*po, "reproducibility_epoch")) { pd.reproducibility_epoch = *ep; } if (const auto *nd = find_key(*po, "nondeterministic")) { if (const auto *b = std::get_if(&nd->value)) { pd.nondeterministic = *b; } } pd.compile_options = get_str_array(*po, "compile_options"); pd.link_options = get_str_array(*po, "link_options"); pd.defines = get_str_array(*po, "defines"); for (const auto &s : get_str_array(*po, "sanitizers")) { pd.sanitizers.push_back(parse_sanitizer(s)); } result.define(std::move(pd)); } return result; } catch (const std::exception &ex) { return std::unexpected{make_error(ex.what())}; } } Void::Result::Result evaluate_project(const CompiledDescriptor &descriptor, const ProfileContext &context, const FrontendOptions &options) { std::error_code ec; const auto run_dir = std::filesystem::weakly_canonical(options.build_root, ec) / ".vbs" / "config" / "eval"; std::filesystem::create_directories(run_dir, ec); const std::string req_id = std::format("desc_{}_{}", static_cast(::getpid()), g_req_seq.fetch_add(1, std::memory_order_relaxed)); const auto ctx_file = run_dir / (req_id + ".ctx"); const auto out_file = run_dir / (req_id + ".json"); const std::string kv_text = serialize_kv_context(context); const std::string ctx_hash = Util::sha256_hex(kv_text); if (auto wrote = Platform::atomic_write_file(ctx_file, kv_text, false); !wrote) { return std::unexpected{wrote.error()}; } auto cleanup = [&] { std::filesystem::remove(ctx_file, ec); std::filesystem::remove(out_file, ec); }; Platform::ProcessRequest req; req.executable = descriptor.executable_path; req.arguments = {"--mode", "describe", "--output", out_file.string(), "--request-id", req_id, "--context-file", ctx_file.string(), "--context-hash", ctx_hash}; req.working_directory = options.project_root; req.timeout = options.eval_timeout; for (const auto &[key, value] : options.extra_environment) { req.environment.set_vars[key] = value; } auto proc = Platform::run_supervised(req); if (!proc) { cleanup(); return std::unexpected{proc.error()}; } if (!proc->succeeded()) { cleanup(); return std::unexpected{make_error( std::format("project evaluation failed for profile '{}' (exit={}, signal={}): {}", context.name, proc->exit_code, proc->term_signal, proc->stderr_data))}; } auto text = Void::FileSystem::read_file_bounded(out_file, {64ULL * 1024ULL * 1024ULL}); cleanup(); if (!text) { return std::unexpected{make_error("project evaluation did not produce a result file")}; } if (!Util::is_valid_utf8(*text)) { return std::unexpected{make_error("project evaluation result contains invalid UTF-8")}; } // Validate envelope header fields cleanly, then slice out payload JSON directly. auto parsed = Void::Json::Strict::parse(*text); if (!parsed) { return std::unexpected{make_error("project evaluation emitted malformed JSON")}; } const auto *root = std::get_if(&parsed->value); if (!root) { return std::unexpected{make_error("project evaluation envelope must be a JSON object")}; } if (get_i64(*root, "protocol_version").value_or(0) != kFrontendProtocolVersion) { return std::unexpected{make_error("project evaluation protocol version mismatch")}; } if (get_str(*root, "request_id").value_or("") != req_id) { return std::unexpected{make_error("project evaluation request_id mismatch")}; } if (get_str(*root, "context_hash").value_or("") != ctx_hash) { return std::unexpected{make_error("project evaluation context_hash mismatch")}; } const auto payload_marker = text->find("\"payload\":"); if (payload_marker == std::string::npos) { return std::unexpected{make_error("project evaluation envelope missing payload")}; } std::string_view payload_slice{*text}; payload_slice.remove_prefix(payload_marker + 10); while (!payload_slice.empty() && (payload_slice.back() == '\n' || payload_slice.back() == '\r' || payload_slice.back() == ' ')) { payload_slice.remove_suffix(1); } if (payload_slice.empty() || payload_slice.back() != '}') { return std::unexpected{make_error("project evaluation envelope truncated")}; } payload_slice.remove_suffix(1); // Remove enclosing envelope '}' auto desc = Graph::ProjectDescription::from_json(payload_slice); if (!desc) { return std::unexpected{desc.error()}; } if (desc->profile.name != context.name || desc->profile.compiler != context.compiler) { return std::unexpected{ make_error("project evaluation returned a mismatched profile context")}; } return desc; } Void::Result::Result evaluate_workspace(const CompiledDescriptor &descriptor, const FrontendOptions &options) { std::error_code ec; const auto run_dir = std::filesystem::weakly_canonical(options.build_root, ec) / ".vbs" / "config" / "eval"; std::filesystem::create_directories(run_dir, ec); const std::string req_id = std::format("ws_{}_{}", static_cast(::getpid()), g_req_seq.fetch_add(1, std::memory_order_relaxed)); const auto out_file = run_dir / (req_id + ".json"); Platform::ProcessRequest req; req.executable = descriptor.executable_path; req.arguments = {"--mode", "workspace", "--output", out_file.string(), "--request-id", req_id}; req.working_directory = options.project_root; req.timeout = options.eval_timeout; for (const auto &[key, value] : options.extra_environment) { req.environment.set_vars[key] = value; } auto proc = Platform::run_supervised(req); auto cleanup = [&] { std::filesystem::remove(out_file, ec); }; if (!proc) { cleanup(); return std::unexpected{proc.error()}; } if (!proc->succeeded()) { cleanup(); return std::unexpected{ make_error(std::format("workspace evaluation failed (exit={}, signal={}): {}", proc->exit_code, proc->term_signal, proc->stderr_data))}; } auto text = Void::FileSystem::read_file_bounded(out_file, {16ULL * 1024ULL * 1024ULL}); cleanup(); if (!text) { return std::unexpected{make_error("workspace evaluation did not produce a result file")}; } if (!Util::is_valid_utf8(*text)) { return std::unexpected{make_error("workspace evaluation result contains invalid UTF-8")}; } auto parsed = Void::Json::Strict::parse(*text); if (!parsed) { return std::unexpected{make_error("workspace evaluation emitted malformed JSON")}; } const auto *root = std::get_if(&parsed->value); if (!root) { return std::unexpected{make_error("workspace evaluation envelope must be a JSON object")}; } if (get_i64(*root, "protocol_version").value_or(0) != kFrontendProtocolVersion) { return std::unexpected{make_error("workspace evaluation protocol version mismatch")}; } if (get_str(*root, "request_id").value_or("") != req_id) { return std::unexpected{make_error("workspace evaluation request_id mismatch")}; } const auto *payload_v = find_key(*root, "payload"); const auto *payload = payload_v ? std::get_if(&payload_v->value) : nullptr; if (!payload) { return std::unexpected{make_error("workspace evaluation missing payload")}; } const auto *members_v = find_key(*payload, "members"); const auto *arr = members_v ? std::get_if(&members_v->value) : nullptr; if (!arr) { return std::unexpected{make_error("workspace evaluation payload missing members array")}; } WorkspaceDescription result; std::set seen; for (const auto &mv : *arr) { const auto *mobj = std::get_if(&mv.value); if (!mobj) { continue; } WorkspaceMember member; member.name = get_str(*mobj, "name").value_or(""); member.path = get_str(*mobj, "path").value_or(""); if (member.name.empty() || member.path.empty()) { return std::unexpected{make_error("workspace member requires nonempty name and path")}; } if (!seen.insert(member.name).second) { return std::unexpected{make_error("duplicate workspace member '" + member.name + "'")}; } result.members.push_back(std::move(member)); } return result; } } // namespace Void::Build::Config