Implement VoidBuildSystem v1 (Plans 01-19) with VoidLibrary integration
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 3s
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 3s
This commit is contained in:
1 parent
3cac890ce9
commit
ab64147f9d
114 files changed
+23777
-1392
No files matched your search
@@ -0,0 +1,285 @@
|
||||
#include <Void/Build/Bridge/CMakeBridge.hpp>
|
||||
|
||||
#include <Void/Build.hpp>
|
||||
#include <Void/Build/Config/Frontend.hpp>
|
||||
#include <Void/Build/Execution/Scheduler.hpp>
|
||||
#include <Void/Build/Graph/Graph.hpp>
|
||||
#include <Void/Build/Package/Fetch.hpp>
|
||||
#include <Void/Build/Platform/FileOps.hpp>
|
||||
#include <Void/Build/Provider/Provider.hpp>
|
||||
#include <Void/Build/Snapshot/Snapshot.hpp>
|
||||
#include <Void/Build/State/StateStore.hpp>
|
||||
#include <Void/Build/Toolchain/Driver.hpp>
|
||||
#include <Void/Data/StrictJson.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <format>
|
||||
#include <set>
|
||||
|
||||
namespace Void::Build::Bridge {
|
||||
namespace {
|
||||
|
||||
using JsonVal = Void::Json::Strict::Value;
|
||||
|
||||
Void::Result::Error make_error(std::string msg) {
|
||||
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
std::move(msg));
|
||||
}
|
||||
|
||||
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::string get_str(const JsonVal::Object &obj, const std::string &k) {
|
||||
const auto *v = find_key(obj, k);
|
||||
if (!v) {
|
||||
return {};
|
||||
}
|
||||
const auto *s = std::get_if<std::string>(&v->value);
|
||||
return s ? *s : std::string{};
|
||||
}
|
||||
|
||||
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
|
||||
const auto *v = find_key(obj, k);
|
||||
if (!v) {
|
||||
return def;
|
||||
}
|
||||
const auto *b = std::get_if<bool>(&v->value);
|
||||
return b ? *b : def;
|
||||
}
|
||||
|
||||
std::string escape_cmake(std::string_view s) {
|
||||
std::string out;
|
||||
for (const char c : s) {
|
||||
if (c == '\\' || c == '"' || c == '$' || c == ';') {
|
||||
out.push_back('\\');
|
||||
}
|
||||
out.push_back(c);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string emit_imported_target_cmake(const std::string &cmake_name,
|
||||
const Graph::ImportedTargetInterface &iface) {
|
||||
std::string cm_type = "INTERFACE";
|
||||
std::filesystem::path loc;
|
||||
if (!iface.static_libraries.empty()) {
|
||||
cm_type = "STATIC";
|
||||
loc = iface.static_libraries.front();
|
||||
} else if (!iface.shared_libraries.empty()) {
|
||||
cm_type = "SHARED";
|
||||
loc = iface.shared_libraries.front();
|
||||
}
|
||||
|
||||
std::string out;
|
||||
out += "if(NOT TARGET " + cmake_name + ")\n";
|
||||
out += " add_library(" + cmake_name + " " + cm_type + " IMPORTED GLOBAL)\n";
|
||||
if (!loc.empty()) {
|
||||
out += " set_property(TARGET " + cmake_name + " PROPERTY IMPORTED_LOCATION \"" +
|
||||
escape_cmake(loc.string()) + "\")\n";
|
||||
}
|
||||
if (!iface.include_dirs.empty()) {
|
||||
out += " set_property(TARGET " + cmake_name + " PROPERTY INTERFACE_INCLUDE_DIRECTORIES";
|
||||
for (const auto &[inc, is_sys] : iface.include_dirs) {
|
||||
(void)is_sys;
|
||||
out += " \"" + escape_cmake(inc.string()) + "\"";
|
||||
}
|
||||
out += ")\n";
|
||||
}
|
||||
if (!iface.defines.empty()) {
|
||||
out += " set_property(TARGET " + cmake_name + " PROPERTY INTERFACE_COMPILE_DEFINITIONS";
|
||||
for (const auto &def : iface.defines) {
|
||||
out += " \"" + escape_cmake(def) + "\"";
|
||||
}
|
||||
out += ")\n";
|
||||
}
|
||||
if (!iface.compile_options.empty()) {
|
||||
out += " set_property(TARGET " + cmake_name + " PROPERTY INTERFACE_COMPILE_OPTIONS";
|
||||
for (const auto &opt : iface.compile_options) {
|
||||
out += " \"" + escape_cmake(opt) + "\"";
|
||||
}
|
||||
out += ")\n";
|
||||
}
|
||||
// Preserve extra transitive static/shared libraries after the primary location!
|
||||
std::vector<std::string> extra_libs;
|
||||
for (std::size_t i = (cm_type == "STATIC" ? 1 : 0); i < iface.static_libraries.size(); ++i) {
|
||||
extra_libs.push_back(iface.static_libraries[i].string());
|
||||
}
|
||||
for (std::size_t i = (cm_type == "SHARED" ? 1 : 0); i < iface.shared_libraries.size(); ++i) {
|
||||
extra_libs.push_back(iface.shared_libraries[i].string());
|
||||
}
|
||||
for (const auto &lopt : iface.link_options) {
|
||||
extra_libs.push_back(lopt);
|
||||
}
|
||||
if (!extra_libs.empty()) {
|
||||
out += " set_property(TARGET " + cmake_name + " PROPERTY INTERFACE_LINK_LIBRARIES";
|
||||
for (const auto &lib : extra_libs) {
|
||||
out += " \"" + escape_cmake(lib) + "\"";
|
||||
}
|
||||
out += ")\n";
|
||||
}
|
||||
out += "endif()\n";
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error>
|
||||
execute_cmake_bridge(const std::filesystem::path &request_json_path,
|
||||
const std::filesystem::path &output_cmake_path) {
|
||||
auto text = Void::FileSystem::read_file(request_json_path);
|
||||
if (!text) {
|
||||
return std::unexpected{text.error()};
|
||||
}
|
||||
auto parsed = Void::Json::Strict::parse(*text);
|
||||
if (!parsed) {
|
||||
return std::unexpected{make_error("bridge request JSON is malformed")};
|
||||
}
|
||||
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
|
||||
if (!root) {
|
||||
return std::unexpected{make_error("bridge request root must be a JSON object")};
|
||||
}
|
||||
|
||||
const std::filesystem::path project_root = get_str(*root, "project_root");
|
||||
const std::filesystem::path build_root = get_str(*root, "build_root");
|
||||
const std::string profile_name = get_str(*root, "profile");
|
||||
const std::string compiler_str = get_str(*root, "compiler");
|
||||
const std::string compiler_path = get_str(*root, "compiler_path");
|
||||
const std::string os_name = get_str(*root, "os");
|
||||
const std::string arch_name = get_str(*root, "architecture");
|
||||
const bool offline = get_bool(*root, "offline", false);
|
||||
|
||||
// Reentry cycle guard (Plan 14: prevent infinite nested bridge recursion / lock deadlock).
|
||||
std::string active_stack;
|
||||
if (const char *env = std::getenv("VBS_BRIDGE_STACK")) {
|
||||
active_stack = env;
|
||||
}
|
||||
const std::string self_marker = "|" + project_root.string() + "|";
|
||||
if (active_stack.find(self_marker) != std::string::npos) {
|
||||
return std::unexpected{make_error(std::format(
|
||||
"reentrant VbsDeps bridge cycle detected for project '{}'", project_root.string()))};
|
||||
}
|
||||
|
||||
ProfileContext ctx = default_profiles().resolve(
|
||||
profile_name.empty() ? "debug" : profile_name,
|
||||
parse_compiler(compiler_str.empty() ? "gcc" : compiler_str),
|
||||
os_name.empty() ? Toolchain::host_os_name() : os_name,
|
||||
arch_name.empty() ? Toolchain::host_architecture_name() : arch_name);
|
||||
ctx.compiler_path = compiler_path;
|
||||
|
||||
auto tc = Toolchain::discover_and_probe(ctx, build_root / ".vbs" / "probes");
|
||||
if (!tc) {
|
||||
return std::unexpected{tc.error()};
|
||||
}
|
||||
|
||||
std::string generated_cmake = "# Generated by VoidBuildSystem CMake bridge (Plan 14)\n";
|
||||
std::set<std::string> emitted_names;
|
||||
|
||||
const auto *deps_v = find_key(*root, "dependencies");
|
||||
const auto *deps_arr = deps_v ? std::get_if<JsonVal::Array>(&deps_v->value) : nullptr;
|
||||
if (!deps_arr) {
|
||||
return std::unexpected{make_error("bridge request missing 'dependencies' array")};
|
||||
}
|
||||
|
||||
for (const auto &dv : *deps_arr) {
|
||||
const auto *dobj = std::get_if<JsonVal::Object>(&dv.value);
|
||||
if (!dobj) {
|
||||
continue;
|
||||
}
|
||||
DependencyRecord dep;
|
||||
dep.name = get_str(*dobj, "alias");
|
||||
dep.builder = get_str(*dobj, "builder");
|
||||
dep.registry_authority = get_str(*dobj, "registry");
|
||||
if (const auto git = get_str(*dobj, "git"); !git.empty()) {
|
||||
dep.source_kind = DependencySourceKind::Git;
|
||||
dep.location = git;
|
||||
dep.revision = get_str(*dobj, "rev");
|
||||
} else if (const auto pth = get_str(*dobj, "path"); !pth.empty()) {
|
||||
dep.source_kind = DependencySourceKind::Path;
|
||||
dep.location = pth;
|
||||
} else if (const auto arc = get_str(*dobj, "archive"); !arc.empty()) {
|
||||
dep.source_kind = DependencySourceKind::Archive;
|
||||
dep.location = arc;
|
||||
dep.sha256 = get_str(*dobj, "sha256");
|
||||
} else if (const auto pkg = get_str(*dobj, "package"); !pkg.empty()) {
|
||||
dep.source_kind = DependencySourceKind::Package;
|
||||
dep.package = pkg;
|
||||
dep.version = get_str(*dobj, "version");
|
||||
}
|
||||
if (const auto *ov = find_key(*dobj, "options")) {
|
||||
if (const auto *oo = std::get_if<JsonVal::Object>(&ov->value)) {
|
||||
for (const auto &[k, val] : *oo) {
|
||||
if (const auto *s = std::get_if<std::string>(&val.value)) {
|
||||
if (*s == "ON" || *s == "TRUE" || *s == "true") {
|
||||
dep.options.emplace(k, OptionValue{true});
|
||||
} else if (*s == "OFF" || *s == "FALSE" || *s == "false") {
|
||||
dep.options.emplace(k, OptionValue{false});
|
||||
} else {
|
||||
dep.options.emplace(k, OptionValue{*s});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Package::FetchOptions fopts;
|
||||
fopts.cache_dir = build_root / ".vbs" / "cache";
|
||||
fopts.project_root = project_root;
|
||||
fopts.offline = offline;
|
||||
auto mat = Package::materialize_dependency_source(dep, fopts);
|
||||
if (!mat) {
|
||||
return std::unexpected{mat.error()};
|
||||
}
|
||||
|
||||
// Auto-detect builder if unspecified.
|
||||
if (dep.builder.empty()) {
|
||||
std::error_code ec;
|
||||
if (std::filesystem::is_regular_file(mat->source_dir / "build.cpp", ec)) {
|
||||
dep.builder = "native";
|
||||
} else if (std::filesystem::is_regular_file(mat->source_dir / "CMakeLists.txt", ec)) {
|
||||
dep.builder = "cmake";
|
||||
} else if (std::filesystem::is_regular_file(mat->source_dir / "meson.build", ec)) {
|
||||
dep.builder = "meson";
|
||||
}
|
||||
}
|
||||
|
||||
if (dep.builder == "cmake" || dep.builder == "meson" || dep.builder == "conan") {
|
||||
Provider::ProviderRequest preq;
|
||||
preq.dependency = dep;
|
||||
preq.source = *mat;
|
||||
preq.profile = ctx;
|
||||
preq.toolchain = *tc;
|
||||
preq.provider_build_root = build_root / ".vbs" / "providers";
|
||||
preq.mode = Provider::ProviderMode::FullBuild;
|
||||
auto exp = Provider::resolve_foreign_provider(preq);
|
||||
if (!exp) {
|
||||
return std::unexpected{exp.error()};
|
||||
}
|
||||
for (const auto &[tname, iface] : exp->targets) {
|
||||
if (emitted_names.insert(tname).second) {
|
||||
generated_cmake += emit_imported_target_cmake(tname, iface);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Native VBS package source: check exported package.json or include/ layout.
|
||||
Graph::ImportedTargetInterface iface;
|
||||
iface.dependency_name = dep.name;
|
||||
iface.target_name = dep.name;
|
||||
std::error_code ec;
|
||||
if (std::filesystem::is_directory(mat->source_dir / "include", ec)) {
|
||||
iface.include_dirs.emplace_back(mat->source_dir / "include", false);
|
||||
}
|
||||
const std::string alias_tgt = dep.name + "::" + dep.name;
|
||||
if (emitted_names.insert(alias_tgt).second) {
|
||||
generated_cmake += emit_imported_target_cmake(alias_tgt, iface);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Platform::atomic_write_file(output_cmake_path, generated_cmake, true);
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Bridge
|
||||
+1177
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,761 @@
|
||||
#include <Void/Build/Config/Frontend.hpp>
|
||||
|
||||
#include <Void/Build/Execution/Scheduler.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/Data/StrictJson.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <format>
|
||||
#include <set>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace Void::Build::Config {
|
||||
namespace {
|
||||
|
||||
using JsonVal = Void::Json::Strict::Value;
|
||||
|
||||
std::atomic<std::uint64_t> 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";
|
||||
}
|
||||
|
||||
std::string generate_driver_source(bool has_profiles_file) {
|
||||
std::string code = R"cpp(#include <Void/Build.hpp>
|
||||
#include <Void/Build/Util/Json.hpp>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
)cpp";
|
||||
if (!has_profiles_file) {
|
||||
code += R"cpp(void profiles(Void::Build::Profiles &descriptions) {
|
||||
descriptions = Void::Build::default_profiles();
|
||||
}
|
||||
)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<std::string> split_lines(std::string_view text) {
|
||||
std::vector<std::string> 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 == "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;
|
||||
}
|
||||
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 += "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<std::string> 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<std::string>(&v->value);
|
||||
return s ? std::optional<std::string>{*s} : std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<std::int64_t> 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<std::int64_t>(&v->value);
|
||||
return i ? std::optional<std::int64_t>{*i} : std::nullopt;
|
||||
}
|
||||
|
||||
std::vector<std::string> get_str_array(const JsonVal::Object &obj, const std::string &k) {
|
||||
std::vector<std::string> out;
|
||||
const auto *v = find_key(obj, k);
|
||||
if (!v) {
|
||||
return out;
|
||||
}
|
||||
if (const auto *arr = std::get_if<JsonVal::Array>(&v->value)) {
|
||||
for (const auto &item : *arr) {
|
||||
if (const auto *s = std::get_if<std::string>(&item.value)) {
|
||||
out.push_back(*s);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<std::vector<std::filesystem::path>, Void::Result::Error>
|
||||
discover_config_sources(const std::filesystem::path &project_root,
|
||||
const std::vector<std::filesystem::path> &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";
|
||||
if (!std::filesystem::is_regular_file(root_build, ec)) {
|
||||
return std::unexpected{
|
||||
make_error(std::format("missing required root description '{}'", root_build.string()))};
|
||||
}
|
||||
|
||||
std::vector<std::filesystem::path> sources;
|
||||
std::set<std::filesystem::path> seen;
|
||||
auto push = [&](const std::filesystem::path &p) {
|
||||
const auto norm = p.lexically_normal();
|
||||
if (seen.insert(norm).second) {
|
||||
sources.push_back(norm);
|
||||
}
|
||||
};
|
||||
|
||||
push(root_build);
|
||||
|
||||
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<std::filesystem::path> 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<CompiledDescriptor, Void::Result::Error>
|
||||
compile_descriptor(const FrontendOptions &options) {
|
||||
auto sources_res = discover_config_sources(options.project_root, options.extra_build_sources);
|
||||
if (!sources_res) {
|
||||
return std::unexpected{sources_res.error()};
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
auto host_hash = Util::sha256_file_hex(host_cxx);
|
||||
if (!host_hash) {
|
||||
return std::unexpected{host_hash.error()};
|
||||
}
|
||||
|
||||
const bool has_profiles =
|
||||
std::filesystem::is_regular_file(canonical_root / "build.profiles.cpp", ec);
|
||||
const std::string driver_src = generate_driver_source(has_profiles);
|
||||
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 = Util::sha256_file_hex(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 = Util::sha256_file_hex(options.sdk_library_path); lib_h) {
|
||||
id_hasher.update_length_prefixed(*lib_h);
|
||||
}
|
||||
}
|
||||
for (const auto &src : *sources_res) {
|
||||
auto h = Util::sha256_file_hex(src);
|
||||
if (!h) {
|
||||
return std::unexpected{h.error()};
|
||||
}
|
||||
id_hasher.update_length_prefixed(src.string());
|
||||
id_hasher.update_length_prefixed(*h);
|
||||
}
|
||||
const std::string seed_id = id_hasher.finalize_hex();
|
||||
|
||||
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!
|
||||
bool up_to_date = false;
|
||||
std::vector<std::filesystem::path> cached_headers;
|
||||
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<JsonVal::Object>(&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<JsonVal::Object>(&hv->value)) {
|
||||
for (const auto &[hpath, hval] : *hobj) {
|
||||
const auto *expected = std::get_if<std::string>(&hval.value);
|
||||
auto actual =
|
||||
Util::sha256_file_hex(std::filesystem::path{hpath});
|
||||
if (!expected || !actual || *actual != *expected) {
|
||||
headers_ok = false;
|
||||
break;
|
||||
}
|
||||
cached_headers.emplace_back(hpath);
|
||||
}
|
||||
}
|
||||
}
|
||||
up_to_date = headers_ok;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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<std::filesystem::path> 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 / "Util" / "Json.cpp");
|
||||
}
|
||||
|
||||
std::vector<std::filesystem::path> objects;
|
||||
std::map<std::string, std::string, std::less<>> 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<long long>(::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 atomically.
|
||||
std::string meta_json = "{\"seed_id\":" + Util::json_quote(seed_id) + ",\"headers\":{";
|
||||
bool first = true;
|
||||
std::vector<std::filesystem::path> headers_list;
|
||||
for (const auto &[hpath, hsha] : header_hashes) {
|
||||
if (!first) {
|
||||
meta_json += ',';
|
||||
}
|
||||
first = false;
|
||||
meta_json += Util::json_quote(hpath) + ':' + Util::json_quote(hsha);
|
||||
headers_list.emplace_back(hpath);
|
||||
}
|
||||
meta_json += "}}\n";
|
||||
(void)Platform::atomic_write_file(meta_path, meta_json, false);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
Void::Result::Result<Profiles, Void::Result::Error>
|
||||
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<long long>(::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;
|
||||
|
||||
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<JsonVal::Object>(&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<JsonVal::Object>(&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<JsonVal::Array>(&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<JsonVal::Object>(&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, "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<bool>(&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<Graph::ProjectDescription, Void::Result::Error>
|
||||
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<long long>(::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;
|
||||
|
||||
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<JsonVal::Object>(&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;
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Config
|
||||
@@ -1,6 +1,6 @@
|
||||
#include <Void/Build.hpp>
|
||||
#include <Void/Build/BootstrapConfig.hpp>
|
||||
#include <Void/Configuration/Argparse.hpp>
|
||||
#include <vbs/bootstrap_config.hpp>
|
||||
#include <vbs/build.hpp>
|
||||
|
||||
#include <iostream>
|
||||
|
||||
@@ -29,11 +29,11 @@ int main(int argc, char **argv) {
|
||||
return 2;
|
||||
}
|
||||
try {
|
||||
vbs::Profiles descriptions;
|
||||
Void::Build::Profiles descriptions;
|
||||
profiles(descriptions);
|
||||
vbs::Project project{descriptions.resolve(profile, vbs::parse_compiler(compiler),
|
||||
std::string{vbs::bootstrap::os},
|
||||
std::string{vbs::bootstrap::architecture})};
|
||||
Void::Build::Project project{descriptions.resolve(
|
||||
profile, Void::Build::parse_compiler(compiler), std::string{Void::Build::Bootstrap::os},
|
||||
std::string{Void::Build::Bootstrap::architecture})};
|
||||
build(project);
|
||||
std::cout << project.to_json() << '\n';
|
||||
return 0;
|
||||
@@ -0,0 +1,574 @@
|
||||
#include <Void/Build/Editor/CompDb.hpp>
|
||||
|
||||
#include <Void/Build/Platform/FileOps.hpp>
|
||||
#include <Void/Build/Util/Json.hpp>
|
||||
#include <Void/Build/Util/Sha256.hpp>
|
||||
#include <Void/Data/StrictJson.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
|
||||
namespace Void::Build::Editor {
|
||||
namespace {
|
||||
|
||||
using JsonVal = Void::Json::Strict::Value;
|
||||
|
||||
Void::Result::Error make_error(std::string msg) {
|
||||
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
std::move(msg));
|
||||
}
|
||||
|
||||
std::string sanitize_profile_dir(std::string_view name) {
|
||||
std::string out;
|
||||
out.reserve(name.size());
|
||||
for (const char c : name) {
|
||||
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
||||
c == '_' || c == '-' || c == '.') {
|
||||
out.push_back(c);
|
||||
} else {
|
||||
out.push_back('_');
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string_view status_name(GenerationStatus s) {
|
||||
switch (s) {
|
||||
case GenerationStatus::Valid:
|
||||
return "valid";
|
||||
case GenerationStatus::Stale:
|
||||
return "stale";
|
||||
case GenerationStatus::Invalid:
|
||||
return "invalid";
|
||||
}
|
||||
return "invalid";
|
||||
}
|
||||
|
||||
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(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 {};
|
||||
}
|
||||
|
||||
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::string get_str(const JsonVal::Object &obj, const std::string &k) {
|
||||
const auto *v = find_key(obj, k);
|
||||
if (!v) {
|
||||
return {};
|
||||
}
|
||||
const auto *s = std::get_if<std::string>(&v->value);
|
||||
return s ? *s : std::string{};
|
||||
}
|
||||
|
||||
std::int64_t get_i64(const JsonVal::Object &obj, const std::string &k, std::int64_t def = 0) {
|
||||
const auto *v = find_key(obj, k);
|
||||
if (!v) {
|
||||
return def;
|
||||
}
|
||||
const auto *i = std::get_if<std::int64_t>(&v->value);
|
||||
return i ? *i : def;
|
||||
}
|
||||
|
||||
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
|
||||
const auto *v = find_key(obj, k);
|
||||
if (!v) {
|
||||
return def;
|
||||
}
|
||||
const auto *b = std::get_if<bool>(&v->value);
|
||||
return b ? *b : def;
|
||||
}
|
||||
|
||||
std::filesystem::path selection_file_path(const std::filesystem::path &project_root) {
|
||||
return project_root / ".vbs" / "editor_selection.json";
|
||||
}
|
||||
|
||||
std::filesystem::path selection_lock_path(const std::filesystem::path &project_root) {
|
||||
return project_root / ".vbs" / "editor_selection.lock";
|
||||
}
|
||||
|
||||
std::string serialize_selection(const SelectionState &st) {
|
||||
using Util::json_quote;
|
||||
return "{\"schema_version\":1,\"ticket\":" + std::to_string(st.ticket) +
|
||||
",\"selected_profile\":" + json_quote(st.selected_profile) +
|
||||
",\"selected_build_root\":" + json_quote(st.selected_build_root.string()) +
|
||||
",\"selected_generation_id\":" + json_quote(st.selected_generation_id) +
|
||||
",\"selected_compdb_path\":" + json_quote(st.selected_compdb_path.string()) +
|
||||
",\"managed_root_alias_active\":" +
|
||||
std::string{st.managed_root_alias_active ? "true" : "false"} +
|
||||
",\"root_alias_warning\":" + json_quote(st.root_alias_warning) + "}\n";
|
||||
}
|
||||
|
||||
std::optional<SelectionState> load_selection_locked(const std::filesystem::path &project_root) {
|
||||
auto text = Void::FileSystem::read_file(selection_file_path(project_root));
|
||||
if (!text) {
|
||||
return std::nullopt;
|
||||
}
|
||||
auto parsed = Void::Json::Strict::parse(*text);
|
||||
if (!parsed) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto *obj = std::get_if<JsonVal::Object>(&parsed->value);
|
||||
if (!obj) {
|
||||
return std::nullopt;
|
||||
}
|
||||
SelectionState st;
|
||||
st.ticket = static_cast<std::uint64_t>(get_i64(*obj, "ticket", 0));
|
||||
st.selected_profile = get_str(*obj, "selected_profile");
|
||||
st.selected_build_root = get_str(*obj, "selected_build_root");
|
||||
st.selected_generation_id = get_str(*obj, "selected_generation_id");
|
||||
st.selected_compdb_path = get_str(*obj, "selected_compdb_path");
|
||||
st.managed_root_alias_active = get_bool(*obj, "managed_root_alias_active", false);
|
||||
st.root_alias_warning = get_str(*obj, "root_alias_warning");
|
||||
return st;
|
||||
}
|
||||
|
||||
// Updates `<project_root>/compile_commands.json` ONLY if it does not exist or is already
|
||||
// a VBS-managed symlink. Preserves any unrelated user-owned file!
|
||||
Void::Result::Result<bool, Void::Result::Error>
|
||||
update_managed_root_alias(const std::filesystem::path &project_root,
|
||||
const std::filesystem::path &build_root,
|
||||
const std::filesystem::path &target_compdb, std::string &warning_out) {
|
||||
const auto root_alias = project_root / "compile_commands.json";
|
||||
auto meta = Platform::stat_lstat(root_alias);
|
||||
if (!meta) {
|
||||
return std::unexpected{meta.error()};
|
||||
}
|
||||
|
||||
if (meta->exists) {
|
||||
if (!meta->is_symlink) {
|
||||
warning_out = "preserved existing user-owned project-root compile_commands.json";
|
||||
return false;
|
||||
}
|
||||
// Check if symlink points into build_root or is recorded as managed.
|
||||
std::filesystem::path target_p{meta->symlink_target};
|
||||
if (!target_p.is_absolute()) {
|
||||
target_p = (project_root / target_p).lexically_normal();
|
||||
}
|
||||
std::error_code ec;
|
||||
const auto canon_build = std::filesystem::weakly_canonical(build_root, ec);
|
||||
if (!Platform::path_is_within(canon_build, target_p)) {
|
||||
warning_out =
|
||||
"preserved existing non-VBS symlink at project-root compile_commands.json";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
auto swapped = Platform::atomic_swap_symlink(root_alias, target_compdb);
|
||||
if (!swapped) {
|
||||
return std::unexpected{swapped.error()};
|
||||
}
|
||||
warning_out.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<EditorCommandEntry> project_editor_commands(const Graph::BuildGraph &graph) {
|
||||
std::vector<EditorCommandEntry> entries;
|
||||
std::error_code ec;
|
||||
|
||||
// Identify enabled targets so disabled targets are omitted, while ALL enabled targets
|
||||
// are included even if a build only executed a subset.
|
||||
std::set<std::string> enabled_targets;
|
||||
for (const auto &t : graph.targets) {
|
||||
if (t.enabled) {
|
||||
enabled_targets.insert(t.name);
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto &act : graph.actions) {
|
||||
if (act.kind != Graph::ActionKind::Compile) {
|
||||
continue;
|
||||
}
|
||||
if (!enabled_targets.contains(act.target_name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Reconstruct structured logical argv directly from typed operands —
|
||||
// NEVER regex/string-replace arbitrary flags or macro definitions!
|
||||
EditorCommandEntry entry;
|
||||
entry.directory = graph.project_root;
|
||||
entry.file = act.logical_source_file;
|
||||
entry.output = act.logical_output_file;
|
||||
entry.target_name = act.target_name;
|
||||
|
||||
entry.arguments.push_back(act.executable.string());
|
||||
if (!graph.toolchain.sysroot.empty()) {
|
||||
entry.arguments.push_back("--sysroot=" + graph.toolchain.sysroot);
|
||||
}
|
||||
if (const auto std_flag = cxx_standard_flag(act.cxx_standard); !std_flag.empty()) {
|
||||
entry.arguments.push_back(std_flag);
|
||||
}
|
||||
if (act.position_independent) {
|
||||
entry.arguments.push_back("-fPIC");
|
||||
}
|
||||
if (act.lto == LtoMode::Full) {
|
||||
entry.arguments.push_back("-flto");
|
||||
} else if (act.lto == LtoMode::Thin) {
|
||||
entry.arguments.push_back("-flto=thin");
|
||||
}
|
||||
if (!act.sanitizers.empty()) {
|
||||
std::string list;
|
||||
for (std::size_t i = 0; i < act.sanitizers.size(); ++i) {
|
||||
if (i > 0) {
|
||||
list += ',';
|
||||
}
|
||||
list += sanitizer_flag(act.sanitizers[i]);
|
||||
}
|
||||
entry.arguments.push_back("-fsanitize=" + list);
|
||||
entry.arguments.push_back("-fno-omit-frame-pointer");
|
||||
}
|
||||
if (act.precompiled_header) {
|
||||
entry.arguments.push_back("-include");
|
||||
entry.arguments.push_back(act.precompiled_header->string());
|
||||
}
|
||||
for (const auto &[inc_path, is_system] : act.logical_include_dirs) {
|
||||
entry.arguments.push_back(is_system ? "-isystem" : "-I");
|
||||
entry.arguments.push_back(inc_path.string());
|
||||
}
|
||||
for (const auto &def : act.defines) {
|
||||
entry.arguments.push_back("-D" + def);
|
||||
}
|
||||
for (const auto &opt : act.compile_options) {
|
||||
entry.arguments.push_back(opt);
|
||||
}
|
||||
entry.arguments.push_back("-c");
|
||||
entry.arguments.push_back(act.logical_source_file.string());
|
||||
entry.arguments.push_back("-o");
|
||||
entry.arguments.push_back(act.logical_output_file.string());
|
||||
|
||||
// Check generated prerequisites readiness (Plan 09/10).
|
||||
for (const auto &dep_id : act.dependencies) {
|
||||
const auto dit = graph.action_index_by_id.find(dep_id);
|
||||
if (dit == graph.action_index_by_id.end()) {
|
||||
continue;
|
||||
}
|
||||
const auto &producer = graph.actions[dit->second];
|
||||
if (producer.kind == Graph::ActionKind::Custom ||
|
||||
producer.kind == Graph::ActionKind::PrecompiledHeader) {
|
||||
for (const auto &out : producer.declared_outputs) {
|
||||
if (!std::filesystem::exists(out, ec)) {
|
||||
entry.missing_generated_prerequisites.push_back(out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
entries.push_back(std::move(entry));
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
std::string format_compile_commands_json(const std::vector<EditorCommandEntry> &entries) {
|
||||
using Util::json_array;
|
||||
using Util::json_quote;
|
||||
|
||||
std::string out{"[\n"};
|
||||
for (std::size_t i = 0; i < entries.size(); ++i) {
|
||||
const auto &e = entries[i];
|
||||
out += " {\"directory\":" + json_quote(e.directory.string()) +
|
||||
",\"file\":" + json_quote(e.file.string()) +
|
||||
",\"output\":" + json_quote(e.output.string()) +
|
||||
",\"arguments\":" + json_array(e.arguments, json_quote) + "}";
|
||||
if (i + 1 < entries.size()) {
|
||||
out += ',';
|
||||
}
|
||||
out += '\n';
|
||||
}
|
||||
out += "]\n";
|
||||
return out;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::uint64_t, Void::Result::Error>
|
||||
reserve_selection_ticket(const std::filesystem::path &project_root,
|
||||
const std::filesystem::path &build_root, std::string_view profile_name) {
|
||||
auto lock = Platform::FileLock::acquire(selection_lock_path(project_root),
|
||||
Platform::LockMode::Exclusive);
|
||||
if (!lock) {
|
||||
return std::unexpected{lock.error()};
|
||||
}
|
||||
SelectionState st = load_selection_locked(project_root).value_or(SelectionState{});
|
||||
st.ticket += 1;
|
||||
// Record reservation ticket monotonically without pointing to an unvalidated generation yet.
|
||||
if (st.selected_build_root.empty()) {
|
||||
st.selected_build_root = build_root;
|
||||
}
|
||||
if (st.selected_profile.empty()) {
|
||||
st.selected_profile = std::string{profile_name};
|
||||
}
|
||||
auto wrote = Platform::atomic_write_file(selection_file_path(project_root),
|
||||
serialize_selection(st), true);
|
||||
if (!wrote) {
|
||||
return std::unexpected{wrote.error()};
|
||||
}
|
||||
return st.ticket;
|
||||
}
|
||||
|
||||
Void::Result::Result<EditorGeneration, Void::Result::Error>
|
||||
publish_profile_compdb(const Graph::BuildGraph &graph, const PublishOptions &options) {
|
||||
const auto entries = project_editor_commands(graph);
|
||||
const std::string compdb_json = format_compile_commands_json(entries);
|
||||
const std::string gen_id =
|
||||
Util::sha256_hex(graph.profile_identity + "\n" + compdb_json).substr(0, 16);
|
||||
|
||||
const auto profile_dir =
|
||||
options.build_root / "profiles" / sanitize_profile_dir(graph.profile.name);
|
||||
const auto gen_dir = profile_dir / "editor" / "generations" / gen_id;
|
||||
const auto gen_compdb = gen_dir / "compile_commands.json";
|
||||
const auto profile_compdb = profile_dir / "compile_commands.json";
|
||||
const auto status_file = profile_dir / "editor" / "status.json";
|
||||
|
||||
EditorGeneration gen;
|
||||
gen.generation_id = gen_id;
|
||||
gen.profile_name = graph.profile.name;
|
||||
gen.profile_identity = graph.profile_identity;
|
||||
gen.status = GenerationStatus::Valid;
|
||||
gen.compdb_path = gen_compdb;
|
||||
gen.entry_count = entries.size();
|
||||
|
||||
for (const auto &e : entries) {
|
||||
for (const auto &missing : e.missing_generated_prerequisites) {
|
||||
gen.readiness_warnings.push_back(std::format("target '{}' missing generated input '{}'",
|
||||
e.target_name, missing.string()));
|
||||
}
|
||||
}
|
||||
|
||||
// Avoid needless rewrite when identical immutable generation bytes already exist.
|
||||
bool bytes_changed = true;
|
||||
if (auto existing = Void::FileSystem::read_file(gen_compdb);
|
||||
existing && *existing == compdb_json) {
|
||||
bytes_changed = false;
|
||||
}
|
||||
if (bytes_changed) {
|
||||
if (auto w = Platform::atomic_write_file(gen_compdb, compdb_json, true); !w) {
|
||||
return std::unexpected{w.error()};
|
||||
}
|
||||
}
|
||||
|
||||
// Atomically update per-profile compile_commands.json pointer.
|
||||
if (auto sw = Platform::atomic_swap_symlink(profile_compdb, gen_compdb); !sw) {
|
||||
return std::unexpected{sw.error()};
|
||||
}
|
||||
|
||||
// Write per-profile status record atomically.
|
||||
const std::string status_json =
|
||||
"{\"schema_version\":1,\"profile\":" + Util::json_quote(graph.profile.name) +
|
||||
",\"generation_id\":" + Util::json_quote(gen_id) +
|
||||
",\"status\":\"valid\",\"diagnostic\":\"\"" +
|
||||
",\"compdb_path\":" + Util::json_quote(gen_compdb.string()) +
|
||||
",\"entry_count\":" + std::to_string(entries.size()) +
|
||||
",\"readiness_warnings\":" + Util::json_array(gen.readiness_warnings, Util::json_quote) +
|
||||
"}\n";
|
||||
if (auto sw = Platform::atomic_write_file(status_file, status_json, true); !sw) {
|
||||
return std::unexpected{sw.error()};
|
||||
}
|
||||
|
||||
// Coordinate project-level editor selection under short exclusive lock with ticket/revision
|
||||
// check!
|
||||
auto lock = Platform::FileLock::acquire(selection_lock_path(options.project_root),
|
||||
Platform::LockMode::Exclusive);
|
||||
if (!lock) {
|
||||
return std::unexpected{lock.error()};
|
||||
}
|
||||
|
||||
SelectionState st = load_selection_locked(options.project_root).value_or(SelectionState{});
|
||||
bool should_select = false;
|
||||
if (options.update_selection) {
|
||||
const std::uint64_t my_ticket = options.reserved_ticket.value_or(st.ticket + 1);
|
||||
// Reject stale late completions whose reserved ticket was superseded by a newer request!
|
||||
if (my_ticket >= st.ticket) {
|
||||
st.ticket = my_ticket;
|
||||
should_select = true;
|
||||
}
|
||||
} else if (st.selected_profile == graph.profile.name &&
|
||||
st.selected_build_root == options.build_root) {
|
||||
// Watchers refresh the ALREADY-SELECTED profile without stealing selection!
|
||||
should_select = true;
|
||||
}
|
||||
|
||||
if (should_select) {
|
||||
st.selected_profile = graph.profile.name;
|
||||
st.selected_build_root = options.build_root;
|
||||
st.selected_generation_id = gen_id;
|
||||
st.selected_compdb_path = gen_compdb;
|
||||
|
||||
const auto build_root_compdb = options.build_root / "compile_commands.json";
|
||||
if (auto sw = Platform::atomic_swap_symlink(build_root_compdb, gen_compdb); !sw) {
|
||||
return std::unexpected{sw.error()};
|
||||
}
|
||||
if (options.manage_project_root_alias) {
|
||||
std::string warn;
|
||||
auto alias_res = update_managed_root_alias(options.project_root, options.build_root,
|
||||
gen_compdb, warn);
|
||||
if (!alias_res) {
|
||||
return std::unexpected{alias_res.error()};
|
||||
}
|
||||
st.managed_root_alias_active = *alias_res;
|
||||
st.root_alias_warning = std::move(warn);
|
||||
}
|
||||
if (auto w = Platform::atomic_write_file(selection_file_path(options.project_root),
|
||||
serialize_selection(st), true);
|
||||
!w) {
|
||||
return std::unexpected{w.error()};
|
||||
}
|
||||
}
|
||||
|
||||
return gen;
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error>
|
||||
mark_profile_stale(const std::filesystem::path &build_root, std::string_view profile_name,
|
||||
GenerationStatus status, std::string_view diagnostic) {
|
||||
const auto profile_dir = build_root / "profiles" / sanitize_profile_dir(profile_name);
|
||||
const auto status_file = profile_dir / "editor" / "status.json";
|
||||
|
||||
// Preserve previous valid generation ID/path if present so editors see clearly stale DB.
|
||||
std::string prev_gen;
|
||||
std::string prev_path;
|
||||
if (auto existing = Void::FileSystem::read_file(status_file); existing) {
|
||||
if (auto parsed = Void::Json::Strict::parse(*existing); parsed) {
|
||||
if (const auto *obj = std::get_if<JsonVal::Object>(&parsed->value)) {
|
||||
prev_gen = get_str(*obj, "generation_id");
|
||||
prev_path = get_str(*obj, "compdb_path");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const std::string json = "{\"schema_version\":1,\"profile\":" + Util::json_quote(profile_name) +
|
||||
",\"generation_id\":" + Util::json_quote(prev_gen) +
|
||||
",\"status\":" + Util::json_quote(status_name(status)) +
|
||||
",\"diagnostic\":" + Util::json_quote(diagnostic) +
|
||||
",\"compdb_path\":" + Util::json_quote(prev_path) + "}\n";
|
||||
return Platform::atomic_write_file(status_file, json, true);
|
||||
}
|
||||
|
||||
Void::Result::Result<SelectionState, Void::Result::Error>
|
||||
select_editor_profile(const std::filesystem::path &project_root,
|
||||
const std::filesystem::path &build_root, std::string_view profile_name,
|
||||
bool manage_project_root_alias) {
|
||||
const auto profile_dir = build_root / "profiles" / sanitize_profile_dir(profile_name);
|
||||
const auto status_file = profile_dir / "editor" / "status.json";
|
||||
auto text = Void::FileSystem::read_file(status_file);
|
||||
if (!text) {
|
||||
return std::unexpected{make_error(
|
||||
std::format("no published compilation database for profile '{}'", profile_name))};
|
||||
}
|
||||
auto parsed = Void::Json::Strict::parse(*text);
|
||||
if (!parsed) {
|
||||
return std::unexpected{make_error("corrupt editor status metadata")};
|
||||
}
|
||||
const auto *obj = std::get_if<JsonVal::Object>(&parsed->value);
|
||||
if (!obj) {
|
||||
return std::unexpected{make_error("invalid editor status metadata")};
|
||||
}
|
||||
const auto gen_id = get_str(*obj, "generation_id");
|
||||
const auto compdb_str = get_str(*obj, "compdb_path");
|
||||
if (compdb_str.empty() || !std::filesystem::exists(compdb_str)) {
|
||||
return std::unexpected{make_error(std::format(
|
||||
"profile '{}' has no valid compilation database generation", profile_name))};
|
||||
}
|
||||
|
||||
auto lock = Platform::FileLock::acquire(selection_lock_path(project_root),
|
||||
Platform::LockMode::Exclusive);
|
||||
if (!lock) {
|
||||
return std::unexpected{lock.error()};
|
||||
}
|
||||
|
||||
SelectionState st = load_selection_locked(project_root).value_or(SelectionState{});
|
||||
st.ticket += 1;
|
||||
st.selected_profile = std::string{profile_name};
|
||||
st.selected_build_root = build_root;
|
||||
st.selected_generation_id = gen_id;
|
||||
st.selected_compdb_path = compdb_str;
|
||||
|
||||
if (auto sw = Platform::atomic_swap_symlink(build_root / "compile_commands.json",
|
||||
st.selected_compdb_path);
|
||||
!sw) {
|
||||
return std::unexpected{sw.error()};
|
||||
}
|
||||
if (manage_project_root_alias) {
|
||||
std::string warn;
|
||||
auto alias_res =
|
||||
update_managed_root_alias(project_root, build_root, st.selected_compdb_path, warn);
|
||||
if (!alias_res) {
|
||||
return std::unexpected{alias_res.error()};
|
||||
}
|
||||
st.managed_root_alias_active = *alias_res;
|
||||
st.root_alias_warning = std::move(warn);
|
||||
}
|
||||
if (auto w = Platform::atomic_write_file(selection_file_path(project_root),
|
||||
serialize_selection(st), true);
|
||||
!w) {
|
||||
return std::unexpected{w.error()};
|
||||
}
|
||||
return st;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<SelectionState>, Void::Result::Error>
|
||||
read_selection_state(const std::filesystem::path &project_root) {
|
||||
auto lock =
|
||||
Platform::FileLock::acquire(selection_lock_path(project_root), Platform::LockMode::Shared);
|
||||
if (!lock) {
|
||||
return std::unexpected{lock.error()};
|
||||
}
|
||||
return load_selection_locked(project_root);
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error>
|
||||
recover_editor_pointers(const std::filesystem::path &project_root) {
|
||||
auto lock = Platform::FileLock::acquire(selection_lock_path(project_root),
|
||||
Platform::LockMode::Exclusive);
|
||||
if (!lock) {
|
||||
return std::unexpected{lock.error()};
|
||||
}
|
||||
auto st = load_selection_locked(project_root);
|
||||
if (!st || st->selected_compdb_path.empty() ||
|
||||
!std::filesystem::exists(st->selected_compdb_path)) {
|
||||
return {};
|
||||
}
|
||||
if (!st->selected_build_root.empty()) {
|
||||
(void)Platform::atomic_swap_symlink(st->selected_build_root / "compile_commands.json",
|
||||
st->selected_compdb_path);
|
||||
}
|
||||
if (st->managed_root_alias_active) {
|
||||
std::string warn;
|
||||
(void)update_managed_root_alias(project_root, st->selected_build_root,
|
||||
st->selected_compdb_path, warn);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Editor
|
||||
@@ -0,0 +1,542 @@
|
||||
#include <Void/Build/Execution/Scheduler.hpp>
|
||||
|
||||
#include <Void/Async/ThreadPool.hpp>
|
||||
#include <Void/Build/Platform/FileOps.hpp>
|
||||
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||
#include <Void/Build/Util/Sha256.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
#include <Void/Time/Stopwatch.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <format>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
|
||||
namespace Void::Build::Execution {
|
||||
namespace {
|
||||
|
||||
Void::Result::Error make_error(std::string msg) {
|
||||
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
std::move(msg));
|
||||
}
|
||||
|
||||
std::string compute_effective_action_key(const Graph::ActionNode &action) {
|
||||
// Re-hash declared input file bytes at execution time (including generated upstream outputs!)
|
||||
// so downstream compile/archive/link actions invalidate immediately when an upstream artifact
|
||||
// changes.
|
||||
Util::Sha256Hasher hasher;
|
||||
hasher.update_length_prefixed(action.action_key);
|
||||
for (const auto &in_path : action.declared_inputs) {
|
||||
hasher.update_length_prefixed(in_path.string());
|
||||
if (auto digest = Util::sha256_file_hex(in_path); digest) {
|
||||
hasher.update_length_prefixed(*digest);
|
||||
} else {
|
||||
hasher.update_length_prefixed("<missing>");
|
||||
}
|
||||
}
|
||||
return hasher.finalize_hex();
|
||||
}
|
||||
|
||||
bool verify_discovered_inputs_unchanged(
|
||||
const std::map<std::string, std::string, std::less<>> &discovered_inputs) {
|
||||
for (const auto &[path_str, expected_sha] : discovered_inputs) {
|
||||
auto actual = Util::sha256_file_hex(std::filesystem::path{path_str});
|
||||
if (!actual || *actual != expected_sha) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool verify_outputs_match_record(const Graph::ActionNode &action,
|
||||
const State::ActionSuccessRecord &record) {
|
||||
for (const auto &out_path : action.declared_outputs) {
|
||||
const auto it = record.outputs.find(out_path.string());
|
||||
if (it == record.outputs.end()) {
|
||||
return false;
|
||||
}
|
||||
auto actual = Util::sha256_file_hex(out_path);
|
||||
if (!actual || *actual != it->second.sha256) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool restore_outputs_from_cache(const Graph::ActionNode &action,
|
||||
const State::ActionSuccessRecord &record,
|
||||
const State::StateStore &state) {
|
||||
for (const auto &out_path : action.declared_outputs) {
|
||||
const auto it = record.outputs.find(out_path.string());
|
||||
if (it == record.outputs.end()) {
|
||||
return false;
|
||||
}
|
||||
auto mat = state.materialize_blob(it->second, out_path);
|
||||
if (!mat) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::set<std::string> collect_ancestors(const Graph::BuildGraph &graph, const std::string &id) {
|
||||
std::set<std::string> ancestors;
|
||||
std::queue<std::string> q;
|
||||
const auto idx_it = graph.action_index_by_id.find(id);
|
||||
if (idx_it == graph.action_index_by_id.end()) {
|
||||
return ancestors;
|
||||
}
|
||||
for (const auto &dep : graph.actions[idx_it->second].dependencies) {
|
||||
if (ancestors.insert(dep).second) {
|
||||
q.push(dep);
|
||||
}
|
||||
}
|
||||
while (!q.empty()) {
|
||||
const auto cur = q.front();
|
||||
q.pop();
|
||||
const auto cit = graph.action_index_by_id.find(cur);
|
||||
if (cit == graph.action_index_by_id.end()) {
|
||||
continue;
|
||||
}
|
||||
for (const auto &dep : graph.actions[cit->second].dependencies) {
|
||||
if (ancestors.insert(dep).second) {
|
||||
q.push(dep);
|
||||
}
|
||||
}
|
||||
}
|
||||
return ancestors;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<std::vector<std::filesystem::path>, Void::Result::Error>
|
||||
parse_depfile(const std::filesystem::path &depfile_path) {
|
||||
auto text = Void::FileSystem::read_file(depfile_path);
|
||||
if (!text) {
|
||||
return std::unexpected{text.error()};
|
||||
}
|
||||
|
||||
// Remove backslash-newline continuations.
|
||||
std::string unfolded;
|
||||
unfolded.reserve(text->size());
|
||||
for (std::size_t i = 0; i < text->size(); ++i) {
|
||||
if ((*text)[i] == '\\' && i + 1 < text->size() && (*text)[i + 1] == '\n') {
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
if ((*text)[i] == '\\' && i + 2 < text->size() && (*text)[i + 1] == '\r' &&
|
||||
(*text)[i + 2] == '\n') {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
unfolded.push_back((*text)[i]);
|
||||
}
|
||||
|
||||
// Find the first unescaped colon separating target(s) from prerequisites.
|
||||
std::size_t colon = std::string::npos;
|
||||
for (std::size_t i = 0; i < unfolded.size(); ++i) {
|
||||
if (unfolded[i] == '\\' && i + 1 < unfolded.size()) {
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
if (unfolded[i] == ':') {
|
||||
colon = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (colon == std::string::npos) {
|
||||
return std::unexpected{make_error(std::format(
|
||||
"parse_depfile: malformed depfile '{}' (missing ':')", depfile_path.string()))};
|
||||
}
|
||||
|
||||
std::vector<std::filesystem::path> deps;
|
||||
std::set<std::string> seen;
|
||||
std::size_t pos = colon + 1;
|
||||
while (pos < unfolded.size()) {
|
||||
while (pos < unfolded.size() && (unfolded[pos] == ' ' || unfolded[pos] == '\t' ||
|
||||
unfolded[pos] == '\n' || unfolded[pos] == '\r')) {
|
||||
++pos;
|
||||
}
|
||||
if (pos >= unfolded.size()) {
|
||||
break;
|
||||
}
|
||||
std::string token;
|
||||
while (pos < unfolded.size() && unfolded[pos] != ' ' && unfolded[pos] != '\t' &&
|
||||
unfolded[pos] != '\n' && unfolded[pos] != '\r') {
|
||||
if (unfolded[pos] == '\\' && pos + 1 < unfolded.size()) {
|
||||
const char next = unfolded[pos + 1];
|
||||
if (next == ' ' || next == '#' || next == '\\' || next == ':') {
|
||||
token.push_back(next);
|
||||
pos += 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (unfolded[pos] == '$' && pos + 1 < unfolded.size() && unfolded[pos + 1] == '$') {
|
||||
token.push_back('$');
|
||||
pos += 2;
|
||||
continue;
|
||||
}
|
||||
token.push_back(unfolded[pos++]);
|
||||
}
|
||||
if (!token.empty() && seen.insert(token).second) {
|
||||
deps.emplace_back(std::move(token));
|
||||
}
|
||||
}
|
||||
return deps;
|
||||
}
|
||||
|
||||
Void::Result::Result<ExecutionReport, Void::Result::Error>
|
||||
execute_graph(const Graph::BuildGraph &graph, State::StateStore &state,
|
||||
const ExecutionOptions &options, std::stop_token external_stop) {
|
||||
auto selected_indices_res = graph.select_action_closure(options.selected_targets);
|
||||
if (!selected_indices_res) {
|
||||
return std::unexpected{selected_indices_res.error()};
|
||||
}
|
||||
const auto &selected_indices = *selected_indices_res;
|
||||
|
||||
ExecutionReport report;
|
||||
report.total_selected = selected_indices.size();
|
||||
if (selected_indices.empty()) {
|
||||
report.succeeded = true;
|
||||
return report;
|
||||
}
|
||||
|
||||
// Serialize writers to the same profile directory; independent profiles run concurrently.
|
||||
const auto profile_lock_path = graph.profile_build_dir / ".profile.lock";
|
||||
auto profile_lock =
|
||||
Platform::FileLock::acquire(profile_lock_path, Platform::LockMode::Exclusive);
|
||||
if (!profile_lock) {
|
||||
return std::unexpected{profile_lock.error()};
|
||||
}
|
||||
|
||||
auto lease = state.acquire_lease(graph.profile.name);
|
||||
if (!lease) {
|
||||
return std::unexpected{lease.error()};
|
||||
}
|
||||
|
||||
// Map every output path across the entire graph to its producer action ID
|
||||
// so we can detect unordered generated inputs discovered via depfiles (Plan 03/06).
|
||||
std::map<std::filesystem::path, std::string> all_output_producers;
|
||||
for (const auto &act : graph.actions) {
|
||||
for (const auto &out : act.declared_outputs) {
|
||||
all_output_producers[out.lexically_normal()] = act.id;
|
||||
}
|
||||
}
|
||||
|
||||
// Build subgraph dependency tables over selected_indices.
|
||||
std::set<std::size_t> selected_set(selected_indices.begin(), selected_indices.end());
|
||||
std::map<std::size_t, std::size_t> in_degree;
|
||||
std::map<std::size_t, std::vector<std::size_t>> dependents;
|
||||
for (const std::size_t idx : selected_indices) {
|
||||
in_degree[idx] = 0;
|
||||
}
|
||||
for (const std::size_t idx : selected_indices) {
|
||||
for (const auto &dep_id : graph.actions[idx].dependencies) {
|
||||
const auto dit = graph.action_index_by_id.find(dep_id);
|
||||
if (dit != graph.action_index_by_id.end() && selected_set.contains(dit->second)) {
|
||||
++in_degree[idx];
|
||||
dependents[dit->second].push_back(idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const std::size_t worker_count =
|
||||
std::min(selected_indices.size(),
|
||||
options.jobs > 0 ? options.jobs
|
||||
: std::max<std::size_t>(1, std::thread::hardware_concurrency()));
|
||||
|
||||
std::mutex mu;
|
||||
std::condition_variable cv;
|
||||
std::queue<std::size_t> ready;
|
||||
for (const std::size_t idx : selected_indices) {
|
||||
if (in_degree[idx] == 0) {
|
||||
ready.push(idx);
|
||||
}
|
||||
}
|
||||
|
||||
std::stop_source internal_stop;
|
||||
std::stop_callback forward_stop(external_stop, [&] { internal_stop.request_stop(); });
|
||||
|
||||
std::size_t active_workers = 0;
|
||||
std::size_t completed_count = 0;
|
||||
bool abort_scheduling = false;
|
||||
|
||||
auto emit_event = [&](ExecutionEvent::Kind kind, const Graph::ActionNode &act,
|
||||
std::size_t completed, std::string msg = {}) {
|
||||
if (options.on_event) {
|
||||
options.on_event(ExecutionEvent{kind, act.id, act.target_name, completed,
|
||||
selected_indices.size(), std::move(msg)});
|
||||
}
|
||||
};
|
||||
|
||||
auto run_one_action = [&](const Graph::ActionNode &act) -> ActionExecutionResult {
|
||||
const auto timer = Void::Time::Stopwatch::started();
|
||||
ActionExecutionResult res;
|
||||
res.action_id = act.id;
|
||||
res.target_name = act.target_name;
|
||||
|
||||
if (internal_stop.stop_requested()) {
|
||||
res.cancelled = true;
|
||||
res.error_message = "cancelled before start";
|
||||
return res;
|
||||
}
|
||||
|
||||
const std::string effective_key = compute_effective_action_key(act);
|
||||
|
||||
// 1. Cache lookup (ONLY when action is deterministic & cacheable!).
|
||||
if (act.cacheable && !act.nondeterministic && options.use_cache) {
|
||||
auto cached = state.lookup_action(effective_key);
|
||||
if (cached && cached->has_value()) {
|
||||
const auto &rec = **cached;
|
||||
if (verify_discovered_inputs_unchanged(rec.discovered_inputs)) {
|
||||
if (verify_outputs_match_record(act, rec) ||
|
||||
restore_outputs_from_cache(act, rec, state)) {
|
||||
res.succeeded = true;
|
||||
res.from_cache = true;
|
||||
res.exit_code = 0;
|
||||
res.elapsed = timer.elapsed_as<std::chrono::milliseconds>();
|
||||
return res;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Prepare output directories and response file.
|
||||
std::error_code ec;
|
||||
for (const auto &out : act.declared_outputs) {
|
||||
if (out.has_parent_path()) {
|
||||
std::filesystem::create_directories(out.parent_path(), ec);
|
||||
}
|
||||
// Critical invariant (Plan 03): remove pre-existing archive before `ar rcsD`
|
||||
// so deleted object files never linger as stale archive members!
|
||||
if (act.kind == Graph::ActionKind::Archive) {
|
||||
std::filesystem::remove(out, ec);
|
||||
}
|
||||
}
|
||||
if (act.depfile && act.depfile->has_parent_path()) {
|
||||
std::filesystem::create_directories(act.depfile->parent_path(), ec);
|
||||
std::filesystem::remove(*act.depfile, ec);
|
||||
}
|
||||
if (act.response_file) {
|
||||
auto wrote_rsp =
|
||||
Platform::atomic_write_file(*act.response_file, act.response_file_content, false);
|
||||
if (!wrote_rsp) {
|
||||
res.error_message = "failed writing response file: " + wrote_rsp.error().message();
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Execute subprocess under Linux process-group supervisor.
|
||||
Platform::ProcessRequest preq;
|
||||
preq.executable = act.executable;
|
||||
preq.arguments = act.arguments;
|
||||
if (!act.working_directory.empty()) {
|
||||
preq.working_directory = act.working_directory;
|
||||
}
|
||||
preq.environment.mode = Platform::EnvPolicyMode::Inherit;
|
||||
preq.environment.set_vars = act.environment;
|
||||
preq.timeout = options.action_timeout;
|
||||
|
||||
auto proc = Platform::run_supervised(preq, internal_stop.get_token());
|
||||
res.elapsed = timer.elapsed_as<std::chrono::milliseconds>();
|
||||
if (!proc) {
|
||||
res.error_message = proc.error().message();
|
||||
return res;
|
||||
}
|
||||
|
||||
res.stdout_data = std::move(proc->stdout_data);
|
||||
res.stderr_data = std::move(proc->stderr_data);
|
||||
res.exit_code = proc->exit_code;
|
||||
res.term_signal = proc->term_signal;
|
||||
res.cancelled = proc->cancelled;
|
||||
res.timed_out = proc->timed_out;
|
||||
|
||||
if (proc->exec_failed) {
|
||||
res.error_message = proc->exec_error_message;
|
||||
return res;
|
||||
}
|
||||
if (proc->cancelled) {
|
||||
res.error_message = "action cancelled";
|
||||
return res;
|
||||
}
|
||||
if (proc->timed_out) {
|
||||
res.error_message = "action timed out";
|
||||
return res;
|
||||
}
|
||||
if (proc->overflowed) {
|
||||
res.error_message = "action output exceeded capture limit";
|
||||
return res;
|
||||
}
|
||||
if (!proc->succeeded()) {
|
||||
res.error_message = proc->term_signal != 0
|
||||
? std::format("terminated by signal {}", proc->term_signal)
|
||||
: std::format("exited with status {}", proc->exit_code);
|
||||
return res;
|
||||
}
|
||||
|
||||
// 4. Validate ALL declared outputs exist after zero exit!
|
||||
for (const auto &out : act.declared_outputs) {
|
||||
auto meta = Platform::stat_lstat(out);
|
||||
if (!meta || !meta->exists || !meta->is_regular) {
|
||||
res.error_message =
|
||||
std::format("action '{}' exited 0 but required output '{}' is missing", act.id,
|
||||
out.string());
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Parse depfile (if declared) and verify no unordered generated producer escaped DAG!
|
||||
std::map<std::string, std::string, std::less<>> discovered_inputs;
|
||||
if (act.depfile && std::filesystem::exists(*act.depfile, ec)) {
|
||||
auto deps_res = parse_depfile(*act.depfile);
|
||||
if (!deps_res) {
|
||||
res.error_message = std::format("action '{}' produced invalid depfile: {}", act.id,
|
||||
deps_res.error().message());
|
||||
return res;
|
||||
}
|
||||
const auto ancestors = collect_ancestors(graph, act.id);
|
||||
for (const auto &dep_raw : *deps_res) {
|
||||
const auto dep_abs = dep_raw.is_absolute()
|
||||
? dep_raw.lexically_normal()
|
||||
: (act.working_directory / dep_raw).lexically_normal();
|
||||
if (const auto prod_it = all_output_producers.find(dep_abs);
|
||||
prod_it != all_output_producers.end() && prod_it->second != act.id &&
|
||||
!ancestors.contains(prod_it->second)) {
|
||||
res.error_message = std::format(
|
||||
"action '{}' read generated file '{}' from unordered producer '{}' "
|
||||
"(declare an explicit dependency/depends_on)",
|
||||
act.id, dep_abs.string(), prod_it->second);
|
||||
return res;
|
||||
}
|
||||
if (auto digest = Util::sha256_file_hex(dep_abs); digest) {
|
||||
discovered_inputs[dep_abs.string()] = std::move(*digest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Publish outputs to CAS BEFORE recording success (only for cacheable actions).
|
||||
if (act.cacheable && !act.nondeterministic) {
|
||||
State::ActionSuccessRecord rec;
|
||||
rec.action_key = effective_key;
|
||||
rec.profile_identity = graph.profile_identity;
|
||||
rec.target_name = act.target_name;
|
||||
rec.discovered_inputs = std::move(discovered_inputs);
|
||||
rec.recorded_epoch = std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch())
|
||||
.count();
|
||||
|
||||
for (const auto &out : act.declared_outputs) {
|
||||
auto stored = state.store_blob_from_file(out);
|
||||
if (!stored) {
|
||||
res.error_message = std::format("failed publishing output '{}' to CAS: {}",
|
||||
out.string(), stored.error().message());
|
||||
return res;
|
||||
}
|
||||
rec.outputs[out.string()] = std::move(*stored);
|
||||
}
|
||||
auto committed = state.record_action_success(rec);
|
||||
if (!committed) {
|
||||
res.error_message = std::format("failed committing action success record: {}",
|
||||
committed.error().message());
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
res.succeeded = true;
|
||||
return res;
|
||||
};
|
||||
|
||||
auto worker_loop = [&] {
|
||||
for (;;) {
|
||||
std::size_t idx = 0;
|
||||
{
|
||||
std::unique_lock lk{mu};
|
||||
cv.wait(lk, [&] {
|
||||
return !ready.empty() || abort_scheduling || internal_stop.stop_requested() ||
|
||||
(active_workers == 0 && ready.empty());
|
||||
});
|
||||
if (abort_scheduling || internal_stop.stop_requested()) {
|
||||
return;
|
||||
}
|
||||
if (ready.empty()) {
|
||||
if (active_workers == 0) {
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
idx = ready.front();
|
||||
ready.pop();
|
||||
++active_workers;
|
||||
}
|
||||
|
||||
const auto &act = graph.actions[idx];
|
||||
emit_event(ExecutionEvent::Kind::ActionStarted, act, completed_count);
|
||||
auto ares = run_one_action(act);
|
||||
|
||||
{
|
||||
std::lock_guard lk{mu};
|
||||
--active_workers;
|
||||
++completed_count;
|
||||
if (ares.succeeded) {
|
||||
if (ares.from_cache) {
|
||||
++report.cached_count;
|
||||
emit_event(ExecutionEvent::Kind::ActionCached, act, completed_count);
|
||||
} else {
|
||||
++report.executed_count;
|
||||
emit_event(ExecutionEvent::Kind::ActionSucceeded, act, completed_count);
|
||||
}
|
||||
for (const std::size_t dep_idx : dependents[idx]) {
|
||||
if (--in_degree[dep_idx] == 0) {
|
||||
ready.push(dep_idx);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
++report.failed_count;
|
||||
if (ares.cancelled) {
|
||||
report.cancelled = true;
|
||||
}
|
||||
if (report.diagnostic.empty()) {
|
||||
report.diagnostic = act.id + ": " + ares.error_message;
|
||||
}
|
||||
emit_event(ExecutionEvent::Kind::ActionFailed, act, completed_count,
|
||||
ares.error_message);
|
||||
if (options.fail_fast) {
|
||||
abort_scheduling = true;
|
||||
internal_stop.request_stop();
|
||||
}
|
||||
}
|
||||
report.results.push_back(std::move(ares));
|
||||
}
|
||||
cv.notify_all();
|
||||
}
|
||||
};
|
||||
|
||||
Void::Concurrency::ThreadPool pool{worker_count};
|
||||
std::vector<std::future<void>> worker_futures;
|
||||
worker_futures.reserve(worker_count);
|
||||
for (std::size_t w = 0; w < worker_count; ++w) {
|
||||
worker_futures.push_back(pool.submit(worker_loop));
|
||||
}
|
||||
for (auto &f : worker_futures) {
|
||||
f.get();
|
||||
}
|
||||
|
||||
if (external_stop.stop_requested()) {
|
||||
report.cancelled = true;
|
||||
}
|
||||
report.succeeded = (report.failed_count == 0) && !report.cancelled &&
|
||||
(report.executed_count + report.cached_count == report.total_selected);
|
||||
if (!report.succeeded && report.diagnostic.empty()) {
|
||||
report.diagnostic = report.cancelled ? "build cancelled" : "build incomplete";
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Execution
|
||||
+1924
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,418 @@
|
||||
#include <Void/Build/Install/Installer.hpp>
|
||||
|
||||
#include <Void/Build/Platform/FileOps.hpp>
|
||||
#include <Void/Build/Util/Json.hpp>
|
||||
#include <Void/Build/Util/Sha256.hpp>
|
||||
#include <Void/Core/Scope.hpp>
|
||||
#include <Void/Data/StrictJson.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <set>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace Void::Build::Install {
|
||||
namespace {
|
||||
|
||||
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
|
||||
return Void::System::make_system_error(code, std::move(msg));
|
||||
}
|
||||
|
||||
bool is_safe_relative_dest(const std::filesystem::path &rel) {
|
||||
if (rel.empty() || rel.is_absolute()) {
|
||||
return false;
|
||||
}
|
||||
const auto norm = rel.lexically_normal();
|
||||
for (const auto &part : norm) {
|
||||
if (part == "..") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string default_dest_for_kind(TargetKind kind) {
|
||||
switch (kind) {
|
||||
case TargetKind::Executable:
|
||||
case TargetKind::Test:
|
||||
return "bin";
|
||||
case TargetKind::StaticLibrary:
|
||||
case TargetKind::SharedLibrary:
|
||||
case TargetKind::ObjectLibrary:
|
||||
return "lib";
|
||||
case TargetKind::HeaderOnly:
|
||||
case TargetKind::CustomAction:
|
||||
return "share";
|
||||
}
|
||||
return "share";
|
||||
}
|
||||
|
||||
std::string escape_cmake_str(std::string_view s) {
|
||||
std::string out;
|
||||
for (const char c : s) {
|
||||
if (c == '\\' || c == '"' || c == '$' || c == ';') {
|
||||
out.push_back('\\');
|
||||
}
|
||||
out.push_back(c);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<InstallReport, Void::Result::Error>
|
||||
install_project(const Graph::ProjectDescription &description, const Graph::BuildGraph &graph,
|
||||
const InstallOptions &options) {
|
||||
if (options.prefix.empty()) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::invalid_argument, "install prefix is empty")};
|
||||
}
|
||||
if (options.package_name.empty()) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"install package_name is empty")};
|
||||
}
|
||||
|
||||
std::error_code ec;
|
||||
const auto prefix_abs = std::filesystem::weakly_canonical(options.prefix, ec);
|
||||
const auto proj_root = graph.project_root;
|
||||
if (Platform::path_is_within(proj_root, prefix_abs) &&
|
||||
!Platform::path_is_within(graph.profile_build_dir, prefix_abs) && prefix_abs == proj_root) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::permission_denied,
|
||||
"refusing to install directly onto project source root")};
|
||||
}
|
||||
|
||||
// Build complete list of staged copy operations and detect destination collisions upfront!
|
||||
struct StagedItem {
|
||||
std::filesystem::path src;
|
||||
std::filesystem::path rel_dest;
|
||||
std::uint32_t mode{0644};
|
||||
std::string target_name;
|
||||
};
|
||||
std::vector<StagedItem> items;
|
||||
std::set<std::filesystem::path> dest_set;
|
||||
|
||||
auto add_item =
|
||||
[&](const std::filesystem::path &src, const std::filesystem::path &rel_dest,
|
||||
std::uint32_t mode,
|
||||
std::string target_name = {}) -> Void::Result::Result<void, Void::Result::Error> {
|
||||
if (!is_safe_relative_dest(rel_dest)) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::permission_denied,
|
||||
std::format("install destination '{}' escapes prefix", rel_dest.string()))};
|
||||
}
|
||||
const auto norm = rel_dest.lexically_normal();
|
||||
if (!dest_set.insert(norm).second) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("install destination collision on '{}'", norm.string()))};
|
||||
}
|
||||
if (!std::filesystem::is_regular_file(src, ec)) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::not_found,
|
||||
std::format("install source artifact '{}' does not exist (build target first)",
|
||||
src.string()))};
|
||||
}
|
||||
items.push_back({src, norm, mode, std::move(target_name)});
|
||||
return {};
|
||||
};
|
||||
|
||||
// 1. Installed targets.
|
||||
struct ExportedTarget {
|
||||
std::string name;
|
||||
TargetKind kind;
|
||||
std::filesystem::path rel_artifact;
|
||||
std::vector<std::string> public_defines;
|
||||
std::vector<std::string> public_compile_opts;
|
||||
std::vector<std::string> local_deps;
|
||||
};
|
||||
std::vector<ExportedTarget> exported_targets;
|
||||
|
||||
for (const auto &trec : description.targets) {
|
||||
if (!trec.install_rule) {
|
||||
continue;
|
||||
}
|
||||
if (options.component && trec.install_rule->component != *options.component) {
|
||||
continue;
|
||||
}
|
||||
const std::string dest_dir = trec.install_rule->destination.empty()
|
||||
? default_dest_for_kind(trec.kind)
|
||||
: trec.install_rule->destination;
|
||||
const auto sum_it =
|
||||
std::ranges::find(graph.targets, trec.name, &Graph::ResolvedTargetSummary::name);
|
||||
if (sum_it == graph.targets.end()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
ExportedTarget et;
|
||||
et.name = trec.name;
|
||||
et.kind = trec.kind;
|
||||
for (const auto &d : trec.defines) {
|
||||
if (d.visibility != Visibility::Private) {
|
||||
et.public_defines.push_back(d.value);
|
||||
}
|
||||
}
|
||||
for (const auto &o : trec.scoped_compile_options) {
|
||||
if (o.visibility != Visibility::Private) {
|
||||
et.public_compile_opts.push_back(o.value);
|
||||
}
|
||||
}
|
||||
for (const auto &l : trec.links) {
|
||||
if (l.kind == LinkKind::Local &&
|
||||
(l.visibility != Visibility::Private || trec.kind == TargetKind::StaticLibrary)) {
|
||||
et.local_deps.push_back(l.target);
|
||||
}
|
||||
}
|
||||
|
||||
if (!sum_it->primary_outputs.empty()) {
|
||||
const auto &art = sum_it->primary_outputs.front();
|
||||
const auto rel_dest = std::filesystem::path{dest_dir} / art.filename();
|
||||
const std::uint32_t mode =
|
||||
(trec.kind == TargetKind::Executable || trec.kind == TargetKind::SharedLibrary)
|
||||
? 0755u
|
||||
: 0644u;
|
||||
if (auto r = add_item(art, rel_dest, mode, trec.name); !r) {
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
et.rel_artifact = rel_dest;
|
||||
}
|
||||
exported_targets.push_back(std::move(et));
|
||||
}
|
||||
|
||||
// 2. Project file & directory install rules (headers/data).
|
||||
for (const auto &rule : description.install_rules) {
|
||||
if (options.component && rule.component != *options.component) {
|
||||
continue;
|
||||
}
|
||||
const auto src_abs = std::filesystem::path{rule.source_path}.is_absolute()
|
||||
? std::filesystem::path{rule.source_path}
|
||||
: (proj_root / rule.source_path);
|
||||
if (rule.is_directory) {
|
||||
if (!std::filesystem::is_directory(src_abs, ec)) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::not_found,
|
||||
std::format("install directory '{}' does not exist", src_abs.string()))};
|
||||
}
|
||||
for (const auto &ent : std::filesystem::recursive_directory_iterator(src_abs, ec)) {
|
||||
if (ent.is_regular_file(ec)) {
|
||||
const auto rel = ent.path().lexically_relative(src_abs);
|
||||
if (auto r = add_item(ent.path(), std::filesystem::path{rule.destination} / rel,
|
||||
0644u);
|
||||
!r) {
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const auto rel_dest = std::filesystem::path{rule.destination} / src_abs.filename();
|
||||
if (auto r = add_item(src_abs, rel_dest, 0644u); !r) {
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Stage everything privately first so failed installs never leave broken metadata.
|
||||
const auto stage_root = graph.profile_build_dir /
|
||||
std::format("install-stage-{}", static_cast<long long>(::getpid()));
|
||||
std::filesystem::remove_all(stage_root, ec);
|
||||
std::filesystem::create_directories(stage_root, ec);
|
||||
auto stage_guard = Void::Scope::on_exit([&] { std::filesystem::remove_all(stage_root, ec); });
|
||||
|
||||
std::vector<std::filesystem::path> owned_rel_files;
|
||||
for (const auto &item : items) {
|
||||
const auto staged = stage_root / item.rel_dest;
|
||||
auto copied = Platform::copy_isolated(item.src, staged, item.mode);
|
||||
if (!copied) {
|
||||
return std::unexpected{copied.error()};
|
||||
}
|
||||
owned_rel_files.push_back(item.rel_dest);
|
||||
}
|
||||
|
||||
// 4. Generate relocatable native package metadata (ZERO build/snapshot paths!).
|
||||
std::optional<std::filesystem::path> native_rel;
|
||||
if (options.export_native_metadata) {
|
||||
using Util::json_array;
|
||||
using Util::json_quote;
|
||||
|
||||
native_rel = std::filesystem::path{"share"} / "vbs" / options.package_name / "package.json";
|
||||
std::string pjson =
|
||||
"{\"schema_version\":1,\"name\":" + json_quote(options.package_name) +
|
||||
",\"version\":" + json_quote(options.package_version) +
|
||||
",\"profile\":" + json_quote(graph.profile.name) +
|
||||
",\"compiler\":" + json_quote(compiler_name(graph.profile.compiler)) +
|
||||
",\"os\":" + json_quote(graph.profile.os) +
|
||||
",\"architecture\":" + json_quote(graph.profile.architecture) +
|
||||
",\"include_dir\":\"include\",\"targets\":" +
|
||||
json_array(exported_targets,
|
||||
[](const ExportedTarget &et) {
|
||||
return "{\"name\":" + json_quote(et.name) +
|
||||
",\"kind\":" + json_quote(target_kind_name(et.kind)) +
|
||||
",\"artifact\":" + json_quote(et.rel_artifact.generic_string()) +
|
||||
",\"defines\":" + json_array(et.public_defines, json_quote) +
|
||||
",\"compile_options\":" +
|
||||
json_array(et.public_compile_opts, json_quote) +
|
||||
",\"dependencies\":" + json_array(et.local_deps, json_quote) +
|
||||
'}';
|
||||
}) +
|
||||
"}\n";
|
||||
if (auto w = Platform::atomic_write_file(stage_root / *native_rel, pjson, false); !w) {
|
||||
return std::unexpected{w.error()};
|
||||
}
|
||||
owned_rel_files.push_back(*native_rel);
|
||||
}
|
||||
|
||||
// 5. Generate relocatable CMake Config + Targets files using ${_vbs_prefix} relative paths!
|
||||
std::optional<std::filesystem::path> cmake_rel;
|
||||
if (options.export_cmake_config) {
|
||||
const auto cmake_dir = std::filesystem::path{"lib"} / "cmake" / options.package_name;
|
||||
cmake_rel = cmake_dir / (options.package_name + "Config.cmake");
|
||||
const auto targets_rel = cmake_dir / (options.package_name + "Targets.cmake");
|
||||
|
||||
std::string cfg_cmake =
|
||||
"# Relocatable CMake config generated by VoidBuildSystem\n"
|
||||
"get_filename_component(_vbs_prefix \"${CMAKE_CURRENT_LIST_DIR}/../../..\" ABSOLUTE)\n"
|
||||
"include(\"${CMAKE_CURRENT_LIST_DIR}/" +
|
||||
options.package_name + "Targets.cmake\")\n";
|
||||
|
||||
std::string tgt_cmake =
|
||||
"# Relocatable CMake imported targets generated by VoidBuildSystem\n"
|
||||
"get_filename_component(_vbs_prefix \"${CMAKE_CURRENT_LIST_DIR}/../../..\" ABSOLUTE)\n";
|
||||
for (const auto &et : exported_targets) {
|
||||
const std::string full = options.package_name + "::" + et.name;
|
||||
std::string cm_type = "STATIC";
|
||||
if (et.kind == TargetKind::SharedLibrary) {
|
||||
cm_type = "SHARED";
|
||||
} else if (et.kind == TargetKind::HeaderOnly) {
|
||||
cm_type = "INTERFACE";
|
||||
} else if (et.kind == TargetKind::Executable) {
|
||||
continue;
|
||||
}
|
||||
tgt_cmake += "if(NOT TARGET " + full + ")\n";
|
||||
tgt_cmake += " add_library(" + full + " " + cm_type + " IMPORTED)\n";
|
||||
tgt_cmake += " set_target_properties(" + full + " PROPERTIES\n";
|
||||
if (!et.rel_artifact.empty()) {
|
||||
tgt_cmake += " IMPORTED_LOCATION \"${_vbs_prefix}/" +
|
||||
escape_cmake_str(et.rel_artifact.generic_string()) + "\"\n";
|
||||
}
|
||||
tgt_cmake += " INTERFACE_INCLUDE_DIRECTORIES \"${_vbs_prefix}/include\"\n";
|
||||
if (!et.public_defines.empty()) {
|
||||
tgt_cmake += " INTERFACE_COMPILE_DEFINITIONS \"";
|
||||
for (std::size_t i = 0; i < et.public_defines.size(); ++i) {
|
||||
if (i > 0) {
|
||||
tgt_cmake += ";";
|
||||
}
|
||||
tgt_cmake += escape_cmake_str(et.public_defines[i]);
|
||||
}
|
||||
tgt_cmake += "\"\n";
|
||||
}
|
||||
if (!et.local_deps.empty()) {
|
||||
tgt_cmake += " INTERFACE_LINK_LIBRARIES \"";
|
||||
for (std::size_t i = 0; i < et.local_deps.size(); ++i) {
|
||||
if (i > 0) {
|
||||
tgt_cmake += ";";
|
||||
}
|
||||
tgt_cmake += options.package_name + "::" + et.local_deps[i];
|
||||
}
|
||||
tgt_cmake += "\"\n";
|
||||
}
|
||||
tgt_cmake += " )\nendif()\n";
|
||||
}
|
||||
|
||||
if (auto w = Platform::atomic_write_file(stage_root / *cmake_rel, cfg_cmake, false); !w) {
|
||||
return std::unexpected{w.error()};
|
||||
}
|
||||
if (auto w = Platform::atomic_write_file(stage_root / targets_rel, tgt_cmake, false); !w) {
|
||||
return std::unexpected{w.error()};
|
||||
}
|
||||
owned_rel_files.push_back(*cmake_rel);
|
||||
owned_rel_files.push_back(targets_rel);
|
||||
}
|
||||
|
||||
// 6. Publish staged files into prefix atomically and write ownership manifest.
|
||||
std::filesystem::create_directories(prefix_abs, ec);
|
||||
InstallReport report;
|
||||
report.prefix = prefix_abs;
|
||||
|
||||
for (const auto &rel : owned_rel_files) {
|
||||
const auto staged = stage_root / rel;
|
||||
const auto final_dst = prefix_abs / rel;
|
||||
auto meta = Platform::stat_lstat(staged);
|
||||
auto copied = Platform::copy_isolated(staged, final_dst, meta ? meta->mode : 0644u);
|
||||
if (!copied) {
|
||||
return std::unexpected{copied.error()};
|
||||
}
|
||||
report.installed_files.push_back(final_dst);
|
||||
}
|
||||
|
||||
report.manifest_path = prefix_abs / ".vbs-install-manifest.json";
|
||||
if (native_rel) {
|
||||
report.native_package_file = prefix_abs / *native_rel;
|
||||
}
|
||||
if (cmake_rel) {
|
||||
report.cmake_config_file = prefix_abs / *cmake_rel;
|
||||
}
|
||||
|
||||
const std::string manifest_json =
|
||||
"{\"schema_version\":1,\"package\":" + Util::json_quote(options.package_name) +
|
||||
",\"files\":" +
|
||||
Util::json_array(
|
||||
owned_rel_files,
|
||||
[](const std::filesystem::path &p) { return Util::json_quote(p.generic_string()); }) +
|
||||
"}\n";
|
||||
auto mw = Platform::atomic_write_file(report.manifest_path, manifest_json, true);
|
||||
if (!mw) {
|
||||
return std::unexpected{mw.error()};
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::size_t, Void::Result::Error>
|
||||
uninstall_prefix(const std::filesystem::path &prefix) {
|
||||
const auto manifest_path = prefix / ".vbs-install-manifest.json";
|
||||
auto text = Void::FileSystem::read_file(manifest_path);
|
||||
if (!text) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::not_found,
|
||||
std::format("no VBS install manifest found at '{}'", manifest_path.string()))};
|
||||
}
|
||||
auto parsed = Void::Json::Strict::parse(*text);
|
||||
if (!parsed) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"corrupt VBS install manifest")};
|
||||
}
|
||||
const auto *root = std::get_if<Void::Json::Strict::Value::Object>(&parsed->value);
|
||||
if (!root) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"invalid VBS install manifest")};
|
||||
}
|
||||
|
||||
std::size_t removed = 0;
|
||||
std::error_code ec;
|
||||
const auto canon_prefix = std::filesystem::weakly_canonical(prefix, ec);
|
||||
const auto fit = root->find("files");
|
||||
if (fit != root->end()) {
|
||||
if (const auto *arr = std::get_if<Void::Json::Strict::Value::Array>(&fit->second.value)) {
|
||||
for (const auto &v : *arr) {
|
||||
if (const auto *s = std::get_if<std::string>(&v.value)) {
|
||||
const std::filesystem::path rel{*s};
|
||||
if (!is_safe_relative_dest(rel)) {
|
||||
continue;
|
||||
}
|
||||
const auto target = (canon_prefix / rel).lexically_normal();
|
||||
if (Platform::path_is_within(canon_prefix, target) &&
|
||||
std::filesystem::is_regular_file(target, ec)) {
|
||||
std::filesystem::remove(target, ec);
|
||||
if (!ec) {
|
||||
++removed;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
std::filesystem::remove(manifest_path, ec);
|
||||
return removed;
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Install
|
||||
+1447
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,428 @@
|
||||
#include <Void/Build/Modules/ModuleScanner.hpp>
|
||||
|
||||
#include <Void/Algorithms/Graph.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/Data/StrictJson.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <set>
|
||||
|
||||
namespace Void::Build::Modules {
|
||||
namespace {
|
||||
|
||||
using JsonVal = Void::Json::Strict::Value;
|
||||
|
||||
Void::Result::Error make_error(std::string msg) {
|
||||
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
std::move(msg));
|
||||
}
|
||||
|
||||
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::string get_str(const JsonVal::Object &obj, const std::string &k) {
|
||||
const auto *v = find_key(obj, k);
|
||||
if (!v) {
|
||||
return {};
|
||||
}
|
||||
const auto *s = std::get_if<std::string>(&v->value);
|
||||
return s ? *s : std::string{};
|
||||
}
|
||||
|
||||
std::string sanitize_module_filename(std::string_view logical_name) {
|
||||
std::string out;
|
||||
out.reserve(logical_name.size());
|
||||
for (const char c : logical_name) {
|
||||
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
||||
c == '_' || c == '-' || c == '.') {
|
||||
out.push_back(c);
|
||||
} else {
|
||||
out += "__";
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string std_flag(CxxStandard standard) {
|
||||
switch (standard) {
|
||||
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";
|
||||
case CxxStandard::Default:
|
||||
return "-std=c++20";
|
||||
}
|
||||
return "-std=c++20";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<ModuleScanUnit, Void::Result::Error>
|
||||
parse_p1689_json(std::string_view json_text, const std::filesystem::path &source_file) {
|
||||
auto parsed = Void::Json::Strict::parse(json_text);
|
||||
if (!parsed) {
|
||||
return std::unexpected{make_error(
|
||||
std::format("failed parsing P1689 module scan JSON for '{}'", source_file.string()))};
|
||||
}
|
||||
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
|
||||
if (!root) {
|
||||
return std::unexpected{make_error("P1689 JSON root must be an object")};
|
||||
}
|
||||
const auto *ver_v = find_key(*root, "version");
|
||||
const auto *ver = ver_v ? std::get_if<std::int64_t>(&ver_v->value) : nullptr;
|
||||
if (!ver || (*ver != 0 && *ver != 1)) {
|
||||
return std::unexpected{make_error("unsupported P1689 JSON version (expected 0 or 1)")};
|
||||
}
|
||||
|
||||
ModuleScanUnit unit;
|
||||
unit.source_file = source_file;
|
||||
|
||||
if (const auto *rules_v = find_key(*root, "rules")) {
|
||||
if (const auto *rules = std::get_if<JsonVal::Array>(&rules_v->value);
|
||||
rules && !rules->empty()) {
|
||||
if (const auto *r0 = std::get_if<JsonVal::Object>(&rules->front().value)) {
|
||||
if (const auto *prov_v = find_key(*r0, "provides")) {
|
||||
if (const auto *parr = std::get_if<JsonVal::Array>(&prov_v->value)) {
|
||||
for (const auto &pv : *parr) {
|
||||
if (const auto *po = std::get_if<JsonVal::Object>(&pv.value)) {
|
||||
const auto name = get_str(*po, "logical-name");
|
||||
if (!name.empty()) {
|
||||
unit.provides.push_back(name);
|
||||
}
|
||||
if (const auto *is_iface = find_key(*po, "is-interface")) {
|
||||
if (const auto *b = std::get_if<bool>(&is_iface->value);
|
||||
b && *b) {
|
||||
unit.is_interface = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (const auto *req_v = find_key(*r0, "requires")) {
|
||||
if (const auto *rarr = std::get_if<JsonVal::Array>(&req_v->value)) {
|
||||
for (const auto &rv : *rarr) {
|
||||
if (const auto *ro = std::get_if<JsonVal::Object>(&rv.value)) {
|
||||
const auto name = get_str(*ro, "logical-name");
|
||||
if (!name.empty()) {
|
||||
unit.required_modules.push_back(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return unit;
|
||||
}
|
||||
|
||||
Void::Result::Result<ModuleScanUnit, Void::Result::Error>
|
||||
scan_translation_unit(const Toolchain::ToolchainCapabilities &toolchain,
|
||||
const std::filesystem::path &source_file,
|
||||
const std::filesystem::path &scratch_dir,
|
||||
const std::vector<std::pair<std::filesystem::path, bool>> &include_dirs,
|
||||
const std::vector<std::string> &defines,
|
||||
const std::vector<std::string> &compile_options, CxxStandard standard) {
|
||||
if (!toolchain.supports_p1689_scan) {
|
||||
return std::unexpected{make_error(
|
||||
std::format("toolchain '{}' does not support P1689 module dependency scanning",
|
||||
toolchain.cxx_compiler.string()))};
|
||||
}
|
||||
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(scratch_dir, ec);
|
||||
const std::string tag = Util::sha256_hex(source_file.string()).substr(0, 12);
|
||||
|
||||
if (toolchain.family == CompilerFamily::Gcc) {
|
||||
const auto ddi_path = scratch_dir / (tag + ".ddi");
|
||||
std::filesystem::remove(ddi_path, ec);
|
||||
|
||||
Platform::ProcessRequest req;
|
||||
req.executable = toolchain.cxx_compiler;
|
||||
req.arguments = {std_flag(standard),
|
||||
"-fmodules",
|
||||
"-E",
|
||||
"-M",
|
||||
"-x",
|
||||
"c++",
|
||||
"-fdeps-format=p1689r5",
|
||||
"-fdeps-file=" + ddi_path.string(),
|
||||
"-fdeps-target=" + (tag + ".o"),
|
||||
"-o",
|
||||
"/dev/null"};
|
||||
for (const auto &[inc, is_sys] : include_dirs) {
|
||||
req.arguments.push_back(is_sys ? "-isystem" : "-I");
|
||||
req.arguments.push_back(inc.string());
|
||||
}
|
||||
for (const auto &def : defines) {
|
||||
req.arguments.push_back("-D" + def);
|
||||
}
|
||||
for (const auto &opt : compile_options) {
|
||||
req.arguments.push_back(opt);
|
||||
}
|
||||
req.arguments.push_back(source_file.string());
|
||||
req.timeout = std::chrono::seconds{30};
|
||||
|
||||
auto proc = Platform::run_supervised(req);
|
||||
if (!proc || !proc->succeeded()) {
|
||||
return std::unexpected{make_error(
|
||||
std::format("GCC P1689 module scan failed for '{}':\n{}", source_file.string(),
|
||||
proc ? proc->stderr_data : proc.error().message()))};
|
||||
}
|
||||
auto ddi_text = Void::FileSystem::read_file(ddi_path);
|
||||
if (!ddi_text) {
|
||||
return std::unexpected{make_error("GCC P1689 scan did not produce .ddi file")};
|
||||
}
|
||||
return parse_p1689_json(*ddi_text, source_file);
|
||||
}
|
||||
|
||||
// Clang: use clang-scan-deps --format=p1689 -- clang++ ...
|
||||
if (!toolchain.module_scanner) {
|
||||
return std::unexpected{make_error("Clang module scanning requires clang-scan-deps")};
|
||||
}
|
||||
Platform::ProcessRequest req;
|
||||
req.executable = *toolchain.module_scanner;
|
||||
req.arguments = {"--format=p1689",
|
||||
"--",
|
||||
toolchain.cxx_compiler.string(),
|
||||
std_flag(standard),
|
||||
"-x",
|
||||
"c++",
|
||||
"-c",
|
||||
source_file.string(),
|
||||
"-o",
|
||||
(scratch_dir / (tag + ".o")).string()};
|
||||
for (const auto &[inc, is_sys] : include_dirs) {
|
||||
req.arguments.push_back(is_sys ? "-isystem" : "-I");
|
||||
req.arguments.push_back(inc.string());
|
||||
}
|
||||
for (const auto &def : defines) {
|
||||
req.arguments.push_back("-D" + def);
|
||||
}
|
||||
for (const auto &opt : compile_options) {
|
||||
req.arguments.push_back(opt);
|
||||
}
|
||||
req.timeout = std::chrono::seconds{30};
|
||||
|
||||
auto proc = Platform::run_supervised(req);
|
||||
if (!proc || !proc->succeeded()) {
|
||||
return std::unexpected{make_error(
|
||||
std::format("clang-scan-deps P1689 scan failed for '{}':\n{}", source_file.string(),
|
||||
proc ? proc->stderr_data : proc.error().message()))};
|
||||
}
|
||||
return parse_p1689_json(proc->stdout_data, source_file);
|
||||
}
|
||||
|
||||
Void::Result::Result<CollatedModulePlan, Void::Result::Error>
|
||||
collate_modules(const std::vector<ModuleScanUnit> &units, const std::filesystem::path &bmi_root,
|
||||
const std::string &context_isolation_key, std::string_view bmi_extension) {
|
||||
// 1. Index module providers and reject duplicates immediately.
|
||||
std::map<std::string, std::size_t, std::less<>> provider_by_name;
|
||||
for (std::size_t i = 0; i < units.size(); ++i) {
|
||||
for (const auto &mod : units[i].provides) {
|
||||
const auto [it, inserted] = provider_by_name.emplace(mod, i);
|
||||
if (!inserted) {
|
||||
return std::unexpected{make_error(std::format(
|
||||
"duplicate module provider for '{}': defined in both '{}' and '{}'", mod,
|
||||
units[it->second].source_file.string(), units[i].source_file.string()))};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Validate every required module has a provider and build directed dependency graph
|
||||
// (edge dep -> importer so providers precede importers in topological order).
|
||||
std::vector<std::vector<std::size_t>> adj(units.size());
|
||||
for (std::size_t i = 0; i < units.size(); ++i) {
|
||||
for (const auto &req_mod : units[i].required_modules) {
|
||||
const auto it = provider_by_name.find(req_mod);
|
||||
if (it == provider_by_name.end()) {
|
||||
return std::unexpected{
|
||||
make_error(std::format("missing module provider for '{}' imported by '{}'",
|
||||
req_mod, units[i].source_file.string()))};
|
||||
}
|
||||
const std::size_t dep = it->second;
|
||||
if (dep == i) {
|
||||
return std::unexpected{
|
||||
make_error(std::format("module '{}' cannot import itself", req_mod))};
|
||||
}
|
||||
if (!std::ranges::contains(adj[dep], i)) {
|
||||
adj[dep].push_back(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Topological sort via Void::Algorithms::topological_order with cycle witness diagnostics.
|
||||
const Void::Algorithms::AdjacencyView view{adj};
|
||||
auto topo = Void::Algorithms::topological_order(view);
|
||||
if (!topo) {
|
||||
std::string chain;
|
||||
const auto &cycle = topo.error().cycle;
|
||||
for (auto it = cycle.rbegin(); it != cycle.rend(); ++it) {
|
||||
if (!chain.empty()) {
|
||||
chain += " -> ";
|
||||
}
|
||||
const auto idx = *it;
|
||||
chain += units[idx].provides.empty() ? units[idx].source_file.filename().string()
|
||||
: units[idx].provides.front();
|
||||
}
|
||||
return std::unexpected{make_error(
|
||||
chain.empty() ? std::format("module import cycle detected: {}", topo.error().message)
|
||||
: std::format("module import cycle detected: {}", chain))};
|
||||
}
|
||||
|
||||
// 4. Assign isolated per-profile/compiler BMI paths and emit GCC module-mapper files.
|
||||
const std::string ctx_short = Util::sha256_hex(context_isolation_key).substr(0, 12);
|
||||
const auto isolated_bmi_dir = bmi_root / ctx_short;
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(isolated_bmi_dir, ec);
|
||||
|
||||
CollatedModulePlan plan;
|
||||
for (const std::size_t idx : topo->order) {
|
||||
const auto &u = units[idx];
|
||||
CollatedModuleNode node;
|
||||
node.source_file = u.source_file;
|
||||
node.provides = u.provides;
|
||||
node.required_modules = u.required_modules;
|
||||
|
||||
if (!u.provides.empty()) {
|
||||
const std::string fname =
|
||||
sanitize_module_filename(u.provides.front()) + std::string{bmi_extension};
|
||||
node.bmi_output_path = isolated_bmi_dir / fname;
|
||||
for (const auto &mod : u.provides) {
|
||||
plan.module_to_bmi[mod] = node.bmi_output_path;
|
||||
}
|
||||
}
|
||||
|
||||
// Build GCC module-mapper file mapping all required + provided modules.
|
||||
std::string mapper;
|
||||
for (const auto &mod : u.provides) {
|
||||
mapper += mod + " " + node.bmi_output_path.string() + "\n";
|
||||
}
|
||||
for (const auto &req_mod : u.required_modules) {
|
||||
const auto &bmi = plan.module_to_bmi.at(req_mod);
|
||||
node.imported_bmis.emplace_back(req_mod, bmi);
|
||||
mapper += req_mod + " " + bmi.string() + "\n";
|
||||
}
|
||||
if (!mapper.empty()) {
|
||||
const std::string mtag = Util::sha256_hex(u.source_file.string()).substr(0, 12);
|
||||
node.module_mapper_path = isolated_bmi_dir / (mtag + ".modmap");
|
||||
auto wrote = Platform::atomic_write_file(node.module_mapper_path, mapper, false);
|
||||
if (!wrote) {
|
||||
return std::unexpected{wrote.error()};
|
||||
}
|
||||
}
|
||||
plan.ordered_units.push_back(std::move(node));
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
Void::Result::Result<Toolchain::LoweredCommand, Void::Result::Error>
|
||||
lower_header_unit_command(const Toolchain::ToolchainCapabilities &toolchain,
|
||||
const std::filesystem::path &header_path,
|
||||
const std::filesystem::path &bmi_output,
|
||||
const std::vector<std::pair<std::filesystem::path, bool>> &include_dirs,
|
||||
const std::vector<std::string> &defines,
|
||||
const std::vector<std::string> &compile_options, CxxStandard standard) {
|
||||
Toolchain::LoweredCommand cmd;
|
||||
cmd.executable = toolchain.cxx_compiler;
|
||||
cmd.arguments.push_back(std_flag(standard));
|
||||
if (toolchain.family == CompilerFamily::Gcc) {
|
||||
const auto mapper_path = std::filesystem::path{bmi_output.string() + ".modmap"};
|
||||
const std::string mapper_content = header_path.string() + " " + bmi_output.string() + "\n";
|
||||
if (auto w = Platform::atomic_write_file(mapper_path, mapper_content, false); !w) {
|
||||
return std::unexpected{w.error()};
|
||||
}
|
||||
cmd.arguments.push_back("-fmodules");
|
||||
cmd.arguments.push_back("-fmodule-header=user");
|
||||
cmd.arguments.push_back("-fmodule-mapper=" + mapper_path.string());
|
||||
cmd.arguments.push_back("-x");
|
||||
cmd.arguments.push_back("c++-user-header");
|
||||
cmd.arguments.push_back("-c");
|
||||
} else {
|
||||
cmd.arguments.push_back("-x");
|
||||
cmd.arguments.push_back("c++-user-header");
|
||||
cmd.arguments.push_back("--precompile");
|
||||
}
|
||||
for (const auto &[inc, is_sys] : include_dirs) {
|
||||
cmd.arguments.push_back(is_sys ? "-isystem" : "-I");
|
||||
cmd.arguments.push_back(inc.string());
|
||||
}
|
||||
for (const auto &def : defines) {
|
||||
cmd.arguments.push_back("-D" + def);
|
||||
}
|
||||
for (const auto &opt : compile_options) {
|
||||
cmd.arguments.push_back(opt);
|
||||
}
|
||||
cmd.arguments.push_back(header_path.string());
|
||||
if (toolchain.family == CompilerFamily::Clang) {
|
||||
cmd.arguments.push_back("-o");
|
||||
cmd.arguments.push_back(bmi_output.string());
|
||||
}
|
||||
cmd.environment["SOURCE_DATE_EPOCH"] = "0";
|
||||
cmd.environment["TZ"] = "UTC";
|
||||
cmd.environment["LC_ALL"] = "C";
|
||||
return cmd;
|
||||
}
|
||||
|
||||
Void::Result::Result<UnityBatchResult, Void::Result::Error>
|
||||
generate_unity_batches(const std::string &target_name,
|
||||
const std::vector<std::filesystem::path> &sources,
|
||||
const std::vector<std::filesystem::path> &excluded_sources,
|
||||
std::size_t batch_size, const std::filesystem::path &unity_dir) {
|
||||
if (batch_size == 0) {
|
||||
return std::unexpected{make_error("unity batch size must be positive")};
|
||||
}
|
||||
|
||||
std::set<std::filesystem::path> excluded;
|
||||
for (const auto &ex : excluded_sources) {
|
||||
excluded.insert(ex.lexically_normal());
|
||||
}
|
||||
|
||||
std::vector<std::filesystem::path> batchable;
|
||||
UnityBatchResult result;
|
||||
for (const auto &src : sources) {
|
||||
const auto norm = src.lexically_normal();
|
||||
const auto ext = norm.extension().string();
|
||||
// Exclude module interface/partition extensions and explicitly excluded files from unity!
|
||||
if (excluded.contains(norm) || ext == ".cppm" || ext == ".ixx" || ext == ".ccm") {
|
||||
result.standalone_files.push_back(norm);
|
||||
} else {
|
||||
batchable.push_back(norm);
|
||||
}
|
||||
}
|
||||
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(unity_dir, ec);
|
||||
|
||||
std::size_t batch_idx = 0;
|
||||
for (std::size_t i = 0; i < batchable.size(); i += batch_size) {
|
||||
std::string content = "// Auto-generated deterministic unity batch by VoidBuildSystem\n";
|
||||
const std::size_t end = std::min(batchable.size(), i + batch_size);
|
||||
for (std::size_t j = i; j < end; ++j) {
|
||||
content += "#include " + Util::json_quote(batchable[j].string()) + "\n";
|
||||
}
|
||||
const auto batch_file =
|
||||
unity_dir / std::format("{}_unity_{}.cpp", target_name, batch_idx++);
|
||||
auto wrote = Platform::atomic_write_file(batch_file, content, false);
|
||||
if (!wrote) {
|
||||
return std::unexpected{wrote.error()};
|
||||
}
|
||||
result.generated_unity_files.push_back(batch_file);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Modules
|
||||
@@ -0,0 +1,581 @@
|
||||
#include <Void/Build/Package/Archive.hpp>
|
||||
|
||||
#include <Void/Build/Platform/FileOps.hpp>
|
||||
#include <Void/Build/Util/Sha256.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <format>
|
||||
#include <set>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace Void::Build::Package {
|
||||
namespace {
|
||||
|
||||
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg, int err = 0) {
|
||||
return Void::System::make_system_error(code, std::move(msg), err);
|
||||
}
|
||||
|
||||
bool is_safe_archive_path(std::string_view raw) {
|
||||
if (raw.empty() || raw.front() == '/' || raw.find('\\') != std::string_view::npos) {
|
||||
return false;
|
||||
}
|
||||
for (const unsigned char c : raw) {
|
||||
if (c < 0x20 || c == 0x7f) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
std::size_t pos = 0;
|
||||
while (pos <= raw.size()) {
|
||||
const auto slash = raw.find('/', pos);
|
||||
const auto seg =
|
||||
raw.substr(pos, slash == std::string_view::npos ? std::string_view::npos : slash - pos);
|
||||
if (seg == "..") {
|
||||
return false;
|
||||
}
|
||||
if (slash == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
pos = slash + 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void write_octal(char *dst, std::size_t width, std::uint64_t val) {
|
||||
std::memset(dst, '0', width - 1);
|
||||
dst[width - 1] = '\0';
|
||||
for (std::size_t i = width - 1; i > 0; --i) {
|
||||
dst[i - 1] = static_cast<char>('0' + (val & 7u));
|
||||
val >>= 3;
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<std::uint64_t> parse_octal(const char *src, std::size_t width) {
|
||||
std::size_t i = 0;
|
||||
while (i < width && (src[i] == ' ' || src[i] == '\0')) {
|
||||
++i;
|
||||
}
|
||||
std::uint64_t val = 0;
|
||||
bool any = false;
|
||||
for (; i < width; ++i) {
|
||||
if (src[i] == '\0' || src[i] == ' ') {
|
||||
break;
|
||||
}
|
||||
if (src[i] < '0' || src[i] > '7') {
|
||||
return std::nullopt;
|
||||
}
|
||||
any = true;
|
||||
val = (val << 3) | static_cast<std::uint64_t>(src[i] - '0');
|
||||
}
|
||||
return any ? std::optional<std::uint64_t>{val} : std::optional<std::uint64_t>{0};
|
||||
}
|
||||
|
||||
void finalize_tar_header(std::array<char, 512> &hdr, std::string_view name, std::uint32_t mode,
|
||||
std::uint64_t size, std::int64_t mtime, char typeflag) {
|
||||
hdr.fill('\0');
|
||||
if (name.size() <= 100) {
|
||||
std::memcpy(hdr.data(), name.data(), name.size());
|
||||
} else {
|
||||
// Split into USTAR prefix (155) + name (100) at a slash boundary.
|
||||
const auto split = name.rfind('/', 154);
|
||||
if (split != std::string_view::npos && name.size() - split - 1 <= 100) {
|
||||
std::memcpy(hdr.data() + 345, name.data(), split);
|
||||
std::memcpy(hdr.data(), name.data() + split + 1, name.size() - split - 1);
|
||||
} else {
|
||||
std::memcpy(hdr.data(), name.data(), std::min<std::size_t>(name.size(), 100));
|
||||
}
|
||||
}
|
||||
write_octal(hdr.data() + 100, 8, mode & 0777u);
|
||||
write_octal(hdr.data() + 108, 8, 0); // canonical uid=0
|
||||
write_octal(hdr.data() + 116, 8, 0); // canonical gid=0
|
||||
write_octal(hdr.data() + 124, 12, size);
|
||||
write_octal(hdr.data() + 136, 12, mtime >= 0 ? static_cast<std::uint64_t>(mtime) : 0u);
|
||||
std::memset(hdr.data() + 148, ' ', 8);
|
||||
hdr[156] = typeflag;
|
||||
std::memcpy(hdr.data() + 257, "ustar", 6);
|
||||
hdr[263] = '0';
|
||||
hdr[264] = '0';
|
||||
|
||||
std::uint64_t chksum = 0;
|
||||
for (const char c : hdr) {
|
||||
chksum += static_cast<unsigned char>(c);
|
||||
}
|
||||
write_octal(hdr.data() + 148, 7, chksum);
|
||||
hdr[155] = ' ';
|
||||
}
|
||||
|
||||
std::string build_pax_path_record(std::string_view path) {
|
||||
// Format: "<len> path=<path>\n"
|
||||
std::string body = " path=" + std::string{path} + "\n";
|
||||
std::size_t total = body.size() + 1;
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
const auto digits = std::to_string(total).size();
|
||||
if (digits + body.size() == total) {
|
||||
break;
|
||||
}
|
||||
total = digits + body.size();
|
||||
}
|
||||
return std::to_string(total) + body;
|
||||
}
|
||||
|
||||
bool write_all(int fd, const void *data, std::size_t len) {
|
||||
const auto *p = static_cast<const char *>(data);
|
||||
std::size_t off = 0;
|
||||
while (off < len) {
|
||||
const ssize_t n = ::write(fd, p + off, len - off);
|
||||
if (n < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
off += static_cast<std::size_t>(n);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool read_exact(int fd, void *data, std::size_t len, std::size_t &got_out) {
|
||||
auto *p = static_cast<char *>(data);
|
||||
got_out = 0;
|
||||
while (got_out < len) {
|
||||
const ssize_t n = ::read(fd, p + got_out, len - got_out);
|
||||
if (n < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (n == 0) {
|
||||
return true;
|
||||
}
|
||||
got_out += static_cast<std::size_t>(n);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool is_zero_block(const std::array<char, 512> &blk) {
|
||||
return std::ranges::all_of(blk, [](char c) { return c == '\0'; });
|
||||
}
|
||||
|
||||
bool is_excluded_source_pkg_part(std::string_view part) {
|
||||
if (part == ".git" || part == ".vbs" || part == "build" || part == ".serena" ||
|
||||
part == ".cache" || part == "keys" || part == "WG.conf") {
|
||||
return true;
|
||||
}
|
||||
if (part == ".env" || (part.starts_with(".env.") && part != ".env.example")) {
|
||||
return true;
|
||||
}
|
||||
if (part.ends_with(".pem") || part.ends_with(".key")) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<std::string, Void::Result::Error>
|
||||
create_deterministic_tar(const std::filesystem::path &output_tar,
|
||||
std::vector<ArchiveEntrySpec> entries,
|
||||
std::int64_t reproducibility_epoch) {
|
||||
std::ranges::sort(entries, [](const ArchiveEntrySpec &a, const ArchiveEntrySpec &b) {
|
||||
return a.archive_path < b.archive_path;
|
||||
});
|
||||
|
||||
std::set<std::string> seen_names;
|
||||
for (const auto &e : entries) {
|
||||
if (!is_safe_archive_path(e.archive_path)) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("create_deterministic_tar: unsafe archive path '{}'", e.archive_path))};
|
||||
}
|
||||
if (!seen_names.insert(e.archive_path).second) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("create_deterministic_tar: duplicate archive path '{}'",
|
||||
e.archive_path))};
|
||||
}
|
||||
}
|
||||
|
||||
std::error_code ec;
|
||||
if (output_tar.has_parent_path()) {
|
||||
std::filesystem::create_directories(output_tar.parent_path(), ec);
|
||||
}
|
||||
const auto temp_tar =
|
||||
output_tar.parent_path() / (output_tar.filename().string() + ".stage_" +
|
||||
std::to_string(static_cast<long long>(::getpid())));
|
||||
const int fd = ::open(temp_tar.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
|
||||
if (fd < 0) {
|
||||
return std::unexpected{make_error(Void::System::map_errno_to_system_code(errno),
|
||||
"create_deterministic_tar: cannot open temp file",
|
||||
errno)};
|
||||
}
|
||||
Void::System::OwnedFd guard{fd};
|
||||
auto fail_cleanup = [&] {
|
||||
(void)guard.close();
|
||||
std::filesystem::remove(temp_tar, ec);
|
||||
};
|
||||
|
||||
Util::Sha256Hasher hasher;
|
||||
auto write_hashed = [&](const void *buf, std::size_t n) -> bool {
|
||||
hasher.update(std::span<const std::uint8_t>{static_cast<const std::uint8_t *>(buf), n});
|
||||
return write_all(fd, buf, n);
|
||||
};
|
||||
|
||||
std::array<char, 512> zero_pad{};
|
||||
std::array<char, 512> hdr{};
|
||||
std::array<char, 65536> copy_buf{};
|
||||
|
||||
for (const auto &entry : entries) {
|
||||
auto meta = Platform::stat_lstat(entry.source_file);
|
||||
if (!meta || !meta->exists || !meta->is_regular) {
|
||||
fail_cleanup();
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::not_found,
|
||||
std::format("create_deterministic_tar: source '{}' is not a regular file",
|
||||
entry.source_file.string()))};
|
||||
}
|
||||
|
||||
// Use PAX extended header whenever path > 100 chars to guarantee lossless long paths.
|
||||
if (entry.archive_path.size() > 100) {
|
||||
const std::string pax = build_pax_path_record(entry.archive_path);
|
||||
finalize_tar_header(hdr, "PaxHeader/" + entry.archive_path.substr(0, 60), 0644,
|
||||
pax.size(), reproducibility_epoch, 'x');
|
||||
if (!write_hashed(hdr.data(), hdr.size()) || !write_hashed(pax.data(), pax.size())) {
|
||||
fail_cleanup();
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error, "tar write failed")};
|
||||
}
|
||||
const std::size_t rem = pax.size() % 512;
|
||||
if (rem != 0 && !write_hashed(zero_pad.data(), 512 - rem)) {
|
||||
fail_cleanup();
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error, "tar pad write failed")};
|
||||
}
|
||||
}
|
||||
|
||||
finalize_tar_header(hdr, entry.archive_path, entry.mode, meta->size, reproducibility_epoch,
|
||||
'0');
|
||||
if (!write_hashed(hdr.data(), hdr.size())) {
|
||||
fail_cleanup();
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error, "tar header write failed")};
|
||||
}
|
||||
|
||||
const int sfd = ::open(entry.source_file.c_str(), O_RDONLY | O_CLOEXEC);
|
||||
if (sfd < 0) {
|
||||
fail_cleanup();
|
||||
return std::unexpected{make_error(Void::System::map_errno_to_system_code(errno),
|
||||
"cannot open source file for tar", errno)};
|
||||
}
|
||||
Void::System::OwnedFd sguard{sfd};
|
||||
std::uint64_t remaining = meta->size;
|
||||
while (remaining > 0) {
|
||||
const std::size_t chunk =
|
||||
static_cast<std::size_t>(std::min<std::uint64_t>(remaining, copy_buf.size()));
|
||||
std::size_t got = 0;
|
||||
if (!read_exact(sfd, copy_buf.data(), chunk, got) || got != chunk) {
|
||||
fail_cleanup();
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"short read while archiving file")};
|
||||
}
|
||||
if (!write_hashed(copy_buf.data(), got)) {
|
||||
fail_cleanup();
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error, "tar body write failed")};
|
||||
}
|
||||
remaining -= got;
|
||||
}
|
||||
const std::size_t pad = static_cast<std::size_t>((512 - (meta->size % 512)) % 512);
|
||||
if (pad > 0 && !write_hashed(zero_pad.data(), pad)) {
|
||||
fail_cleanup();
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error, "tar padding write failed")};
|
||||
}
|
||||
}
|
||||
|
||||
// Two 512-byte zero blocks terminate a valid tar archive.
|
||||
if (!write_hashed(zero_pad.data(), 512) || !write_hashed(zero_pad.data(), 512)) {
|
||||
fail_cleanup();
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error, "tar trailer write failed")};
|
||||
}
|
||||
|
||||
if (const auto closed = guard.close(); !closed) {
|
||||
std::filesystem::remove(temp_tar, ec);
|
||||
return std::unexpected{closed.error()};
|
||||
}
|
||||
std::filesystem::rename(temp_tar, output_tar, ec);
|
||||
if (ec) {
|
||||
std::filesystem::remove(temp_tar, ec);
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error, "tar atomic publish failed")};
|
||||
}
|
||||
return hasher.finalize_hex();
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string, Void::Result::Error>
|
||||
create_source_package(const std::filesystem::path &project_root,
|
||||
const std::filesystem::path &output_tar, std::int64_t reproducibility_epoch) {
|
||||
std::error_code ec;
|
||||
const auto canon = std::filesystem::weakly_canonical(project_root, ec);
|
||||
if (ec || !std::filesystem::is_directory(canon)) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::not_found, "project root does not exist")};
|
||||
}
|
||||
|
||||
std::vector<ArchiveEntrySpec> entries;
|
||||
std::filesystem::recursive_directory_iterator it{
|
||||
canon, std::filesystem::directory_options::skip_permission_denied, ec};
|
||||
for (; !ec && it != std::filesystem::recursive_directory_iterator{}; it.increment(ec)) {
|
||||
const auto rel = it->path().lexically_relative(canon);
|
||||
bool skip = false;
|
||||
for (const auto &part : rel) {
|
||||
if (is_excluded_source_pkg_part(part.string())) {
|
||||
skip = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (skip) {
|
||||
if (it->is_directory(ec)) {
|
||||
it.disable_recursion_pending();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (it->is_regular_file(ec)) {
|
||||
auto meta = Platform::stat_lstat(it->path());
|
||||
const std::uint32_t mode = (meta && (meta->mode & 0111u)) ? 0755u : 0644u;
|
||||
entries.push_back({rel.lexically_normal().generic_string(), it->path(), mode});
|
||||
}
|
||||
}
|
||||
return create_deterministic_tar(output_tar, std::move(entries), reproducibility_epoch);
|
||||
}
|
||||
|
||||
Void::Result::Result<ArchiveExtractionStats, Void::Result::Error>
|
||||
extract_safe_tar(const std::filesystem::path &tar_path,
|
||||
const std::filesystem::path &destination_dir, const ArchiveLimits &limits) {
|
||||
const int fd = ::open(tar_path.c_str(), O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::map_errno_to_system_code(errno),
|
||||
std::format("extract_safe_tar: cannot open '{}'", tar_path.string()), errno)};
|
||||
}
|
||||
Void::System::OwnedFd guard{fd};
|
||||
|
||||
std::error_code ec;
|
||||
const auto parent = destination_dir.parent_path().empty() ? std::filesystem::path{"."}
|
||||
: destination_dir.parent_path();
|
||||
std::filesystem::create_directories(parent, ec);
|
||||
const auto stage_dir = parent / (destination_dir.filename().string() + ".extract_" +
|
||||
std::to_string(static_cast<long long>(::getpid())));
|
||||
std::filesystem::remove_all(stage_dir, ec);
|
||||
std::filesystem::create_directories(stage_dir, ec);
|
||||
|
||||
auto abort_extract = [&] { std::filesystem::remove_all(stage_dir, ec); };
|
||||
|
||||
ArchiveExtractionStats stats;
|
||||
std::set<std::string> seen_paths;
|
||||
std::optional<std::string> next_pax_path;
|
||||
std::array<char, 512> hdr{};
|
||||
std::array<char, 65536> buf{};
|
||||
|
||||
for (;;) {
|
||||
std::size_t got = 0;
|
||||
if (!read_exact(fd, hdr.data(), 512, got)) {
|
||||
abort_extract();
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error, "tar read error")};
|
||||
}
|
||||
if (got == 0 || (got == 512 && is_zero_block(hdr))) {
|
||||
break;
|
||||
}
|
||||
if (got != 512) {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"truncated tar header")};
|
||||
}
|
||||
|
||||
// Verify header checksum.
|
||||
const auto expected_sum = parse_octal(hdr.data() + 148, 8);
|
||||
if (!expected_sum) {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"malformed tar checksum")};
|
||||
}
|
||||
std::uint64_t actual_sum = 0;
|
||||
for (std::size_t i = 0; i < 512; ++i) {
|
||||
actual_sum += (i >= 148 && i < 156) ? static_cast<unsigned char>(' ')
|
||||
: static_cast<unsigned char>(hdr[i]);
|
||||
}
|
||||
if (actual_sum != *expected_sum) {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"tar header checksum mismatch")};
|
||||
}
|
||||
|
||||
const auto size_opt = parse_octal(hdr.data() + 124, 12);
|
||||
const auto mode_opt = parse_octal(hdr.data() + 100, 8);
|
||||
if (!size_opt || !mode_opt) {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"malformed tar size or mode")};
|
||||
}
|
||||
const std::uint64_t entry_size = *size_opt;
|
||||
const std::uint32_t entry_mode = static_cast<std::uint32_t>(*mode_opt & 0777u);
|
||||
const char typeflag = hdr[156];
|
||||
|
||||
// Handle PAX extended header ('x') for long paths.
|
||||
if (typeflag == 'x') {
|
||||
if (entry_size > 65536) {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::limit_exceeded,
|
||||
"PAX header exceeds limit")};
|
||||
}
|
||||
std::string pax_data(static_cast<std::size_t>(entry_size), '\0');
|
||||
if (!read_exact(fd, pax_data.data(), pax_data.size(), got) || got != pax_data.size()) {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"truncated PAX body")};
|
||||
}
|
||||
const std::size_t pad = static_cast<std::size_t>((512 - (entry_size % 512)) % 512);
|
||||
if (pad > 0 && (!read_exact(fd, buf.data(), pad, got) || got != pad)) {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"truncated PAX padding")};
|
||||
}
|
||||
const auto path_pos = pax_data.find(" path=");
|
||||
if (path_pos != std::string::npos) {
|
||||
const auto val_start = path_pos + 6;
|
||||
const auto nl = pax_data.find('\n', val_start);
|
||||
next_pax_path = pax_data.substr(
|
||||
val_start, nl == std::string::npos ? std::string::npos : nl - val_start);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Reject symlinks ('2'), hardlinks ('1'), devices ('3'/'4'), FIFOs ('6'), etc.!
|
||||
if (typeflag != '0' && typeflag != '\0' && typeflag != '5') {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::permission_denied,
|
||||
std::format("archive contains disallowed non-regular entry type '{}'", typeflag))};
|
||||
}
|
||||
|
||||
std::string entry_name;
|
||||
if (next_pax_path) {
|
||||
entry_name = std::move(*next_pax_path);
|
||||
next_pax_path.reset();
|
||||
} else {
|
||||
const std::string name_part(hdr.data(), ::strnlen(hdr.data(), 100));
|
||||
const std::string prefix_part(hdr.data() + 345, ::strnlen(hdr.data() + 345, 155));
|
||||
entry_name = prefix_part.empty() ? name_part : (prefix_part + "/" + name_part);
|
||||
}
|
||||
while (entry_name.starts_with("./")) {
|
||||
entry_name.erase(0, 2);
|
||||
}
|
||||
while (!entry_name.empty() && entry_name.back() == '/') {
|
||||
entry_name.pop_back();
|
||||
}
|
||||
if (entry_name.empty() && typeflag == '5') {
|
||||
continue;
|
||||
}
|
||||
if (!is_safe_archive_path(entry_name)) {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::permission_denied,
|
||||
std::format("archive contains unsafe or traversal path '{}'", entry_name))};
|
||||
}
|
||||
|
||||
if (++stats.entries > limits.max_entries) {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::limit_exceeded,
|
||||
"archive entry count exceeds limit")};
|
||||
}
|
||||
if (entry_size > limits.max_file_bytes ||
|
||||
stats.total_bytes + entry_size > limits.max_total_bytes) {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::limit_exceeded,
|
||||
"archive extracted size exceeds limit")};
|
||||
}
|
||||
|
||||
const auto rel_norm = std::filesystem::path{entry_name}.lexically_normal().generic_string();
|
||||
if (!seen_paths.insert(rel_norm).second) {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("archive contains duplicate colliding path '{}'", rel_norm))};
|
||||
}
|
||||
|
||||
const auto dst_path = stage_dir / rel_norm;
|
||||
if (!Platform::path_is_within(stage_dir, dst_path)) {
|
||||
abort_extract();
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::permission_denied,
|
||||
std::format("archive entry '{}' escapes destination", rel_norm))};
|
||||
}
|
||||
|
||||
if (typeflag == '5') {
|
||||
std::filesystem::create_directories(dst_path, ec);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (dst_path.has_parent_path()) {
|
||||
std::filesystem::create_directories(dst_path.parent_path(), ec);
|
||||
}
|
||||
const int out_fd = ::open(dst_path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC,
|
||||
static_cast<mode_t>(entry_mode ? entry_mode : 0644u));
|
||||
if (out_fd < 0) {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(
|
||||
Void::System::map_errno_to_system_code(errno),
|
||||
std::format("extract_safe_tar: failed creating '{}'", dst_path.string()), errno)};
|
||||
}
|
||||
Void::System::OwnedFd out_guard{out_fd};
|
||||
|
||||
std::uint64_t remaining = entry_size;
|
||||
while (remaining > 0) {
|
||||
const std::size_t chunk =
|
||||
static_cast<std::size_t>(std::min<std::uint64_t>(remaining, buf.size()));
|
||||
if (!read_exact(fd, buf.data(), chunk, got) || got != chunk) {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"truncated tar file body")};
|
||||
}
|
||||
if (!write_all(out_fd, buf.data(), got)) {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"failed writing extracted file")};
|
||||
}
|
||||
remaining -= got;
|
||||
}
|
||||
stats.total_bytes += entry_size;
|
||||
stats.extracted_files.push_back(std::filesystem::path{rel_norm});
|
||||
|
||||
const std::size_t pad = static_cast<std::size_t>((512 - (entry_size % 512)) % 512);
|
||||
if (pad > 0 && (!read_exact(fd, buf.data(), pad, got) || got != pad)) {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"truncated tar file padding")};
|
||||
}
|
||||
}
|
||||
|
||||
// Atomic publication into destination_dir.
|
||||
if (std::filesystem::exists(destination_dir, ec)) {
|
||||
std::filesystem::remove_all(destination_dir, ec);
|
||||
}
|
||||
std::filesystem::rename(stage_dir, destination_dir, ec);
|
||||
if (ec) {
|
||||
abort_extract();
|
||||
return std::unexpected{make_error(
|
||||
Void::System::map_errno_to_system_code(ec.value()),
|
||||
std::format("extract_safe_tar: atomic rename to '{}' failed", destination_dir.string()),
|
||||
ec.value())};
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Package
|
||||
@@ -0,0 +1,365 @@
|
||||
#include <Void/Build/Package/Fetch.hpp>
|
||||
|
||||
#include <Void/Build/Platform/FileOps.hpp>
|
||||
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||
#include <Void/Build/Snapshot/Snapshot.hpp>
|
||||
#include <Void/Build/Util/Sha256.hpp>
|
||||
#include <Void/Core/Scope.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
#include <Void/Text/Str.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
|
||||
namespace Void::Build::Package {
|
||||
namespace {
|
||||
|
||||
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
|
||||
return Void::System::make_system_error(code, redact_secrets(msg));
|
||||
}
|
||||
|
||||
std::string sanitize_key(std::string_view text) {
|
||||
std::string out;
|
||||
for (const char c : text) {
|
||||
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
||||
c == '_' || c == '-') {
|
||||
out.push_back(c);
|
||||
} else {
|
||||
out.push_back('_');
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string trim(std::string_view s) { return std::string{Void::Str::trim_right_ascii(s)}; }
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string redact_secrets(std::string_view text) {
|
||||
std::string out{text};
|
||||
// Redact scheme://user:pass@host -> scheme://<redacted>@host
|
||||
std::size_t pos = 0;
|
||||
while ((pos = out.find("://", pos)) != std::string::npos) {
|
||||
const auto after = pos + 3;
|
||||
const auto slash = out.find('/', after);
|
||||
const auto space = out.find_first_of(" \t\r\n\"'", after);
|
||||
const auto bound = std::min(slash, space);
|
||||
const auto at = out.find('@', after);
|
||||
if (at != std::string::npos && at < bound) {
|
||||
out.replace(after, at - after, "<redacted>");
|
||||
pos = after + 10;
|
||||
} else {
|
||||
pos = after;
|
||||
}
|
||||
}
|
||||
// Redact Bearer tokens.
|
||||
pos = 0;
|
||||
while ((pos = out.find("Bearer ", pos)) != std::string::npos) {
|
||||
const auto start = pos + 7;
|
||||
const auto end = out.find_first_of(" \t\r\n\"',;}", start);
|
||||
const auto len = (end == std::string::npos) ? (out.size() - start) : (end - start);
|
||||
out.replace(start, len, "<redacted>");
|
||||
pos = start + 10;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string BinaryCompatibilityKey::compute_key_hash() const {
|
||||
Util::Sha256Hasher h;
|
||||
h.update_length_prefixed("vbs-bin-abi-v1");
|
||||
h.update_length_prefixed(os);
|
||||
h.update_length_prefixed(architecture);
|
||||
h.update_length_prefixed(compiler_family);
|
||||
h.update_length_prefixed(compiler_abi);
|
||||
h.update_length_prefixed(stdlib_abi);
|
||||
h.update_length_prefixed(linkage);
|
||||
h.update_length_prefixed(cpu_features);
|
||||
h.update_length_prefixed(sanitizers_key);
|
||||
h.update_length_prefixed(lto_mode);
|
||||
h.update_length_prefixed(dependency_closure_hash);
|
||||
return h.finalize_hex();
|
||||
}
|
||||
|
||||
bool BinaryCompatibilityKey::matches(const BinaryVariantMeta &candidate) const noexcept {
|
||||
return candidate.os == os && candidate.architecture == architecture &&
|
||||
candidate.compiler_family == compiler_family && candidate.compiler_abi == compiler_abi &&
|
||||
candidate.stdlib_abi == stdlib_abi && candidate.linkage == linkage &&
|
||||
candidate.cpu_features == cpu_features && candidate.sanitizers_key == sanitizers_key &&
|
||||
candidate.lto_mode == lto_mode &&
|
||||
candidate.dependency_closure_hash == dependency_closure_hash;
|
||||
}
|
||||
|
||||
BinaryCompatibilityKey
|
||||
make_binary_compatibility_key(const ProfileContext &profile,
|
||||
const Toolchain::ToolchainCapabilities &toolchain,
|
||||
std::string_view linkage, std::string_view dependency_closure_hash) {
|
||||
BinaryCompatibilityKey key;
|
||||
key.os = profile.os;
|
||||
key.architecture = profile.architecture;
|
||||
key.compiler_family = std::string{compiler_name(profile.compiler)};
|
||||
key.compiler_abi = toolchain.version_banner + "|" + toolchain.target_triple;
|
||||
key.stdlib_abi = (profile.compiler == CompilerFamily::Gcc) ? "libstdc++" : "libstdc++/libc++";
|
||||
for (const auto &opt : profile.compile_options) {
|
||||
if (opt == "-stdlib=libc++") {
|
||||
key.stdlib_abi = "libc++";
|
||||
} else if (opt == "-stdlib=libstdc++") {
|
||||
key.stdlib_abi = "libstdc++";
|
||||
} else if (opt.starts_with("-march=") || opt.starts_with("-mcpu=")) {
|
||||
if (!key.cpu_features.empty()) {
|
||||
key.cpu_features += ",";
|
||||
}
|
||||
key.cpu_features += opt;
|
||||
}
|
||||
}
|
||||
key.linkage = std::string{linkage};
|
||||
key.lto_mode = std::string{lto_mode_name(profile.lto)};
|
||||
std::vector<std::string> sans;
|
||||
for (const auto s : profile.sanitizers) {
|
||||
sans.emplace_back(sanitizer_name(s));
|
||||
}
|
||||
std::ranges::sort(sans);
|
||||
for (std::size_t i = 0; i < sans.size(); ++i) {
|
||||
if (i > 0) {
|
||||
key.sanitizers_key += "+";
|
||||
}
|
||||
key.sanitizers_key += sans[i];
|
||||
}
|
||||
key.dependency_closure_hash = std::string{dependency_closure_hash};
|
||||
return key;
|
||||
}
|
||||
|
||||
std::optional<BinaryVariantMeta>
|
||||
select_compatible_binary(const BinaryCompatibilityKey &key,
|
||||
const std::vector<BinaryVariantMeta> &available) {
|
||||
for (const auto &v : available) {
|
||||
if (key.matches(v)) {
|
||||
return v;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
Void::Result::Result<MaterializedSource, Void::Result::Error>
|
||||
materialize_dependency_source(const DependencyRecord &dep, const FetchOptions &options) {
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(options.cache_dir, ec);
|
||||
|
||||
// 1. Local path source: compute content hash without mutating the external checkout.
|
||||
if (dep.source_kind == DependencySourceKind::Path) {
|
||||
const std::filesystem::path raw{dep.location};
|
||||
const auto abs = raw.is_absolute() ? raw : (options.project_root / raw);
|
||||
const auto canon = std::filesystem::weakly_canonical(abs, ec);
|
||||
if (ec || !std::filesystem::is_directory(canon)) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::not_found,
|
||||
std::format("local path dependency '{}' at '{}' does not exist",
|
||||
dep.name, dep.location))};
|
||||
}
|
||||
Snapshot::SnapshotOptions sopts;
|
||||
sopts.project_root = canon;
|
||||
sopts.snapshot_store_dir = options.cache_dir / "path-snapshots";
|
||||
sopts.materialize = false;
|
||||
auto snap = Snapshot::capture_snapshot(sopts, {}, {canon});
|
||||
if (!snap) {
|
||||
return std::unexpected{snap.error()};
|
||||
}
|
||||
MaterializedSource out;
|
||||
out.alias = dep.name;
|
||||
out.source_dir = canon;
|
||||
out.content_identity_hash = snap->snapshot_id;
|
||||
out.from_cache = true;
|
||||
return out;
|
||||
}
|
||||
|
||||
// 2. Checksummed archive source (local file:// or verified cached tar).
|
||||
if (dep.source_kind == DependencySourceKind::Archive) {
|
||||
const auto extract_dir = options.cache_dir / "archives" / dep.sha256;
|
||||
const auto marker = extract_dir / ".vbs_verified";
|
||||
const auto lock_path = options.cache_dir / "locks" / (dep.sha256 + ".lock");
|
||||
auto lock = Platform::FileLock::acquire(lock_path, Platform::LockMode::Exclusive);
|
||||
if (!lock) {
|
||||
return std::unexpected{lock.error()};
|
||||
}
|
||||
|
||||
if (std::filesystem::is_regular_file(marker, ec)) {
|
||||
MaterializedSource out;
|
||||
out.alias = dep.name;
|
||||
out.source_dir = extract_dir;
|
||||
out.content_identity_hash = dep.sha256;
|
||||
out.from_cache = true;
|
||||
return out;
|
||||
}
|
||||
|
||||
const auto downloaded_tar = options.cache_dir / "downloads" / (dep.sha256 + ".tar");
|
||||
std::filesystem::create_directories(downloaded_tar.parent_path(), ec);
|
||||
|
||||
if (!std::filesystem::is_regular_file(downloaded_tar, ec)) {
|
||||
if (dep.location.starts_with("file://")) {
|
||||
const std::filesystem::path src_file{dep.location.substr(7)};
|
||||
auto copied = Platform::copy_isolated(src_file, downloaded_tar);
|
||||
if (!copied) {
|
||||
return std::unexpected{copied.error()};
|
||||
}
|
||||
} else if (std::filesystem::is_regular_file(dep.location, ec)) {
|
||||
auto copied = Platform::copy_isolated(dep.location, downloaded_tar);
|
||||
if (!copied) {
|
||||
return std::unexpected{copied.error()};
|
||||
}
|
||||
} else {
|
||||
if (options.offline) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::not_found,
|
||||
std::format("offline mode: archive '{}' (sha256={}) is not cached",
|
||||
dep.location, dep.sha256))};
|
||||
}
|
||||
auto curl = Platform::resolve_executable("curl");
|
||||
if (!curl) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::not_found,
|
||||
"cannot fetch remote archive: neither curl nor Void::Net is available")};
|
||||
}
|
||||
const auto tmp_dl = downloaded_tar.string() + ".part";
|
||||
Platform::ProcessRequest req;
|
||||
req.executable = *curl;
|
||||
req.arguments = {"--fail", "--silent", "--show-error", "--location", "--proto",
|
||||
"=https,http", "--output", tmp_dl, dep.location};
|
||||
req.timeout = std::chrono::seconds{120};
|
||||
auto proc = Platform::run_supervised(req);
|
||||
if (!proc || !proc->succeeded()) {
|
||||
std::filesystem::remove(tmp_dl, ec);
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error,
|
||||
std::format("failed fetching archive '{}': {}", dep.location,
|
||||
proc ? proc->stderr_data : proc.error().message()))};
|
||||
}
|
||||
std::filesystem::rename(tmp_dl, downloaded_tar, ec);
|
||||
}
|
||||
}
|
||||
|
||||
// Verify SHA-256 BEFORE extracting!
|
||||
auto actual_sha = Util::sha256_file_hex(downloaded_tar);
|
||||
if (!actual_sha) {
|
||||
return std::unexpected{actual_sha.error()};
|
||||
}
|
||||
if (*actual_sha != dep.sha256) {
|
||||
std::filesystem::remove(downloaded_tar, ec);
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("SHA-256 mismatch for archive '{}': expected {}, got {}",
|
||||
dep.location, dep.sha256, *actual_sha))};
|
||||
}
|
||||
|
||||
auto extracted = extract_safe_tar(downloaded_tar, extract_dir, options.archive_limits);
|
||||
if (!extracted) {
|
||||
return std::unexpected{extracted.error()};
|
||||
}
|
||||
(void)Platform::atomic_write_file(marker, dep.sha256 + "\n", true);
|
||||
|
||||
MaterializedSource out;
|
||||
out.alias = dep.name;
|
||||
out.source_dir = extract_dir;
|
||||
out.content_identity_hash = dep.sha256;
|
||||
out.from_cache = false;
|
||||
return out;
|
||||
}
|
||||
|
||||
// 3. Exact pinned Git revision source.
|
||||
if (dep.source_kind == DependencySourceKind::Git) {
|
||||
const auto git_dir =
|
||||
options.cache_dir / "git" / (sanitize_key(dep.name) + "_" + dep.revision);
|
||||
const auto marker = git_dir / ".vbs_verified_rev";
|
||||
const auto lock_path = options.cache_dir / "locks" / ("git_" + dep.revision + ".lock");
|
||||
auto lock = Platform::FileLock::acquire(lock_path, Platform::LockMode::Exclusive);
|
||||
if (!lock) {
|
||||
return std::unexpected{lock.error()};
|
||||
}
|
||||
|
||||
if (std::filesystem::is_regular_file(marker, ec)) {
|
||||
MaterializedSource out;
|
||||
out.alias = dep.name;
|
||||
out.source_dir = git_dir;
|
||||
out.content_identity_hash = dep.revision;
|
||||
out.from_cache = true;
|
||||
return out;
|
||||
}
|
||||
|
||||
const bool is_local_repo = dep.location.starts_with("file://") ||
|
||||
dep.location.starts_with("/") ||
|
||||
std::filesystem::is_directory(dep.location, ec);
|
||||
if (options.offline && !is_local_repo) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::not_found,
|
||||
std::format("offline mode: git dependency '{}' ({}@{}) is not cached",
|
||||
dep.name, dep.location, dep.revision))};
|
||||
}
|
||||
|
||||
auto git_bin = Platform::resolve_executable("git");
|
||||
if (!git_bin) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::not_found, "'git' not found in PATH")};
|
||||
}
|
||||
|
||||
const auto stage = git_dir.parent_path() / (git_dir.filename().string() + ".stage");
|
||||
std::filesystem::remove_all(stage, ec);
|
||||
std::filesystem::create_directories(stage.parent_path(), ec);
|
||||
auto stage_cleanup = Void::Scope::on_exit([&] { std::filesystem::remove_all(stage, ec); });
|
||||
|
||||
auto run_git =
|
||||
[&](std::vector<std::string> args,
|
||||
std::optional<std::filesystem::path> cwd =
|
||||
std::nullopt) -> Void::Result::Result<std::string, Void::Result::Error> {
|
||||
Platform::ProcessRequest req;
|
||||
req.executable = *git_bin;
|
||||
req.arguments = std::move(args);
|
||||
req.working_directory = cwd;
|
||||
req.environment.set_vars["GIT_TERMINAL_PROMPT"] = "0";
|
||||
req.timeout = std::chrono::seconds{180};
|
||||
auto p = Platform::run_supervised(req);
|
||||
if (!p || !p->succeeded()) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error,
|
||||
std::format("git failed for '{}': {}", dep.location,
|
||||
p ? p->stderr_data : p.error().message()))};
|
||||
}
|
||||
return p->stdout_data;
|
||||
};
|
||||
|
||||
if (auto r = run_git({"clone", "--no-checkout", dep.location, stage.string()}); !r) {
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
if (auto r = run_git({"checkout", "--detach", dep.revision}, stage); !r) {
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
auto head = run_git({"rev-parse", "HEAD"}, stage);
|
||||
if (!head || trim(*head) != dep.revision) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("git checkout HEAD mismatch for '{}': expected {}", dep.name,
|
||||
dep.revision))};
|
||||
}
|
||||
(void)Platform::atomic_write_file(stage / ".vbs_verified_rev", dep.revision + "\n", true);
|
||||
if (std::filesystem::exists(git_dir, ec)) {
|
||||
std::filesystem::remove_all(git_dir, ec);
|
||||
}
|
||||
std::filesystem::rename(stage, git_dir, ec);
|
||||
if (ec) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"failed publishing git checkout")};
|
||||
}
|
||||
stage_cleanup.dismiss();
|
||||
|
||||
MaterializedSource out;
|
||||
out.alias = dep.name;
|
||||
out.source_dir = git_dir;
|
||||
out.content_identity_hash = dep.revision;
|
||||
out.from_cache = false;
|
||||
return out;
|
||||
}
|
||||
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("dependency '{}' requires package/registry resolution before source fetch",
|
||||
dep.name))};
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Package
|
||||
@@ -0,0 +1,389 @@
|
||||
#include <Void/Build/Package/Lockfile.hpp>
|
||||
|
||||
#include <Void/Build/Platform/FileOps.hpp>
|
||||
#include <Void/Build/Util/Json.hpp>
|
||||
#include <Void/Build/Util/Sha256.hpp>
|
||||
#include <Void/Data/StrictJson.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <type_traits>
|
||||
|
||||
namespace Void::Build::Package {
|
||||
namespace {
|
||||
|
||||
using JsonVal = Void::Json::Strict::Value;
|
||||
|
||||
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
|
||||
return Void::System::make_system_error(code, std::move(msg));
|
||||
}
|
||||
|
||||
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::string get_str(const JsonVal::Object &obj, const std::string &k) {
|
||||
const auto *v = find_key(obj, k);
|
||||
if (!v) {
|
||||
return {};
|
||||
}
|
||||
const auto *s = std::get_if<std::string>(&v->value);
|
||||
return s ? *s : std::string{};
|
||||
}
|
||||
|
||||
std::int64_t get_i64(const JsonVal::Object &obj, const std::string &k, std::int64_t def = 0) {
|
||||
const auto *v = find_key(obj, k);
|
||||
if (!v) {
|
||||
return def;
|
||||
}
|
||||
const auto *i = std::get_if<std::int64_t>(&v->value);
|
||||
return i ? *i : def;
|
||||
}
|
||||
|
||||
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
|
||||
const auto *v = find_key(obj, k);
|
||||
if (!v) {
|
||||
return def;
|
||||
}
|
||||
const auto *b = std::get_if<bool>(&v->value);
|
||||
return b ? *b : def;
|
||||
}
|
||||
|
||||
std::vector<std::string> get_str_array(const JsonVal::Object &obj, const std::string &k) {
|
||||
std::vector<std::string> out;
|
||||
const auto *v = find_key(obj, k);
|
||||
if (!v) {
|
||||
return out;
|
||||
}
|
||||
if (const auto *arr = std::get_if<JsonVal::Array>(&v->value)) {
|
||||
for (const auto &item : *arr) {
|
||||
if (const auto *s = std::get_if<std::string>(&item.value)) {
|
||||
out.push_back(*s);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Strips embedded URL credentials (user:pass@host) before persisting to vbs.lock!
|
||||
std::string strip_url_credentials(std::string_view url) {
|
||||
const auto scheme = url.find("://");
|
||||
if (scheme == std::string_view::npos) {
|
||||
return std::string{url};
|
||||
}
|
||||
const auto after_scheme = scheme + 3;
|
||||
const auto slash = url.find('/', after_scheme);
|
||||
const auto at = url.find('@', after_scheme);
|
||||
if (at != std::string_view::npos && (slash == std::string_view::npos || at < slash)) {
|
||||
return std::string{url.substr(0, after_scheme)} + std::string{url.substr(at + 1)};
|
||||
}
|
||||
return std::string{url};
|
||||
}
|
||||
|
||||
std::string
|
||||
serialize_contexts_body(const std::map<std::string, LockContextRecord, std::less<>> &ctxs) {
|
||||
using Util::json_array;
|
||||
using Util::json_quote;
|
||||
|
||||
std::string out{"{"};
|
||||
bool first = true;
|
||||
for (const auto &[key, ctx] : ctxs) {
|
||||
if (!first) {
|
||||
out += ',';
|
||||
}
|
||||
first = false;
|
||||
out += json_quote(key) + ":{\"context_key\":" + json_quote(ctx.context_key) +
|
||||
",\"profile_name\":" + json_quote(ctx.profile_name) +
|
||||
",\"compiler\":" + json_quote(ctx.compiler) + ",\"os\":" + json_quote(ctx.os) +
|
||||
",\"architecture\":" + json_quote(ctx.architecture) +
|
||||
",\"machine_role\":" + json_quote(ctx.machine_role) +
|
||||
",\"declaration_fingerprint\":" + json_quote(ctx.declaration_fingerprint) +
|
||||
",\"entries\":";
|
||||
out += json_array(ctx.entries, [](const LockedSourceEntry &e) {
|
||||
return "{\"alias\":" + json_quote(e.alias) +
|
||||
",\"source_kind\":" + json_quote(e.source_kind) + ",\"registry_authority\":" +
|
||||
json_quote(strip_url_credentials(e.registry_authority)) +
|
||||
",\"package_name\":" + json_quote(e.package_name) +
|
||||
",\"version\":" + json_quote(e.version) +
|
||||
",\"location\":" + json_quote(strip_url_credentials(e.location)) +
|
||||
",\"revision\":" + json_quote(e.revision) +
|
||||
",\"sha256\":" + json_quote(e.sha256) + ",\"builder\":" + json_quote(e.builder) +
|
||||
",\"features\":" + json_array(e.features, json_quote) +
|
||||
",\"build_dependency\":" + std::string{e.build_dependency ? "true" : "false"} +
|
||||
'}';
|
||||
});
|
||||
out += '}';
|
||||
}
|
||||
out += '}';
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string make_lock_context_key(const ProfileContext &profile, std::string_view machine_role) {
|
||||
return std::format("{}:{}:{}:{}:{}", profile.name, compiler_name(profile.compiler), profile.os,
|
||||
profile.architecture, machine_role);
|
||||
}
|
||||
|
||||
std::string compute_declaration_fingerprint(const ProfileContext &profile,
|
||||
std::string_view machine_role,
|
||||
const std::vector<NormalizedDependency> &declarations) {
|
||||
Util::Sha256Hasher h;
|
||||
h.update_length_prefixed("vbs-lock-decl-v1");
|
||||
h.update_length_prefixed(profile.name);
|
||||
h.update_length_prefixed(compiler_name(profile.compiler));
|
||||
h.update_length_prefixed(profile.os);
|
||||
h.update_length_prefixed(profile.architecture);
|
||||
h.update_length_prefixed(machine_role);
|
||||
|
||||
std::vector<const DependencyRecord *> sorted;
|
||||
for (const auto &nd : declarations) {
|
||||
const bool want_build = (machine_role == "build");
|
||||
if (nd.record.build_dependency == want_build) {
|
||||
sorted.push_back(&nd.record);
|
||||
}
|
||||
}
|
||||
std::ranges::sort(sorted, [](const DependencyRecord *a, const DependencyRecord *b) {
|
||||
return a->name < b->name;
|
||||
});
|
||||
|
||||
h.update_u64(sorted.size());
|
||||
for (const auto *d : sorted) {
|
||||
h.update_length_prefixed(d->name);
|
||||
h.update_u64(static_cast<std::uint64_t>(d->source_kind));
|
||||
h.update_length_prefixed(strip_url_credentials(d->location));
|
||||
h.update_length_prefixed(d->revision);
|
||||
h.update_length_prefixed(d->package);
|
||||
h.update_length_prefixed(d->version);
|
||||
h.update_length_prefixed(d->builder);
|
||||
h.update_length_prefixed(strip_url_credentials(d->registry_authority));
|
||||
h.update_length_prefixed(d->sha256);
|
||||
h.update_u64(d->features.size());
|
||||
for (const auto &f : d->features) {
|
||||
h.update_length_prefixed(f);
|
||||
}
|
||||
h.update_u64(d->options.size());
|
||||
for (const auto &[k, opt] : d->options) {
|
||||
h.update_length_prefixed(k);
|
||||
std::visit(
|
||||
[&](const auto &v) {
|
||||
using T = std::remove_cvref_t<decltype(v)>;
|
||||
if constexpr (std::same_as<T, std::string>) {
|
||||
h.update_length_prefixed("s:" + v);
|
||||
} else if constexpr (std::same_as<T, bool>) {
|
||||
h.update_length_prefixed(v ? "b:1" : "b:0");
|
||||
} else {
|
||||
h.update_length_prefixed("i:" + std::to_string(v));
|
||||
}
|
||||
},
|
||||
opt.value);
|
||||
}
|
||||
}
|
||||
return h.finalize_hex();
|
||||
}
|
||||
|
||||
std::string serialize_lockfile(const LockfileDocument &doc) {
|
||||
const std::string body = serialize_contexts_body(doc.contexts);
|
||||
const std::string rev = Util::sha256_hex(body);
|
||||
return "{\"schema_version\":" + std::to_string(doc.schema_version) +
|
||||
",\"revision_hash\":" + Util::json_quote(rev) + ",\"contexts\":" + body + "}\n";
|
||||
}
|
||||
|
||||
Void::Result::Result<LockfileDocument, Void::Result::Error>
|
||||
parse_lockfile(std::string_view json_text) {
|
||||
if (!Util::is_valid_utf8(json_text)) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::invalid_argument, "lockfile invalid UTF-8")};
|
||||
}
|
||||
auto parsed = Void::Json::Strict::parse(json_text);
|
||||
if (!parsed) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"malformed JSON in vbs.lock")};
|
||||
}
|
||||
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
|
||||
if (!root) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"vbs.lock root must be a JSON object")};
|
||||
}
|
||||
LockfileDocument doc;
|
||||
doc.schema_version = static_cast<int>(get_i64(*root, "schema_version", 0));
|
||||
if (doc.schema_version != kLockfileSchemaVersion) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("unsupported vbs.lock schema_version {}", doc.schema_version))};
|
||||
}
|
||||
doc.revision_hash = get_str(*root, "revision_hash");
|
||||
|
||||
if (const auto *ctxs_v = find_key(*root, "contexts")) {
|
||||
const auto *cobj = std::get_if<JsonVal::Object>(&ctxs_v->value);
|
||||
if (!cobj) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"vbs.lock contexts must be an object")};
|
||||
}
|
||||
for (const auto &[key, cv] : *cobj) {
|
||||
const auto *co = std::get_if<JsonVal::Object>(&cv.value);
|
||||
if (!co) {
|
||||
continue;
|
||||
}
|
||||
LockContextRecord rec;
|
||||
rec.context_key = get_str(*co, "context_key");
|
||||
rec.profile_name = get_str(*co, "profile_name");
|
||||
rec.compiler = get_str(*co, "compiler");
|
||||
rec.os = get_str(*co, "os");
|
||||
rec.architecture = get_str(*co, "architecture");
|
||||
rec.machine_role = get_str(*co, "machine_role");
|
||||
rec.declaration_fingerprint = get_str(*co, "declaration_fingerprint");
|
||||
if (const auto *ev = find_key(*co, "entries")) {
|
||||
if (const auto *earr = std::get_if<JsonVal::Array>(&ev->value)) {
|
||||
for (const auto &item : *earr) {
|
||||
if (const auto *eo = std::get_if<JsonVal::Object>(&item.value)) {
|
||||
LockedSourceEntry e;
|
||||
e.alias = get_str(*eo, "alias");
|
||||
e.source_kind = get_str(*eo, "source_kind");
|
||||
e.registry_authority = get_str(*eo, "registry_authority");
|
||||
e.package_name = get_str(*eo, "package_name");
|
||||
e.version = get_str(*eo, "version");
|
||||
e.location = get_str(*eo, "location");
|
||||
e.revision = get_str(*eo, "revision");
|
||||
e.sha256 = get_str(*eo, "sha256");
|
||||
e.builder = get_str(*eo, "builder");
|
||||
e.features = get_str_array(*eo, "features");
|
||||
e.build_dependency = get_bool(*eo, "build_dependency", false);
|
||||
rec.entries.push_back(std::move(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
doc.contexts[key] = std::move(rec);
|
||||
}
|
||||
}
|
||||
|
||||
// Verify revision hash integrity against canonical body!
|
||||
const std::string expected_rev = Util::sha256_hex(serialize_contexts_body(doc.contexts));
|
||||
if (!doc.revision_hash.empty() && doc.revision_hash != expected_rev) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::invalid_argument,
|
||||
"vbs.lock revision_hash does not match contents (corrupted or hand-edited lockfile)")};
|
||||
}
|
||||
doc.revision_hash = expected_rev;
|
||||
return doc;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<PinnedLock>, Void::Result::Error>
|
||||
load_pinned_lock(const std::filesystem::path &lock_path) {
|
||||
auto meta = Platform::stat_lstat(lock_path);
|
||||
if (!meta) {
|
||||
return std::unexpected{meta.error()};
|
||||
}
|
||||
if (!meta->exists) {
|
||||
return std::nullopt;
|
||||
}
|
||||
auto text = Void::FileSystem::read_file_bounded(lock_path, {64ULL * 1024ULL * 1024ULL});
|
||||
if (!text) {
|
||||
return std::unexpected{text.error()};
|
||||
}
|
||||
auto parsed = parse_lockfile(*text);
|
||||
if (!parsed) {
|
||||
return std::unexpected{parsed.error()};
|
||||
}
|
||||
PinnedLock pinned;
|
||||
pinned.revision_hash = parsed->revision_hash;
|
||||
pinned.raw_json = std::move(*text);
|
||||
pinned.document = std::move(*parsed);
|
||||
return pinned;
|
||||
}
|
||||
|
||||
Void::Result::Result<const LockContextRecord *, Void::Result::Error>
|
||||
validate_locked_context(const LockfileDocument &doc, std::string_view context_key,
|
||||
std::string_view expected_declaration_fingerprint) {
|
||||
const auto it = doc.contexts.find(context_key);
|
||||
if (it == doc.contexts.end()) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("vbs.lock has no resolution for context '{}' (run 'vbs deps resolve')",
|
||||
context_key))};
|
||||
}
|
||||
if (it->second.declaration_fingerprint != expected_declaration_fingerprint) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format(
|
||||
"vbs.lock context '{}' is incompatible with current dependency declarations "
|
||||
"(run 'vbs deps resolve' or 'vbs deps update')",
|
||||
context_key))};
|
||||
}
|
||||
return &it->second;
|
||||
}
|
||||
|
||||
Void::Result::Result<PinnedLock, Void::Result::Error>
|
||||
publish_lock_context_cas(const std::filesystem::path &lock_path,
|
||||
std::string_view expected_base_revision,
|
||||
const LockContextRecord &updated_context, bool locked_mode) {
|
||||
if (locked_mode) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::permission_denied,
|
||||
"--locked forbids creating or modifying vbs.lock")};
|
||||
}
|
||||
|
||||
const auto mutex_path = lock_path.parent_path() / ".vbs" / "lockfile.mutex";
|
||||
auto mutex = Platform::FileLock::acquire(mutex_path, Platform::LockMode::Exclusive);
|
||||
if (!mutex) {
|
||||
return std::unexpected{mutex.error()};
|
||||
}
|
||||
|
||||
LockfileDocument current;
|
||||
std::string current_rev;
|
||||
auto meta = Platform::stat_lstat(lock_path);
|
||||
if (!meta) {
|
||||
return std::unexpected{meta.error()};
|
||||
}
|
||||
if (meta->exists) {
|
||||
auto text = Void::FileSystem::read_file_bounded(lock_path, {64ULL * 1024ULL * 1024ULL});
|
||||
if (!text) {
|
||||
return std::unexpected{text.error()};
|
||||
}
|
||||
auto parsed = parse_lockfile(*text);
|
||||
if (!parsed) {
|
||||
return std::unexpected{parsed.error()};
|
||||
}
|
||||
current = std::move(*parsed);
|
||||
current_rev = current.revision_hash;
|
||||
}
|
||||
|
||||
// Compare-and-swap revision check (D-025): if another profile updated the lock concurrently,
|
||||
// allow merging ONLY if the other update did NOT touch our context_key; if it modified our
|
||||
// context_key or base mismatch occurred, report busy conflict for caller re-resolution!
|
||||
if (current_rev != expected_base_revision) {
|
||||
const auto existing_ctx = current.contexts.find(updated_context.context_key);
|
||||
if (existing_ctx != current.contexts.end() &&
|
||||
existing_ctx->second.declaration_fingerprint !=
|
||||
updated_context.declaration_fingerprint) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::busy,
|
||||
std::format("concurrent vbs.lock revision conflict (expected '{}', found '{}'); "
|
||||
"re-resolve and retry",
|
||||
expected_base_revision, current_rev))};
|
||||
}
|
||||
}
|
||||
|
||||
current.contexts[updated_context.context_key] = updated_context;
|
||||
const std::string serialized = serialize_lockfile(current);
|
||||
auto reparsed = parse_lockfile(serialized);
|
||||
if (!reparsed) {
|
||||
return std::unexpected{reparsed.error()};
|
||||
}
|
||||
|
||||
auto wrote = Platform::atomic_write_file(lock_path, serialized, true);
|
||||
if (!wrote) {
|
||||
return std::unexpected{wrote.error()};
|
||||
}
|
||||
|
||||
PinnedLock pinned;
|
||||
pinned.revision_hash = reparsed->revision_hash;
|
||||
pinned.raw_json = serialized;
|
||||
pinned.document = std::move(*reparsed);
|
||||
return pinned;
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Package
|
||||
@@ -0,0 +1,420 @@
|
||||
#include <Void/Build/Package/RegistryClient.hpp>
|
||||
|
||||
#include <Void/Build/Package/Fetch.hpp>
|
||||
#include <Void/Build/Platform/FileOps.hpp>
|
||||
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||
#include <Void/Build/Util/Sha256.hpp>
|
||||
#include <Void/Core/Scope.hpp>
|
||||
#include <Void/Data/StrictJson.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
#include <Void/Text/Semver.hpp>
|
||||
#include <Void/Text/Str.hpp>
|
||||
#include <Void/Text/Url.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <arpa/inet.h>
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <map>
|
||||
#include <netdb.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace Void::Build::Package {
|
||||
namespace {
|
||||
|
||||
using JsonVal = Void::Json::Strict::Value;
|
||||
|
||||
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
|
||||
return Void::System::make_system_error(code, redact_secrets(msg));
|
||||
}
|
||||
|
||||
struct ParsedHttpUrl {
|
||||
std::string scheme;
|
||||
std::string host;
|
||||
std::uint16_t port{80};
|
||||
std::string base_path;
|
||||
};
|
||||
|
||||
Void::Result::Result<ParsedHttpUrl, Void::Result::Error> parse_registry_url(std::string_view url) {
|
||||
url = Void::Str::trim_ascii(url);
|
||||
const auto sep = url.find("://");
|
||||
if (sep == std::string_view::npos) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"registry URL must include http:// or https:// scheme")};
|
||||
}
|
||||
ParsedHttpUrl out;
|
||||
out.scheme = Void::Str::to_lower_ascii(url.substr(0, sep));
|
||||
if (out.scheme != "http" && out.scheme != "https") {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"unsupported registry URL scheme (expected http/https)")};
|
||||
}
|
||||
const auto rest = url.substr(sep + 3);
|
||||
const auto slash = rest.find('/');
|
||||
const auto authority = slash == std::string_view::npos ? rest : rest.substr(0, slash);
|
||||
out.base_path =
|
||||
slash == std::string_view::npos ? std::string{} : std::string{rest.substr(slash)};
|
||||
while (!out.base_path.empty() && out.base_path.back() == '/') {
|
||||
out.base_path.pop_back();
|
||||
}
|
||||
|
||||
const auto colon = authority.rfind(':');
|
||||
if (colon != std::string_view::npos) {
|
||||
out.host = std::string{authority.substr(0, colon)};
|
||||
int p = 0;
|
||||
if (!Void::Str::to_int(authority.substr(colon + 1), p) || p <= 0 || p > 65535) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"invalid port in registry URL")};
|
||||
}
|
||||
out.port = static_cast<std::uint16_t>(p);
|
||||
} else {
|
||||
out.host = std::string{authority};
|
||||
out.port = (out.scheme == "https") ? 443 : 80;
|
||||
}
|
||||
if (out.host.empty()) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"empty host in registry URL")};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
struct RawHttpReply {
|
||||
std::uint16_t status{0};
|
||||
std::map<std::string, std::string, std::less<>> headers;
|
||||
std::string body;
|
||||
};
|
||||
|
||||
bool send_all(int fd, std::string_view data) {
|
||||
std::size_t off = 0;
|
||||
while (off < data.size()) {
|
||||
const ssize_t n = ::send(fd, data.data() + off, data.size() - off, MSG_NOSIGNAL);
|
||||
if (n < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
off += static_cast<std::size_t>(n);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Void::Result::Result<RawHttpReply, Void::Result::Error>
|
||||
send_http_request(const ParsedHttpUrl &parsed, std::string_view method, std::string_view path,
|
||||
const std::map<std::string, std::string, std::less<>> &headers,
|
||||
std::string_view body) {
|
||||
const std::string full_path = parsed.base_path + std::string{path};
|
||||
|
||||
// Plain TCP HTTP/1.1 client for http:// (loopback/local registry without external deps).
|
||||
if (parsed.scheme == "http") {
|
||||
struct addrinfo hints{};
|
||||
hints.ai_family = AF_INET;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
struct addrinfo *res = nullptr;
|
||||
const std::string port_s = std::to_string(parsed.port);
|
||||
if (::getaddrinfo(parsed.host.c_str(), port_s.c_str(), &hints, &res) != 0 || !res) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::io_error,
|
||||
std::format("registry client: failed resolving host '{}'", parsed.host))};
|
||||
}
|
||||
auto free_ai = Void::Scope::on_exit([&] { ::freeaddrinfo(res); });
|
||||
|
||||
const int fd = ::socket(res->ai_family, res->ai_socktype | SOCK_CLOEXEC, res->ai_protocol);
|
||||
if (fd < 0) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"registry client: socket() failed")};
|
||||
}
|
||||
Void::System::OwnedFd guard{fd};
|
||||
|
||||
struct timeval tv{30, 0};
|
||||
(void)::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
|
||||
(void)::setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
|
||||
|
||||
if (::connect(fd, res->ai_addr, res->ai_addrlen) != 0) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::io_error,
|
||||
std::format("registry client: connect to {}:{} failed", parsed.host, parsed.port))};
|
||||
}
|
||||
|
||||
std::string req = std::format("{} {} HTTP/1.1\r\nHost: {}:{}\r\nConnection: close\r\n"
|
||||
"Content-Length: {}\r\n",
|
||||
method, full_path, parsed.host, parsed.port, body.size());
|
||||
for (const auto &[k, v] : headers) {
|
||||
req += k + ": " + v + "\r\n";
|
||||
}
|
||||
req += "\r\n";
|
||||
req += body;
|
||||
if (!send_all(fd, req)) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"registry client: send() failed")};
|
||||
}
|
||||
|
||||
std::string raw;
|
||||
std::array<char, 16384> buf{};
|
||||
for (;;) {
|
||||
const ssize_t n = ::recv(fd, buf.data(), buf.size(), 0);
|
||||
if (n > 0) {
|
||||
raw.append(buf.data(), static_cast<std::size_t>(n));
|
||||
} else if (n == 0) {
|
||||
break;
|
||||
} else if (errno != EINTR) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"registry client: recv() failed")};
|
||||
}
|
||||
}
|
||||
|
||||
const auto hdr_end = raw.find("\r\n\r\n");
|
||||
if (hdr_end == std::string::npos) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"registry client: malformed HTTP response")};
|
||||
}
|
||||
|
||||
RawHttpReply reply;
|
||||
const std::string_view hdr_block{raw.data(), hdr_end};
|
||||
const auto first_crlf = hdr_block.find("\r\n");
|
||||
const auto status_line = hdr_block.substr(0, first_crlf);
|
||||
const auto sp1 = status_line.find(' ');
|
||||
if (sp1 != std::string_view::npos) {
|
||||
int code = 0;
|
||||
if (Void::Str::to_int(status_line.substr(sp1 + 1, 3), code)) {
|
||||
reply.status = static_cast<std::uint16_t>(code);
|
||||
}
|
||||
}
|
||||
if (first_crlf != std::string_view::npos) {
|
||||
std::size_t pos = first_crlf + 2;
|
||||
while (pos < hdr_block.size()) {
|
||||
const auto next = hdr_block.find("\r\n", pos);
|
||||
const auto line = hdr_block.substr(
|
||||
pos, next == std::string_view::npos ? std::string_view::npos : next - pos);
|
||||
const auto colon = line.find(':');
|
||||
if (colon != std::string_view::npos) {
|
||||
reply.headers[Void::Str::to_lower_ascii(
|
||||
Void::Str::trim_ascii(line.substr(0, colon)))] =
|
||||
std::string{Void::Str::trim_ascii(line.substr(colon + 1))};
|
||||
}
|
||||
if (next == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
pos = next + 2;
|
||||
}
|
||||
}
|
||||
reply.body = raw.substr(hdr_end + 4);
|
||||
return reply;
|
||||
}
|
||||
|
||||
// HTTPS fallback via curl (preserves TLS certificate verification; never disables TLS!).
|
||||
auto curl = Platform::resolve_executable("curl");
|
||||
if (!curl) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::not_found,
|
||||
"HTTPS registry operations require curl (OpenSSL/Void::Net not linked)")};
|
||||
}
|
||||
const std::string full_url =
|
||||
std::format("https://{}:{}{}", parsed.host, parsed.port, full_path);
|
||||
Platform::ProcessRequest req;
|
||||
req.executable = *curl;
|
||||
req.arguments = {"--silent", "--show-error", "--proto", "=https",
|
||||
"-X", std::string{method}, "-w", "\n%{http_code}"};
|
||||
for (const auto &[k, v] : headers) {
|
||||
req.arguments.push_back("-H");
|
||||
req.arguments.push_back(k + ": " + v);
|
||||
}
|
||||
if (!body.empty()) {
|
||||
req.arguments.push_back("--data-binary");
|
||||
req.arguments.push_back("@-");
|
||||
req.stdin_data = std::string{body};
|
||||
}
|
||||
req.arguments.push_back(full_url);
|
||||
req.timeout = std::chrono::seconds{120};
|
||||
auto proc = Platform::run_supervised(req);
|
||||
if (!proc || !proc->succeeded()) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error,
|
||||
std::format("HTTPS request failed: {}",
|
||||
proc ? proc->stderr_data : proc.error().message()))};
|
||||
}
|
||||
const auto nl = proc->stdout_data.rfind('\n');
|
||||
RawHttpReply reply;
|
||||
if (nl != std::string::npos) {
|
||||
int code = 0;
|
||||
if (Void::Str::to_int(Void::Str::trim_ascii(proc->stdout_data.substr(nl + 1)), code)) {
|
||||
reply.status = static_cast<std::uint16_t>(code);
|
||||
}
|
||||
reply.body = proc->stdout_data.substr(0, nl);
|
||||
}
|
||||
return reply;
|
||||
}
|
||||
|
||||
std::string get_str(const JsonVal::Object &obj, const std::string &k) {
|
||||
const auto it = obj.find(k);
|
||||
if (it == obj.end()) {
|
||||
return {};
|
||||
}
|
||||
const auto *s = std::get_if<std::string>(&it->second.value);
|
||||
return s ? *s : std::string{};
|
||||
}
|
||||
|
||||
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
|
||||
const auto it = obj.find(k);
|
||||
if (it == obj.end()) {
|
||||
return def;
|
||||
}
|
||||
const auto *b = std::get_if<bool>(&it->second.value);
|
||||
return b ? *b : def;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<std::vector<ReleaseRecord>, Void::Result::Error>
|
||||
fetch_package_releases(std::string_view registry_url, std::string_view package_name,
|
||||
const RegistryAuth &auth) {
|
||||
auto parsed_url = parse_registry_url(registry_url);
|
||||
if (!parsed_url) {
|
||||
return std::unexpected{parsed_url.error()};
|
||||
}
|
||||
std::map<std::string, std::string, std::less<>> headers;
|
||||
if (!auth.bearer_token.empty()) {
|
||||
headers["Authorization"] = "Bearer " + auth.bearer_token;
|
||||
}
|
||||
const std::string path = "/api/v1/packages/" + Void::Encoding::Url::encode(package_name);
|
||||
auto reply = send_http_request(*parsed_url, "GET", path, headers, {});
|
||||
if (!reply) {
|
||||
return std::unexpected{reply.error()};
|
||||
}
|
||||
if (reply->status != 200) {
|
||||
return std::unexpected{make_error(reply->status == 404
|
||||
? Void::System::SystemErrorCode::not_found
|
||||
: Void::System::SystemErrorCode::permission_denied,
|
||||
std::format("registry GET {} failed with HTTP {}: {}",
|
||||
path, reply->status, reply->body))};
|
||||
}
|
||||
|
||||
auto json = Void::Json::Strict::parse(reply->body);
|
||||
if (!json) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"invalid JSON returned by registry package endpoint")};
|
||||
}
|
||||
const auto *root = std::get_if<JsonVal::Object>(&json->value);
|
||||
if (!root) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"registry response root must be a JSON object")};
|
||||
}
|
||||
|
||||
std::vector<ReleaseRecord> releases;
|
||||
const auto rit = root->find("releases");
|
||||
if (rit != root->end()) {
|
||||
if (const auto *rarr = std::get_if<JsonVal::Array>(&rit->second.value)) {
|
||||
for (const auto &rv : *rarr) {
|
||||
const auto *ro = std::get_if<JsonVal::Object>(&rv.value);
|
||||
if (!ro) {
|
||||
continue;
|
||||
}
|
||||
const auto ver_str = get_str(*ro, "version");
|
||||
auto ver = Void::Semver::parse_strict(ver_str);
|
||||
if (!ver) {
|
||||
continue;
|
||||
}
|
||||
ReleaseRecord rec;
|
||||
rec.id = PackageId{std::string{registry_url}, std::string{package_name}};
|
||||
rec.version = *ver;
|
||||
rec.yanked = get_bool(*ro, "yanked", false);
|
||||
rec.source_sha256 = get_str(*ro, "sha256");
|
||||
rec.source_url = std::string{registry_url} + "/api/v1/packages/" +
|
||||
Void::Encoding::Url::encode(package_name) + "/" +
|
||||
Void::Encoding::Url::encode(ver_str) + "/download";
|
||||
releases.push_back(std::move(rec));
|
||||
}
|
||||
}
|
||||
}
|
||||
return releases;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::filesystem::path, Void::Result::Error>
|
||||
download_release_archive(std::string_view registry_url, std::string_view package_name,
|
||||
std::string_view version, std::string_view expected_sha256,
|
||||
const std::filesystem::path &dest_file, const RegistryAuth &auth) {
|
||||
auto parsed_url = parse_registry_url(registry_url);
|
||||
if (!parsed_url) {
|
||||
return std::unexpected{parsed_url.error()};
|
||||
}
|
||||
std::map<std::string, std::string, std::less<>> headers;
|
||||
if (!auth.bearer_token.empty()) {
|
||||
headers["Authorization"] = "Bearer " + auth.bearer_token;
|
||||
}
|
||||
const std::string path = "/api/v1/packages/" + Void::Encoding::Url::encode(package_name) + "/" +
|
||||
Void::Encoding::Url::encode(version) + "/download";
|
||||
auto reply = send_http_request(*parsed_url, "GET", path, headers, {});
|
||||
if (!reply) {
|
||||
return std::unexpected{reply.error()};
|
||||
}
|
||||
if (reply->status != 200) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
std::format("registry download {}@{} failed with HTTP {}",
|
||||
package_name, version, reply->status))};
|
||||
}
|
||||
|
||||
const std::string actual_sha = Util::sha256_hex(reply->body);
|
||||
if (!expected_sha256.empty() && actual_sha != expected_sha256) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("registry archive SHA-256 mismatch for {}@{}: expected {}, got {}",
|
||||
package_name, version, expected_sha256, actual_sha))};
|
||||
}
|
||||
|
||||
auto wrote = Platform::atomic_write_file(dest_file, reply->body, true);
|
||||
if (!wrote) {
|
||||
return std::unexpected{wrote.error()};
|
||||
}
|
||||
return dest_file;
|
||||
}
|
||||
|
||||
Void::Result::Result<PublishReceipt, Void::Result::Error>
|
||||
publish_package_archive(const PublishOptions &options) {
|
||||
if (!Void::Semver::parse_strict(options.version)) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"publish version must be strict SemVer (X.Y.Z)")};
|
||||
}
|
||||
auto parsed_url = parse_registry_url(options.registry_url);
|
||||
if (!parsed_url) {
|
||||
return std::unexpected{parsed_url.error()};
|
||||
}
|
||||
auto bytes = Void::FileSystem::read_file(options.archive_path);
|
||||
if (!bytes) {
|
||||
return std::unexpected{bytes.error()};
|
||||
}
|
||||
const std::string sha = Util::sha256_hex(*bytes);
|
||||
|
||||
std::map<std::string, std::string, std::less<>> headers;
|
||||
headers["X-Content-SHA256"] = sha;
|
||||
if (!options.auth.bearer_token.empty()) {
|
||||
headers["Authorization"] = "Bearer " + options.auth.bearer_token;
|
||||
}
|
||||
if (options.is_private) {
|
||||
headers["X-Package-Private"] = "true";
|
||||
}
|
||||
if (!options.description.empty()) {
|
||||
headers["X-Package-Description"] = options.description;
|
||||
}
|
||||
|
||||
const std::string path = "/api/v1/packages/" +
|
||||
Void::Encoding::Url::encode(options.package_name) + "/" +
|
||||
Void::Encoding::Url::encode(options.version);
|
||||
auto reply = send_http_request(*parsed_url, "PUT", path, headers, *bytes);
|
||||
if (!reply) {
|
||||
return std::unexpected{reply.error()};
|
||||
}
|
||||
if (reply->status != 200 && reply->status != 201) {
|
||||
return std::unexpected{make_error(
|
||||
reply->status == 409 ? Void::System::SystemErrorCode::already_exists
|
||||
: Void::System::SystemErrorCode::permission_denied,
|
||||
std::format("registry publish {}@{} failed with HTTP {}: {}", options.package_name,
|
||||
options.version, reply->status, reply->body))};
|
||||
}
|
||||
return PublishReceipt{sha, reply->status == 200};
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Package
|
||||
@@ -0,0 +1,342 @@
|
||||
#include <Void/Build/Package/Solver.hpp>
|
||||
|
||||
#include <Void/System/Types.hpp>
|
||||
#include <Void/Text/Str.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace Void::Build::Package {
|
||||
namespace {
|
||||
|
||||
Void::Result::Error solve_err(std::string msg) {
|
||||
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
std::move(msg));
|
||||
}
|
||||
|
||||
bool all_digits(std::string_view s) { return Void::Str::is_digit_ascii(s); }
|
||||
|
||||
std::string normalize_semver_token(std::string_view tok) {
|
||||
if (tok.empty() || tok == "*") {
|
||||
return std::string{tok};
|
||||
}
|
||||
std::string_view op;
|
||||
if (tok.starts_with(">=") || tok.starts_with("<=")) {
|
||||
op = tok.substr(0, 2);
|
||||
tok.remove_prefix(2);
|
||||
} else if (tok.starts_with('^') || tok.starts_with('~') || tok.starts_with('>') ||
|
||||
tok.starts_with('<') || tok.starts_with('=')) {
|
||||
op = tok.substr(0, 1);
|
||||
tok.remove_prefix(1);
|
||||
}
|
||||
|
||||
const auto meta_pos = tok.find_first_of("-+");
|
||||
const auto core = meta_pos == std::string_view::npos ? tok : tok.substr(0, meta_pos);
|
||||
const auto meta =
|
||||
meta_pos == std::string_view::npos ? std::string_view{} : tok.substr(meta_pos);
|
||||
|
||||
if (core.find_first_of("xX*") != std::string_view::npos) {
|
||||
return std::string{op} + std::string{tok};
|
||||
}
|
||||
|
||||
const auto dot1 = core.find('.');
|
||||
if (dot1 == std::string_view::npos) {
|
||||
if (!all_digits(core)) {
|
||||
return std::string{op} + std::string{tok};
|
||||
}
|
||||
if ((op == "~" || op == "^") && meta.empty()) {
|
||||
const unsigned long maj = std::stoul(std::string{core});
|
||||
if (op == "~" || maj == 0) {
|
||||
return std::format(">={}.0.0 <{}.0.0", maj, maj + 1);
|
||||
}
|
||||
}
|
||||
return std::string{op} + std::string{core} + ".0.0" + std::string{meta};
|
||||
}
|
||||
const auto dot2 = core.find('.', dot1 + 1);
|
||||
if (dot2 == std::string_view::npos) {
|
||||
const auto p1 = core.substr(0, dot1);
|
||||
const auto p2 = core.substr(dot1 + 1);
|
||||
if (!all_digits(p1) || !all_digits(p2)) {
|
||||
return std::string{op} + std::string{tok};
|
||||
}
|
||||
return std::string{op} + std::string{p1} + "." + std::string{p2} + ".0" + std::string{meta};
|
||||
}
|
||||
return std::string{op} + std::string{tok};
|
||||
}
|
||||
|
||||
// Adapter for shorthand SemVer comparator tokens (^1, ^1.0, ~1.2, <2) since
|
||||
// pinned Void::Semver::parse_range requires full major.minor.patch triplets.
|
||||
std::optional<Void::Semver::VersionRange> parse_semver_range_compat(std::string_view expr) {
|
||||
if (auto direct = Void::Semver::parse_range(expr); direct) {
|
||||
return direct;
|
||||
}
|
||||
std::string normalized;
|
||||
std::size_t pos = 0;
|
||||
bool first_clause = true;
|
||||
while (pos <= expr.size()) {
|
||||
const auto sep = expr.find("||", pos);
|
||||
const auto clause = expr.substr(pos, sep == std::string_view::npos ? sep : sep - pos);
|
||||
if (!first_clause) {
|
||||
normalized += " || ";
|
||||
}
|
||||
first_clause = false;
|
||||
|
||||
bool first_tok = true;
|
||||
std::size_t i = 0;
|
||||
while (i < clause.size()) {
|
||||
while (i < clause.size() && (clause[i] == ' ' || clause[i] == '\t')) {
|
||||
++i;
|
||||
}
|
||||
if (i == clause.size()) {
|
||||
break;
|
||||
}
|
||||
auto end = clause.find_first_of(" \t", i);
|
||||
if (end == std::string_view::npos) {
|
||||
end = clause.size();
|
||||
}
|
||||
if (!first_tok) {
|
||||
normalized.push_back(' ');
|
||||
}
|
||||
first_tok = false;
|
||||
normalized += normalize_semver_token(clause.substr(i, end - i));
|
||||
i = end;
|
||||
}
|
||||
if (sep == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
pos = sep + 2;
|
||||
}
|
||||
return Void::Semver::parse_range(normalized);
|
||||
}
|
||||
|
||||
struct ActiveConstraint {
|
||||
Void::Semver::VersionRange range;
|
||||
std::string range_expr;
|
||||
std::string requirer;
|
||||
std::vector<std::string> features;
|
||||
};
|
||||
|
||||
// PubGrub-style conflict-driven backtracking solver with incompatibility explanation trace.
|
||||
class PubGrubSolver {
|
||||
public:
|
||||
PubGrubSolver(const PackageIndex &index, const SolveOptions &options)
|
||||
: index_{index}, options_{options} {}
|
||||
|
||||
Void::Result::Result<SolveResult, Void::Result::Error>
|
||||
solve(const std::vector<DependencyConstraint> &roots) {
|
||||
std::map<PackageId, std::vector<ActiveConstraint>> constraints;
|
||||
for (const auto &rc : roots) {
|
||||
auto parsed = parse_semver_range_compat(rc.range_expr);
|
||||
if (!parsed) {
|
||||
return std::unexpected{
|
||||
solve_err(std::format("invalid version range '{}' for '{}' (from {})",
|
||||
rc.range_expr, rc.target.format(), rc.origin_label))};
|
||||
}
|
||||
constraints[rc.target].push_back(ActiveConstraint{
|
||||
*parsed, rc.range_expr, rc.origin_label.empty() ? "root" : rc.origin_label,
|
||||
rc.required_features});
|
||||
}
|
||||
|
||||
std::map<PackageId, ReleaseRecord> chosen;
|
||||
if (backtrack(constraints, chosen)) {
|
||||
SolveResult out;
|
||||
for (const auto &[id, rel] : chosen) {
|
||||
SolvedPackage sp;
|
||||
sp.id = id;
|
||||
sp.version = rel.version;
|
||||
sp.source_sha256 = rel.source_sha256;
|
||||
sp.source_url = rel.source_url;
|
||||
sp.binaries = rel.binaries;
|
||||
if (const auto cit = constraints.find(id); cit != constraints.end()) {
|
||||
for (const auto &ac : cit->second) {
|
||||
for (const auto &f : ac.features) {
|
||||
sp.enabled_features.insert(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const auto &dep : rel.dependencies) {
|
||||
sp.dependencies.push_back(dep.target);
|
||||
}
|
||||
std::ranges::sort(sp.dependencies);
|
||||
sp.dependencies.erase(std::unique(sp.dependencies.begin(), sp.dependencies.end()),
|
||||
sp.dependencies.end());
|
||||
out.packages.emplace(id, std::move(sp));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string report = "dependency version resolution failed:\n";
|
||||
if (conflicts_.empty()) {
|
||||
report += " no satisfiable version assignment found within solver step budget";
|
||||
} else {
|
||||
const std::size_t shown = std::min<std::size_t>(conflicts_.size(), 8);
|
||||
for (std::size_t i = 0; i < shown; ++i) {
|
||||
report += " - " + conflicts_[i] + "\n";
|
||||
}
|
||||
}
|
||||
return std::unexpected{solve_err(std::move(report))};
|
||||
}
|
||||
|
||||
private:
|
||||
bool matches_all(const Void::Semver::Version &v,
|
||||
const std::vector<ActiveConstraint> &list) const {
|
||||
for (const auto &c : list) {
|
||||
if (!c.range.contains(v)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<ReleaseRecord> ordered_candidates(const PackageId &id,
|
||||
const std::vector<ActiveConstraint> &list) const {
|
||||
auto all = index_.releases_for(id);
|
||||
std::vector<ReleaseRecord> matching;
|
||||
const auto pin_it = options_.pinned_versions.find(id);
|
||||
|
||||
for (auto &rel : all) {
|
||||
const bool is_pinned =
|
||||
(pin_it != options_.pinned_versions.end() && rel.version == pin_it->second);
|
||||
if (rel.yanked && !(is_pinned && options_.allow_yanked_if_pinned)) {
|
||||
continue;
|
||||
}
|
||||
if (matches_all(rel.version, list)) {
|
||||
matching.push_back(std::move(rel));
|
||||
}
|
||||
}
|
||||
|
||||
// Deterministic priority: pinned compatible version first, then highest SemVer descending.
|
||||
std::ranges::sort(matching, [&](const ReleaseRecord &a, const ReleaseRecord &b) {
|
||||
const bool a_pin =
|
||||
(pin_it != options_.pinned_versions.end() && a.version == pin_it->second);
|
||||
const bool b_pin =
|
||||
(pin_it != options_.pinned_versions.end() && b.version == pin_it->second);
|
||||
if (a_pin != b_pin) {
|
||||
return a_pin;
|
||||
}
|
||||
return a.version > b.version;
|
||||
});
|
||||
return matching;
|
||||
}
|
||||
|
||||
void record_incompatibility(const PackageId &id, const std::vector<ActiveConstraint> &list) {
|
||||
std::string msg = "no version of " + id.format() + " satisfies: ";
|
||||
for (std::size_t i = 0; i < list.size(); ++i) {
|
||||
if (i > 0) {
|
||||
msg += " AND ";
|
||||
}
|
||||
msg += list[i].range_expr + " (from " + list[i].requirer + ")";
|
||||
}
|
||||
if (conflicts_.size() < 32 && !std::ranges::contains(conflicts_, msg)) {
|
||||
conflicts_.push_back(std::move(msg));
|
||||
}
|
||||
}
|
||||
|
||||
bool backtrack(std::map<PackageId, std::vector<ActiveConstraint>> &constraints,
|
||||
std::map<PackageId, ReleaseRecord> &chosen) {
|
||||
if (++steps_ > options_.max_steps) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Unit propagation / fail-fast check: choose undecided package with fewest candidates!
|
||||
std::optional<PackageId> next_pkg;
|
||||
std::vector<ReleaseRecord> best_candidates;
|
||||
std::size_t min_count = std::numeric_limits<std::size_t>::max();
|
||||
|
||||
for (const auto &[id, clist] : constraints) {
|
||||
if (const auto cit = chosen.find(id); cit != chosen.end()) {
|
||||
if (!matches_all(cit->second.version, clist)) {
|
||||
record_incompatibility(id, clist);
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
auto cands = ordered_candidates(id, clist);
|
||||
if (cands.empty()) {
|
||||
record_incompatibility(id, clist);
|
||||
return false;
|
||||
}
|
||||
if (cands.size() < min_count) {
|
||||
min_count = cands.size();
|
||||
next_pkg = id;
|
||||
best_candidates = std::move(cands);
|
||||
if (min_count == 1) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!next_pkg) {
|
||||
return true; // All constrained packages decided and mutually consistent!
|
||||
}
|
||||
|
||||
const PackageId pkg = *next_pkg;
|
||||
for (const auto &candidate : best_candidates) {
|
||||
// Save constraints snapshot before descending.
|
||||
auto next_constraints = constraints;
|
||||
bool valid_ranges = true;
|
||||
const std::string origin = pkg.format() + "@" + candidate.version.to_string();
|
||||
|
||||
for (const auto &dep : candidate.dependencies) {
|
||||
auto parsed = parse_semver_range_compat(dep.range_expr);
|
||||
if (!parsed) {
|
||||
valid_ranges = false;
|
||||
conflicts_.push_back(
|
||||
std::format("package {} declares invalid range '{}' for {}", origin,
|
||||
dep.range_expr, dep.target.format()));
|
||||
break;
|
||||
}
|
||||
next_constraints[dep.target].push_back(
|
||||
ActiveConstraint{*parsed, dep.range_expr, origin, dep.required_features});
|
||||
}
|
||||
if (!valid_ranges) {
|
||||
continue;
|
||||
}
|
||||
|
||||
chosen.insert_or_assign(pkg, candidate);
|
||||
if (backtrack(next_constraints, chosen)) {
|
||||
constraints = std::move(next_constraints);
|
||||
return true;
|
||||
}
|
||||
chosen.erase(pkg);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const PackageIndex &index_;
|
||||
const SolveOptions &options_;
|
||||
std::size_t steps_{0};
|
||||
std::vector<std::string> conflicts_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string PackageId::format() const {
|
||||
if (registry_authority.empty()) {
|
||||
return name;
|
||||
}
|
||||
return registry_authority + "/" + name;
|
||||
}
|
||||
|
||||
void PackageIndex::add_release(ReleaseRecord release) {
|
||||
releases_[release.id].push_back(std::move(release));
|
||||
}
|
||||
|
||||
std::vector<ReleaseRecord> PackageIndex::releases_for(const PackageId &id) const {
|
||||
const auto it = releases_.find(id);
|
||||
if (it == releases_.end()) {
|
||||
return {};
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
|
||||
Void::Result::Result<SolveResult, Void::Result::Error>
|
||||
solve_dependencies(const std::vector<DependencyConstraint> &root_constraints,
|
||||
const PackageIndex &index, const SolveOptions &options) {
|
||||
PubGrubSolver solver{index, options};
|
||||
return solver.solve(root_constraints);
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Package
|
||||
@@ -0,0 +1,949 @@
|
||||
#include <Void/Build/Package/Toml.hpp>
|
||||
|
||||
#include <Void/Build/Util/Json.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <charconv>
|
||||
#include <cmath>
|
||||
#include <format>
|
||||
#include <set>
|
||||
|
||||
namespace Void::Build::Package {
|
||||
namespace {
|
||||
|
||||
Void::Result::Error parse_err(const SourceOrigin &orig, std::string msg) {
|
||||
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("{}: {}", orig.format(), std::move(msg)));
|
||||
}
|
||||
|
||||
class TomlParser {
|
||||
public:
|
||||
TomlParser(std::string_view text, std::string source_name)
|
||||
: text_{text}, source_name_{std::move(source_name)} {}
|
||||
|
||||
Void::Result::Result<TomlTable, Void::Result::Error> parse() {
|
||||
if (!Util::is_valid_utf8(text_)) {
|
||||
return std::unexpected{parse_err({source_name_, 1, 1}, "invalid UTF-8 in TOML")};
|
||||
}
|
||||
TomlValue root = TomlValue::make_table({source_name_, 1, 1});
|
||||
TomlTable *current_table = &root.as_table_mut();
|
||||
|
||||
while (!eof()) {
|
||||
skip_ws_and_comments(true);
|
||||
if (eof()) {
|
||||
break;
|
||||
}
|
||||
if (peek() == '[') {
|
||||
const auto hdr_origin = origin();
|
||||
advance();
|
||||
const bool is_array_table = (!eof() && peek() == '[');
|
||||
if (is_array_table) {
|
||||
advance();
|
||||
}
|
||||
skip_inline_ws();
|
||||
auto keys = parse_key_path();
|
||||
if (!keys) {
|
||||
return std::unexpected{keys.error()};
|
||||
}
|
||||
skip_inline_ws();
|
||||
if (eof() || peek() != ']') {
|
||||
return std::unexpected{parse_err(origin(), "expected ']' in table header")};
|
||||
}
|
||||
advance();
|
||||
if (is_array_table) {
|
||||
if (eof() || peek() != ']') {
|
||||
return std::unexpected{
|
||||
parse_err(origin(), "expected ']]' in array-of-tables header")};
|
||||
}
|
||||
advance();
|
||||
}
|
||||
if (auto r = expect_line_end(); !r) {
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
auto tbl =
|
||||
navigate_table_header(root.as_table_mut(), *keys, is_array_table, hdr_origin);
|
||||
if (!tbl) {
|
||||
return std::unexpected{tbl.error()};
|
||||
}
|
||||
current_table = *tbl;
|
||||
} else {
|
||||
const auto kv_origin = origin();
|
||||
auto keys = parse_key_path();
|
||||
if (!keys) {
|
||||
return std::unexpected{keys.error()};
|
||||
}
|
||||
skip_inline_ws();
|
||||
if (eof() || peek() != '=') {
|
||||
return std::unexpected{parse_err(origin(), "expected '=' after key")};
|
||||
}
|
||||
advance();
|
||||
skip_inline_ws();
|
||||
auto val = parse_value();
|
||||
if (!val) {
|
||||
return std::unexpected{val.error()};
|
||||
}
|
||||
if (auto r = expect_line_end(); !r) {
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
if (auto r = insert_key_value(*current_table, *keys, std::move(*val), kv_origin);
|
||||
!r) {
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
}
|
||||
}
|
||||
return std::move(root.as_table_mut());
|
||||
}
|
||||
|
||||
private:
|
||||
bool eof() const noexcept { return pos_ >= text_.size(); }
|
||||
char peek(std::size_t off = 0) const noexcept {
|
||||
return (pos_ + off < text_.size()) ? text_[pos_ + off] : '\0';
|
||||
}
|
||||
char advance() noexcept {
|
||||
const char c = text_[pos_++];
|
||||
if (c == '\n') {
|
||||
++line_;
|
||||
col_ = 1;
|
||||
} else {
|
||||
++col_;
|
||||
}
|
||||
return c;
|
||||
}
|
||||
SourceOrigin origin() const { return {source_name_, line_, col_}; }
|
||||
|
||||
void skip_inline_ws() noexcept {
|
||||
while (!eof() && (peek() == ' ' || peek() == '\t')) {
|
||||
advance();
|
||||
}
|
||||
}
|
||||
|
||||
void skip_ws_and_comments(bool allow_newlines) noexcept {
|
||||
while (!eof()) {
|
||||
const char c = peek();
|
||||
if (c == ' ' || c == '\t' || (allow_newlines && (c == '\n' || c == '\r'))) {
|
||||
advance();
|
||||
} else if (c == '#') {
|
||||
while (!eof() && peek() != '\n') {
|
||||
advance();
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error> expect_line_end() {
|
||||
skip_inline_ws();
|
||||
if (!eof() && peek() == '#') {
|
||||
while (!eof() && peek() != '\n') {
|
||||
advance();
|
||||
}
|
||||
}
|
||||
if (eof()) {
|
||||
return {};
|
||||
}
|
||||
if (peek() == '\r') {
|
||||
advance();
|
||||
}
|
||||
if (eof() || peek() == '\n') {
|
||||
if (!eof()) {
|
||||
advance();
|
||||
}
|
||||
return {};
|
||||
}
|
||||
return std::unexpected{parse_err(origin(), "unexpected trailing characters on line")};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string, Void::Result::Error> parse_basic_string(bool multiline) {
|
||||
const auto start = origin();
|
||||
if (multiline && !eof() && (peek() == '\n' || (peek() == '\r' && peek(1) == '\n'))) {
|
||||
if (peek() == '\r') {
|
||||
advance();
|
||||
}
|
||||
advance();
|
||||
}
|
||||
std::string out;
|
||||
while (!eof()) {
|
||||
if (multiline && peek() == '"' && peek(1) == '"' && peek(2) == '"') {
|
||||
advance();
|
||||
advance();
|
||||
advance();
|
||||
return out;
|
||||
}
|
||||
if (!multiline && peek() == '"') {
|
||||
advance();
|
||||
return out;
|
||||
}
|
||||
const char c = advance();
|
||||
if (!multiline && (c == '\n' || c == '\r')) {
|
||||
return std::unexpected{parse_err(start, "unterminated basic string")};
|
||||
}
|
||||
if (c == '\\') {
|
||||
if (eof()) {
|
||||
return std::unexpected{parse_err(origin(), "unterminated escape sequence")};
|
||||
}
|
||||
const char esc = advance();
|
||||
switch (esc) {
|
||||
case 'b':
|
||||
out.push_back('\b');
|
||||
break;
|
||||
case 't':
|
||||
out.push_back('\t');
|
||||
break;
|
||||
case 'n':
|
||||
out.push_back('\n');
|
||||
break;
|
||||
case 'f':
|
||||
out.push_back('\f');
|
||||
break;
|
||||
case 'r':
|
||||
out.push_back('\r');
|
||||
break;
|
||||
case '"':
|
||||
out.push_back('"');
|
||||
break;
|
||||
case '\\':
|
||||
out.push_back('\\');
|
||||
break;
|
||||
case '\n':
|
||||
case '\r':
|
||||
case ' ':
|
||||
case '\t':
|
||||
if (!multiline) {
|
||||
return std::unexpected{parse_err(origin(), "invalid escape in string")};
|
||||
}
|
||||
while (!eof() &&
|
||||
(peek() == ' ' || peek() == '\t' || peek() == '\n' || peek() == '\r')) {
|
||||
advance();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
return std::unexpected{
|
||||
parse_err(origin(), std::format("unsupported escape '\\{}'", esc))};
|
||||
}
|
||||
} else {
|
||||
out.push_back(c);
|
||||
}
|
||||
}
|
||||
return std::unexpected{parse_err(start, "unterminated string literal")};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string, Void::Result::Error> parse_literal_string(bool multiline) {
|
||||
const auto start = origin();
|
||||
if (multiline && !eof() && (peek() == '\n' || (peek() == '\r' && peek(1) == '\n'))) {
|
||||
if (peek() == '\r') {
|
||||
advance();
|
||||
}
|
||||
advance();
|
||||
}
|
||||
std::string out;
|
||||
while (!eof()) {
|
||||
if (multiline && peek() == '\'' && peek(1) == '\'' && peek(2) == '\'') {
|
||||
advance();
|
||||
advance();
|
||||
advance();
|
||||
return out;
|
||||
}
|
||||
if (!multiline && peek() == '\'') {
|
||||
advance();
|
||||
return out;
|
||||
}
|
||||
const char c = advance();
|
||||
if (!multiline && (c == '\n' || c == '\r')) {
|
||||
return std::unexpected{parse_err(start, "unterminated literal string")};
|
||||
}
|
||||
out.push_back(c);
|
||||
}
|
||||
return std::unexpected{parse_err(start, "unterminated literal string")};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string, Void::Result::Error> parse_single_key() {
|
||||
skip_inline_ws();
|
||||
if (eof()) {
|
||||
return std::unexpected{parse_err(origin(), "expected key")};
|
||||
}
|
||||
if (peek() == '"') {
|
||||
advance();
|
||||
return parse_basic_string(false);
|
||||
}
|
||||
if (peek() == '\'') {
|
||||
advance();
|
||||
return parse_literal_string(false);
|
||||
}
|
||||
std::string key;
|
||||
while (!eof()) {
|
||||
const char c = peek();
|
||||
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
||||
c == '_' || c == '-') {
|
||||
key.push_back(advance());
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (key.empty()) {
|
||||
return std::unexpected{parse_err(origin(), "empty or invalid bare key")};
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::vector<std::string>, Void::Result::Error> parse_key_path() {
|
||||
std::vector<std::string> parts;
|
||||
auto first = parse_single_key();
|
||||
if (!first) {
|
||||
return std::unexpected{first.error()};
|
||||
}
|
||||
parts.push_back(std::move(*first));
|
||||
for (;;) {
|
||||
skip_inline_ws();
|
||||
if (!eof() && peek() == '.') {
|
||||
advance();
|
||||
auto next = parse_single_key();
|
||||
if (!next) {
|
||||
return std::unexpected{next.error()};
|
||||
}
|
||||
parts.push_back(std::move(*next));
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
Void::Result::Result<TomlValue, Void::Result::Error> parse_value() {
|
||||
skip_inline_ws();
|
||||
const auto start = origin();
|
||||
if (eof()) {
|
||||
return std::unexpected{parse_err(start, "expected value")};
|
||||
}
|
||||
const char c = peek();
|
||||
if (c == '"') {
|
||||
if (peek(1) == '"' && peek(2) == '"') {
|
||||
advance();
|
||||
advance();
|
||||
advance();
|
||||
auto s = parse_basic_string(true);
|
||||
if (!s) {
|
||||
return std::unexpected{s.error()};
|
||||
}
|
||||
return TomlValue{std::move(*s), start};
|
||||
}
|
||||
advance();
|
||||
auto s = parse_basic_string(false);
|
||||
if (!s) {
|
||||
return std::unexpected{s.error()};
|
||||
}
|
||||
return TomlValue{std::move(*s), start};
|
||||
}
|
||||
if (c == '\'') {
|
||||
if (peek(1) == '\'' && peek(2) == '\'') {
|
||||
advance();
|
||||
advance();
|
||||
advance();
|
||||
auto s = parse_literal_string(true);
|
||||
if (!s) {
|
||||
return std::unexpected{s.error()};
|
||||
}
|
||||
return TomlValue{std::move(*s), start};
|
||||
}
|
||||
advance();
|
||||
auto s = parse_literal_string(false);
|
||||
if (!s) {
|
||||
return std::unexpected{s.error()};
|
||||
}
|
||||
return TomlValue{std::move(*s), start};
|
||||
}
|
||||
if (c == '[') {
|
||||
return parse_array();
|
||||
}
|
||||
if (c == '{') {
|
||||
return parse_inline_table();
|
||||
}
|
||||
|
||||
// Read scalar token (bool, int, float).
|
||||
std::string token;
|
||||
while (!eof()) {
|
||||
const char ch = peek();
|
||||
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' || ch == '#' || ch == ',' ||
|
||||
ch == ']' || ch == '}') {
|
||||
break;
|
||||
}
|
||||
token.push_back(advance());
|
||||
}
|
||||
if (token == "true") {
|
||||
return TomlValue{true, start};
|
||||
}
|
||||
if (token == "false") {
|
||||
return TomlValue{false, start};
|
||||
}
|
||||
|
||||
std::string clean;
|
||||
for (const char ch : token) {
|
||||
if (ch != '_') {
|
||||
clean.push_back(ch);
|
||||
}
|
||||
}
|
||||
if (clean.empty()) {
|
||||
return std::unexpected{parse_err(start, "empty scalar value")};
|
||||
}
|
||||
|
||||
// Integer (hex/oct/bin/dec).
|
||||
const bool looks_float = clean.find('.') != std::string::npos ||
|
||||
clean.find('e') != std::string::npos ||
|
||||
clean.find('E') != std::string::npos;
|
||||
if (!looks_float) {
|
||||
int base = 10;
|
||||
std::string_view digits{clean};
|
||||
if (digits.starts_with("0x")) {
|
||||
base = 16;
|
||||
digits.remove_prefix(2);
|
||||
} else if (digits.starts_with("0o")) {
|
||||
base = 8;
|
||||
digits.remove_prefix(2);
|
||||
} else if (digits.starts_with("0b")) {
|
||||
base = 2;
|
||||
digits.remove_prefix(2);
|
||||
} else if (digits.starts_with("+")) {
|
||||
digits.remove_prefix(1);
|
||||
}
|
||||
std::int64_t iv = 0;
|
||||
const auto [ptr, ec] =
|
||||
std::from_chars(digits.data(), digits.data() + digits.size(), iv, base);
|
||||
if (ec == std::errc{} && ptr == digits.data() + digits.size()) {
|
||||
return TomlValue{iv, start};
|
||||
}
|
||||
}
|
||||
double dv = 0.0;
|
||||
const auto [ptr, ec] = std::from_chars(clean.data(), clean.data() + clean.size(), dv);
|
||||
if (ec == std::errc{} && ptr == clean.data() + clean.size()) {
|
||||
return TomlValue{dv, start};
|
||||
}
|
||||
return std::unexpected{parse_err(start, std::format("invalid TOML value '{}'", token))};
|
||||
}
|
||||
|
||||
Void::Result::Result<TomlValue, Void::Result::Error> parse_array() {
|
||||
const auto start = origin();
|
||||
advance(); // '['
|
||||
TomlValue arr = TomlValue::make_array(start);
|
||||
for (;;) {
|
||||
skip_ws_and_comments(true);
|
||||
if (eof()) {
|
||||
return std::unexpected{parse_err(start, "unterminated array")};
|
||||
}
|
||||
if (peek() == ']') {
|
||||
advance();
|
||||
return arr;
|
||||
}
|
||||
auto elem = parse_value();
|
||||
if (!elem) {
|
||||
return std::unexpected{elem.error()};
|
||||
}
|
||||
arr.as_array_mut().push_back(std::move(*elem));
|
||||
skip_ws_and_comments(true);
|
||||
if (!eof() && peek() == ',') {
|
||||
advance();
|
||||
continue;
|
||||
}
|
||||
if (!eof() && peek() == ']') {
|
||||
advance();
|
||||
return arr;
|
||||
}
|
||||
return std::unexpected{parse_err(origin(), "expected ',' or ']' in array")};
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<TomlValue, Void::Result::Error> parse_inline_table() {
|
||||
const auto start = origin();
|
||||
advance(); // '{'
|
||||
TomlValue tbl = TomlValue::make_table(start);
|
||||
skip_inline_ws();
|
||||
if (!eof() && peek() == '}') {
|
||||
advance();
|
||||
return tbl;
|
||||
}
|
||||
for (;;) {
|
||||
skip_inline_ws();
|
||||
const auto kv_origin = origin();
|
||||
auto keys = parse_key_path();
|
||||
if (!keys) {
|
||||
return std::unexpected{keys.error()};
|
||||
}
|
||||
skip_inline_ws();
|
||||
if (eof() || peek() != '=') {
|
||||
return std::unexpected{parse_err(origin(), "expected '=' in inline table")};
|
||||
}
|
||||
advance();
|
||||
auto val = parse_value();
|
||||
if (!val) {
|
||||
return std::unexpected{val.error()};
|
||||
}
|
||||
if (auto r = insert_key_value(tbl.as_table_mut(), *keys, std::move(*val), kv_origin);
|
||||
!r) {
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
skip_inline_ws();
|
||||
if (!eof() && peek() == ',') {
|
||||
advance();
|
||||
continue;
|
||||
}
|
||||
if (!eof() && peek() == '}') {
|
||||
advance();
|
||||
return tbl;
|
||||
}
|
||||
return std::unexpected{parse_err(origin(), "expected ',' or '}' in inline table")};
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<TomlTable *, Void::Result::Error>
|
||||
navigate_table_header(TomlTable &root, const std::vector<std::string> &keys,
|
||||
bool is_array_table, const SourceOrigin &hdr_origin) {
|
||||
TomlTable *cur = &root;
|
||||
for (std::size_t i = 0; i + 1 < keys.size(); ++i) {
|
||||
const auto &k = keys[i];
|
||||
auto it = cur->find(k);
|
||||
if (it == cur->end()) {
|
||||
it = cur->emplace(k, TomlValue::make_table(hdr_origin)).first;
|
||||
}
|
||||
if (it->second.is_table()) {
|
||||
cur = &it->second.as_table_mut();
|
||||
} else if (it->second.is_array() && !it->second.as_array().empty() &&
|
||||
it->second.as_array().back().is_table()) {
|
||||
cur = &it->second.as_array_mut().back().as_table_mut();
|
||||
} else {
|
||||
return std::unexpected{
|
||||
parse_err(hdr_origin, std::format("key '{}' is not a table", k))};
|
||||
}
|
||||
}
|
||||
const auto &last = keys.back();
|
||||
if (is_array_table) {
|
||||
auto it = cur->find(last);
|
||||
if (it == cur->end()) {
|
||||
it = cur->emplace(last, TomlValue::make_array(hdr_origin)).first;
|
||||
}
|
||||
if (!it->second.is_array()) {
|
||||
return std::unexpected{parse_err(
|
||||
hdr_origin, std::format("key '{}' cannot be redefined as array table", last))};
|
||||
}
|
||||
it->second.as_array_mut().push_back(TomlValue::make_table(hdr_origin));
|
||||
return &it->second.as_array_mut().back().as_table_mut();
|
||||
}
|
||||
auto it = cur->find(last);
|
||||
if (it == cur->end()) {
|
||||
it = cur->emplace(last, TomlValue::make_table(hdr_origin)).first;
|
||||
}
|
||||
if (!it->second.is_table()) {
|
||||
return std::unexpected{
|
||||
parse_err(hdr_origin, std::format("key '{}' already defined as non-table", last))};
|
||||
}
|
||||
std::string full_header;
|
||||
for (std::size_t i = 0; i < keys.size(); ++i) {
|
||||
if (i > 0) {
|
||||
full_header += '.';
|
||||
}
|
||||
full_header += keys[i];
|
||||
}
|
||||
if (!explicit_tables_.insert(full_header).second) {
|
||||
return std::unexpected{
|
||||
parse_err(hdr_origin, std::format("duplicate table header [{}]", full_header))};
|
||||
}
|
||||
return &it->second.as_table_mut();
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error>
|
||||
insert_key_value(TomlTable &table, const std::vector<std::string> &keys, TomlValue val,
|
||||
const SourceOrigin &kv_origin) {
|
||||
TomlTable *cur = &table;
|
||||
for (std::size_t i = 0; i + 1 < keys.size(); ++i) {
|
||||
const auto &k = keys[i];
|
||||
auto it = cur->find(k);
|
||||
if (it == cur->end()) {
|
||||
it = cur->emplace(k, TomlValue::make_table(kv_origin)).first;
|
||||
}
|
||||
if (!it->second.is_table()) {
|
||||
return std::unexpected{
|
||||
parse_err(kv_origin, std::format("cannot index into non-table key '{}'", k))};
|
||||
}
|
||||
cur = &it->second.as_table_mut();
|
||||
}
|
||||
const auto &leaf = keys.back();
|
||||
if (cur->contains(leaf)) {
|
||||
return std::unexpected{
|
||||
parse_err(kv_origin, std::format("duplicate TOML key '{}'", leaf))};
|
||||
}
|
||||
cur->emplace(leaf, std::move(val));
|
||||
return {};
|
||||
}
|
||||
|
||||
std::string_view text_;
|
||||
std::string source_name_;
|
||||
std::size_t pos_{0};
|
||||
std::size_t line_{1};
|
||||
std::size_t col_{1};
|
||||
std::set<std::string> explicit_tables_;
|
||||
};
|
||||
|
||||
std::string toml_quote_key(std::string_view key) {
|
||||
bool bare_ok = !key.empty();
|
||||
for (const char c : key) {
|
||||
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
||||
c == '_' || c == '-')) {
|
||||
bare_ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return bare_ok ? std::string{key} : Util::json_quote(key);
|
||||
}
|
||||
|
||||
std::string serialize_scalar_or_inline(const TomlValue &v) {
|
||||
if (v.is_string()) {
|
||||
return Util::json_quote(v.as_string());
|
||||
}
|
||||
if (v.is_bool()) {
|
||||
return v.as_bool() ? "true" : "false";
|
||||
}
|
||||
if (v.is_int()) {
|
||||
return std::to_string(v.as_int());
|
||||
}
|
||||
if (v.is_double()) {
|
||||
return std::format("{}", v.as_double());
|
||||
}
|
||||
if (v.is_array()) {
|
||||
std::string out{"["};
|
||||
const auto &arr = v.as_array();
|
||||
for (std::size_t i = 0; i < arr.size(); ++i) {
|
||||
if (i > 0) {
|
||||
out += ", ";
|
||||
}
|
||||
out += serialize_scalar_or_inline(arr[i]);
|
||||
}
|
||||
out += "]";
|
||||
return out;
|
||||
}
|
||||
std::string out{"{"};
|
||||
bool first = true;
|
||||
for (const auto &[k, val] : v.as_table()) {
|
||||
if (!first) {
|
||||
out += ", ";
|
||||
}
|
||||
first = false;
|
||||
out += toml_quote_key(k) + " = " + serialize_scalar_or_inline(val);
|
||||
}
|
||||
out += "}";
|
||||
return out;
|
||||
}
|
||||
|
||||
void serialize_table_section(const TomlTable &tbl, const std::string &prefix, std::string &out) {
|
||||
// Scalars & arrays first.
|
||||
for (const auto &[k, v] : tbl) {
|
||||
if (!v.is_table()) {
|
||||
out += toml_quote_key(k) + " = " + serialize_scalar_or_inline(v) + "\n";
|
||||
}
|
||||
}
|
||||
// Nested subtables next.
|
||||
for (const auto &[k, v] : tbl) {
|
||||
if (v.is_table()) {
|
||||
const std::string header =
|
||||
prefix.empty() ? toml_quote_key(k) : (prefix + "." + toml_quote_key(k));
|
||||
out += "\n[" + header + "]\n";
|
||||
serialize_table_section(v.as_table(), header, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool option_value_equal(const OptionValue &a, const OptionValue &b) { return a.value == b.value; }
|
||||
|
||||
bool dependency_records_equal(const DependencyRecord &a, const DependencyRecord &b) {
|
||||
if (a.source_kind != b.source_kind || a.location != b.location || a.revision != b.revision ||
|
||||
a.package != b.package || a.version != b.version || a.builder != b.builder ||
|
||||
a.registry_authority != b.registry_authority || a.sha256 != b.sha256 ||
|
||||
a.features != b.features || a.build_dependency != b.build_dependency ||
|
||||
a.options.size() != b.options.size()) {
|
||||
return false;
|
||||
}
|
||||
for (const auto &[k, av] : a.options) {
|
||||
const auto bit = b.options.find(k);
|
||||
if (bit == b.options.end() || !option_value_equal(av, bit->second)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string SourceOrigin::format() const {
|
||||
if (line == 0) {
|
||||
return file.empty() ? "<unknown>" : file;
|
||||
}
|
||||
return std::format("{}:{}:{}", file, line, column);
|
||||
}
|
||||
|
||||
TomlValue TomlValue::make_table(SourceOrigin origin) {
|
||||
return TomlValue{std::make_shared<TomlTable>(), std::move(origin)};
|
||||
}
|
||||
|
||||
TomlValue TomlValue::make_array(SourceOrigin origin) {
|
||||
return TomlValue{std::make_shared<TomlArray>(), std::move(origin)};
|
||||
}
|
||||
|
||||
Void::Result::Result<TomlTable, Void::Result::Error> parse_toml(std::string_view text,
|
||||
std::string_view source_name) {
|
||||
TomlParser parser{text, std::string{source_name}};
|
||||
return parser.parse();
|
||||
}
|
||||
|
||||
Void::Result::Result<TomlTable, Void::Result::Error>
|
||||
parse_toml_file(const std::filesystem::path &path) {
|
||||
auto content = Void::FileSystem::read_file(path);
|
||||
if (!content) {
|
||||
return std::unexpected{content.error()};
|
||||
}
|
||||
return parse_toml(*content, path.string());
|
||||
}
|
||||
|
||||
std::string serialize_toml(const TomlTable &table) {
|
||||
std::string out;
|
||||
serialize_table_section(table, "", out);
|
||||
return out;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::vector<NormalizedDependency>, Void::Result::Error>
|
||||
load_dependencies_toml(const std::filesystem::path &toml_path) {
|
||||
auto root_res = parse_toml_file(toml_path);
|
||||
if (!root_res) {
|
||||
return std::unexpected{root_res.error()};
|
||||
}
|
||||
const auto &root = *root_res;
|
||||
|
||||
// Validate top-level keys (reject unknown fields explicitly!).
|
||||
for (const auto &[k, v] : root) {
|
||||
if (k != "dependencies" && k != "build_dependencies" && k != "registries") {
|
||||
return std::unexpected{parse_err(
|
||||
v.origin, std::format("unknown top-level key '{}' in dependency manifest", k))};
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<NormalizedDependency> out;
|
||||
auto parse_dep_section =
|
||||
[&](const std::string §ion_key,
|
||||
bool is_build_dep) -> Void::Result::Result<void, Void::Result::Error> {
|
||||
const auto sec_it = root.find(section_key);
|
||||
if (sec_it == root.end()) {
|
||||
return {};
|
||||
}
|
||||
if (!sec_it->second.is_table()) {
|
||||
return std::unexpected{
|
||||
parse_err(sec_it->second.origin, std::format("'{}' must be a table", section_key))};
|
||||
}
|
||||
for (const auto &[alias, dep_val] : sec_it->second.as_table()) {
|
||||
if (!dep_val.is_table()) {
|
||||
return std::unexpected{parse_err(
|
||||
dep_val.origin, std::format("dependency '{}' must be a table", alias))};
|
||||
}
|
||||
const auto &dtbl = dep_val.as_table();
|
||||
DependencyRecord rec;
|
||||
rec.name = alias;
|
||||
rec.build_dependency = is_build_dep;
|
||||
|
||||
static const std::set<std::string_view> kAllowedFields{
|
||||
"git", "rev", "path", "archive", "sha256", "package", "version",
|
||||
"conan", "builder", "options", "registry", "features", "build_dependency"};
|
||||
for (const auto &[fk, fv] : dtbl) {
|
||||
if (!kAllowedFields.contains(fk)) {
|
||||
return std::unexpected{
|
||||
parse_err(fv.origin,
|
||||
std::format("unknown field '{}' in dependency '{}'", fk, alias))};
|
||||
}
|
||||
}
|
||||
|
||||
int source_count = 0;
|
||||
if (const auto it = dtbl.find("git"); it != dtbl.end()) {
|
||||
++source_count;
|
||||
if (!it->second.is_string()) {
|
||||
return std::unexpected{parse_err(it->second.origin, "'git' must be a string")};
|
||||
}
|
||||
const auto rev_it = dtbl.find("rev");
|
||||
if (rev_it == dtbl.end() || !rev_it->second.is_string()) {
|
||||
return std::unexpected{
|
||||
parse_err(dep_val.origin,
|
||||
std::format("git dependency '{}' requires 40-hex 'rev'", alias))};
|
||||
}
|
||||
const auto &rev = rev_it->second.as_string();
|
||||
if (rev.size() != 40 || !std::ranges::all_of(rev, [](char c) {
|
||||
return std::isxdigit(static_cast<unsigned char>(c)) != 0;
|
||||
})) {
|
||||
return std::unexpected{parse_err(
|
||||
rev_it->second.origin, "git 'rev' must be an exact 40-hex commit SHA")};
|
||||
}
|
||||
rec.source_kind = DependencySourceKind::Git;
|
||||
rec.location = it->second.as_string();
|
||||
rec.revision = rev;
|
||||
}
|
||||
if (const auto it = dtbl.find("package"); it != dtbl.end()) {
|
||||
++source_count;
|
||||
if (!it->second.is_string()) {
|
||||
return std::unexpected{
|
||||
parse_err(it->second.origin, "'package' must be a string")};
|
||||
}
|
||||
const auto ver_it = dtbl.find("version");
|
||||
if (ver_it == dtbl.end() || !ver_it->second.is_string()) {
|
||||
return std::unexpected{parse_err(
|
||||
dep_val.origin,
|
||||
std::format("package dependency '{}' requires 'version'", alias))};
|
||||
}
|
||||
rec.source_kind = DependencySourceKind::Package;
|
||||
rec.package = it->second.as_string();
|
||||
rec.version = ver_it->second.as_string();
|
||||
}
|
||||
if (const auto it = dtbl.find("path"); it != dtbl.end()) {
|
||||
++source_count;
|
||||
if (!it->second.is_string()) {
|
||||
return std::unexpected{parse_err(it->second.origin, "'path' must be a string")};
|
||||
}
|
||||
rec.source_kind = DependencySourceKind::Path;
|
||||
rec.location = it->second.as_string();
|
||||
}
|
||||
if (const auto it = dtbl.find("archive"); it != dtbl.end()) {
|
||||
++source_count;
|
||||
if (!it->second.is_string()) {
|
||||
return std::unexpected{
|
||||
parse_err(it->second.origin, "'archive' must be a string")};
|
||||
}
|
||||
const auto sha_it = dtbl.find("sha256");
|
||||
if (sha_it == dtbl.end() || !sha_it->second.is_string() ||
|
||||
sha_it->second.as_string().size() != 64) {
|
||||
return std::unexpected{parse_err(
|
||||
dep_val.origin,
|
||||
std::format("archive dependency '{}' requires 64-hex 'sha256'", alias))};
|
||||
}
|
||||
rec.source_kind = DependencySourceKind::Archive;
|
||||
rec.location = it->second.as_string();
|
||||
rec.sha256 = sha_it->second.as_string();
|
||||
}
|
||||
if (const auto it = dtbl.find("conan"); it != dtbl.end()) {
|
||||
++source_count;
|
||||
if (!it->second.is_string()) {
|
||||
return std::unexpected{
|
||||
parse_err(it->second.origin, "'conan' must be a string")};
|
||||
}
|
||||
rec.source_kind = DependencySourceKind::Conan;
|
||||
rec.package = it->second.as_string();
|
||||
rec.builder = "conan";
|
||||
}
|
||||
|
||||
if (source_count != 1) {
|
||||
return std::unexpected{parse_err(
|
||||
dep_val.origin, std::format("dependency '{}' must specify exactly one source "
|
||||
"(git/package/path/archive/conan)",
|
||||
alias))};
|
||||
}
|
||||
|
||||
if (const auto it = dtbl.find("builder"); it != dtbl.end()) {
|
||||
if (!it->second.is_string()) {
|
||||
return std::unexpected{
|
||||
parse_err(it->second.origin, "'builder' must be a string")};
|
||||
}
|
||||
const auto &b = it->second.as_string();
|
||||
if (b != "cmake" && b != "meson" && b != "conan" && b != "native") {
|
||||
return std::unexpected{
|
||||
parse_err(it->second.origin, std::format("unsupported builder '{}'", b))};
|
||||
}
|
||||
if (rec.source_kind == DependencySourceKind::Package && b != "native") {
|
||||
return std::unexpected{parse_err(
|
||||
it->second.origin, "contradictory builder on native package dependency")};
|
||||
}
|
||||
rec.builder = b;
|
||||
}
|
||||
if (const auto it = dtbl.find("registry"); it != dtbl.end()) {
|
||||
if (!it->second.is_string()) {
|
||||
return std::unexpected{
|
||||
parse_err(it->second.origin, "'registry' must be a string")};
|
||||
}
|
||||
rec.registry_authority = it->second.as_string();
|
||||
}
|
||||
if (const auto it = dtbl.find("build_dependency"); it != dtbl.end()) {
|
||||
if (!it->second.is_bool()) {
|
||||
return std::unexpected{
|
||||
parse_err(it->second.origin, "'build_dependency' must be a bool")};
|
||||
}
|
||||
rec.build_dependency = it->second.as_bool();
|
||||
}
|
||||
if (const auto it = dtbl.find("features"); it != dtbl.end()) {
|
||||
if (!it->second.is_array()) {
|
||||
return std::unexpected{
|
||||
parse_err(it->second.origin, "'features' must be an array of strings")};
|
||||
}
|
||||
for (const auto &fv : it->second.as_array()) {
|
||||
if (!fv.is_string()) {
|
||||
return std::unexpected{
|
||||
parse_err(fv.origin, "feature entry must be a string")};
|
||||
}
|
||||
rec.features.push_back(fv.as_string());
|
||||
}
|
||||
}
|
||||
if (const auto it = dtbl.find("options"); it != dtbl.end()) {
|
||||
if (!it->second.is_table()) {
|
||||
return std::unexpected{
|
||||
parse_err(it->second.origin, "'options' must be a table")};
|
||||
}
|
||||
for (const auto &[ok, ov] : it->second.as_table()) {
|
||||
if (ov.is_string()) {
|
||||
rec.options.emplace(ok, OptionValue{ov.as_string()});
|
||||
} else if (ov.is_bool()) {
|
||||
rec.options.emplace(ok, OptionValue{ov.as_bool()});
|
||||
} else if (ov.is_int()) {
|
||||
rec.options.emplace(ok, OptionValue{ov.as_int()});
|
||||
} else {
|
||||
return std::unexpected{parse_err(
|
||||
ov.origin,
|
||||
std::format("option '{}' must be string, bool, or integer", ok))};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
out.push_back(NormalizedDependency{std::move(rec), dep_val.origin});
|
||||
}
|
||||
return {};
|
||||
};
|
||||
|
||||
if (auto r = parse_dep_section("dependencies", false); !r) {
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
if (auto r = parse_dep_section("build_dependencies", true); !r) {
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::vector<NormalizedDependency>, Void::Result::Error>
|
||||
merge_dependencies(const std::vector<DependencyRecord> &cpp_deps,
|
||||
const std::vector<NormalizedDependency> &toml_deps) {
|
||||
std::map<std::string, NormalizedDependency, std::less<>> merged;
|
||||
for (const auto &d : cpp_deps) {
|
||||
merged.emplace(d.name, NormalizedDependency{d, SourceOrigin{"build.cpp", 0, 0}});
|
||||
}
|
||||
for (const auto &td : toml_deps) {
|
||||
const auto it = merged.find(td.record.name);
|
||||
if (it == merged.end()) {
|
||||
merged.emplace(td.record.name, td);
|
||||
continue;
|
||||
}
|
||||
if (!dependency_records_equal(it->second.record, td.record)) {
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("conflicting declaration for dependency '{}': first declared at {}, "
|
||||
"conflicting declaration at {}",
|
||||
td.record.name, it->second.origin.format(), td.origin.format()))};
|
||||
}
|
||||
}
|
||||
std::vector<NormalizedDependency> out;
|
||||
out.reserve(merged.size());
|
||||
for (auto &[k, v] : merged) {
|
||||
out.push_back(std::move(v));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Package
|
||||
@@ -0,0 +1,444 @@
|
||||
#include <Void/Build/Platform/FileOps.hpp>
|
||||
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cerrno>
|
||||
#include <fcntl.h>
|
||||
#include <format>
|
||||
#include <linux/fs.h>
|
||||
#include <set>
|
||||
#include <sys/file.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Build::Platform {
|
||||
namespace {
|
||||
|
||||
std::atomic<std::uint64_t> g_temp_seq{0};
|
||||
|
||||
std::string unique_suffix() {
|
||||
const auto seq = g_temp_seq.fetch_add(1, std::memory_order_relaxed);
|
||||
return std::format(".vbs_tmp_{}_{}", static_cast<long long>(::getpid()), seq);
|
||||
}
|
||||
|
||||
Void::Result::Error sys_err(int err, std::string message) {
|
||||
return Void::System::make_system_error(Void::System::map_errno_to_system_code(err),
|
||||
std::move(message), err);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
FileLock::~FileLock() noexcept { release(); }
|
||||
|
||||
FileLock::FileLock(FileLock &&other) noexcept : fd_{std::exchange(other.fd_, -1)} {}
|
||||
|
||||
FileLock &FileLock::operator=(FileLock &&other) noexcept {
|
||||
if (this != &other) {
|
||||
release();
|
||||
fd_ = std::exchange(other.fd_, -1);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
void FileLock::release() noexcept {
|
||||
if (fd_ >= 0) {
|
||||
(void)::flock(fd_, LOCK_UN);
|
||||
(void)::close(fd_);
|
||||
fd_ = -1;
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<FileLock, Void::Result::Error>
|
||||
FileLock::acquire(const std::filesystem::path &lock_path, LockMode mode, bool non_blocking) {
|
||||
std::error_code ec;
|
||||
if (lock_path.has_parent_path()) {
|
||||
std::filesystem::create_directories(lock_path.parent_path(), ec);
|
||||
if (ec) {
|
||||
return std::unexpected{
|
||||
sys_err(ec.value(), std::format("FileLock: failed creating parent for '{}': {}",
|
||||
lock_path.string(), ec.message()))};
|
||||
}
|
||||
}
|
||||
const int fd = ::open(lock_path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0644);
|
||||
if (fd < 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("FileLock: cannot open '{}'", lock_path.string()))};
|
||||
}
|
||||
int op = (mode == LockMode::Exclusive) ? LOCK_EX : LOCK_SH;
|
||||
if (non_blocking) {
|
||||
op |= LOCK_NB;
|
||||
}
|
||||
for (;;) {
|
||||
if (::flock(fd, op) == 0) {
|
||||
return FileLock{fd};
|
||||
}
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
const int err = errno;
|
||||
(void)::close(fd);
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("FileLock: flock failed for '{}'", lock_path.string()))};
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<FileMetadata, Void::Result::Error>
|
||||
stat_lstat(const std::filesystem::path &path) {
|
||||
struct stat st{};
|
||||
if (::lstat(path.c_str(), &st) != 0) {
|
||||
const int err = errno;
|
||||
if (err == ENOENT || err == ENOTDIR) {
|
||||
FileMetadata missing;
|
||||
missing.exists = false;
|
||||
return missing;
|
||||
}
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("stat_lstat: lstat failed for '{}'", path.string()))};
|
||||
}
|
||||
|
||||
FileMetadata meta;
|
||||
meta.exists = true;
|
||||
meta.is_regular = S_ISREG(st.st_mode);
|
||||
meta.is_directory = S_ISDIR(st.st_mode);
|
||||
meta.is_symlink = S_ISLNK(st.st_mode);
|
||||
meta.dev = static_cast<std::uint64_t>(st.st_dev);
|
||||
meta.ino = static_cast<std::uint64_t>(st.st_ino);
|
||||
meta.size = static_cast<std::uint64_t>(st.st_size);
|
||||
meta.nlink = static_cast<std::uint64_t>(st.st_nlink);
|
||||
meta.mode = static_cast<std::uint32_t>(st.st_mode & 07777u);
|
||||
meta.mtime_sec = static_cast<std::int64_t>(st.st_mtim.tv_sec);
|
||||
meta.mtime_nsec = static_cast<std::int64_t>(st.st_mtim.tv_nsec);
|
||||
|
||||
if (meta.is_symlink) {
|
||||
std::size_t buf_size =
|
||||
st.st_size > 0 ? static_cast<std::size_t>(st.st_size) + 1 : std::size_t{256};
|
||||
for (int attempt = 0; attempt < 8; ++attempt) {
|
||||
std::string target(buf_size, '\0');
|
||||
const ssize_t n = ::readlink(path.c_str(), target.data(), target.size());
|
||||
if (n < 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{sys_err(
|
||||
err, std::format("stat_lstat: readlink failed for '{}'", path.string()))};
|
||||
}
|
||||
if (static_cast<std::size_t>(n) < target.size()) {
|
||||
target.resize(static_cast<std::size_t>(n));
|
||||
meta.symlink_target = std::move(target);
|
||||
break;
|
||||
}
|
||||
buf_size *= 2;
|
||||
}
|
||||
}
|
||||
return meta;
|
||||
}
|
||||
|
||||
Void::Result::Result<bool, Void::Result::Error>
|
||||
copy_isolated(const std::filesystem::path &src, const std::filesystem::path &dst,
|
||||
std::optional<std::uint32_t> mode_override) {
|
||||
const int src_fd = ::open(src.c_str(), O_RDONLY | O_CLOEXEC);
|
||||
if (src_fd < 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("copy_isolated: cannot open source '{}'", src.string()))};
|
||||
}
|
||||
Void::System::OwnedFd src_guard{src_fd};
|
||||
|
||||
struct stat src_st{};
|
||||
if (::fstat(src_fd, &src_st) != 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("copy_isolated: fstat failed for '{}'", src.string()))};
|
||||
}
|
||||
if (!S_ISREG(src_st.st_mode)) {
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("copy_isolated: source '{}' is not a regular file", src.string()))};
|
||||
}
|
||||
|
||||
std::error_code ec;
|
||||
if (dst.has_parent_path()) {
|
||||
std::filesystem::create_directories(dst.parent_path(), ec);
|
||||
if (ec) {
|
||||
return std::unexpected{sys_err(
|
||||
ec.value(), std::format("copy_isolated: cannot create parent dir for '{}': {}",
|
||||
dst.string(), ec.message()))};
|
||||
}
|
||||
}
|
||||
|
||||
const auto mode = mode_override.value_or(static_cast<std::uint32_t>(src_st.st_mode & 0777u));
|
||||
const auto temp_path = dst.parent_path() / (dst.filename().string() + unique_suffix());
|
||||
const int dst_fd = ::open(temp_path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC,
|
||||
static_cast<mode_t>(mode));
|
||||
if (dst_fd < 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{sys_err(
|
||||
err, std::format("copy_isolated: cannot create temp '{}'", temp_path.string()))};
|
||||
}
|
||||
Void::System::OwnedFd dst_guard{dst_fd};
|
||||
auto cleanup = [&] { (void)::unlink(temp_path.c_str()); };
|
||||
|
||||
bool used_reflink = false;
|
||||
#ifdef FICLONE
|
||||
if (::ioctl(dst_fd, FICLONE, src_fd) == 0) {
|
||||
used_reflink = true;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (!used_reflink) {
|
||||
std::array<char, 65536> buf{};
|
||||
for (;;) {
|
||||
const ssize_t n = ::read(src_fd, buf.data(), buf.size());
|
||||
if (n > 0) {
|
||||
std::size_t off = 0;
|
||||
while (off < static_cast<std::size_t>(n)) {
|
||||
const ssize_t w =
|
||||
::write(dst_fd, buf.data() + off, static_cast<std::size_t>(n) - off);
|
||||
if (w < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
const int err = errno;
|
||||
cleanup();
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("copy_isolated: write failed for '{}'",
|
||||
dst.string()))};
|
||||
}
|
||||
off += static_cast<std::size_t>(w);
|
||||
}
|
||||
} else if (n == 0) {
|
||||
break;
|
||||
} else if (errno != EINTR) {
|
||||
const int err = errno;
|
||||
cleanup();
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("copy_isolated: read failed for '{}'", src.string()))};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(void)::fchmod(dst_fd, static_cast<mode_t>(mode));
|
||||
if (const auto closed = dst_guard.close(); !closed) {
|
||||
cleanup();
|
||||
return std::unexpected{closed.error()};
|
||||
}
|
||||
|
||||
if (::rename(temp_path.c_str(), dst.c_str()) != 0) {
|
||||
const int err = errno;
|
||||
cleanup();
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("copy_isolated: rename failed for '{}'", dst.string()))};
|
||||
}
|
||||
return used_reflink;
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error>
|
||||
set_canonical_mtime(const std::filesystem::path &path, std::int64_t epoch_seconds) {
|
||||
struct timespec times[2];
|
||||
times[0].tv_sec = static_cast<time_t>(epoch_seconds);
|
||||
times[0].tv_nsec = 0;
|
||||
times[1].tv_sec = static_cast<time_t>(epoch_seconds);
|
||||
times[1].tv_nsec = 0;
|
||||
if (::utimensat(AT_FDCWD, path.c_str(), times, AT_SYMLINK_NOFOLLOW) != 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{sys_err(
|
||||
err, std::format("set_canonical_mtime: utimensat failed for '{}'", path.string()))};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error>
|
||||
atomic_write_bytes(const std::filesystem::path &path, std::span<const std::byte> bytes,
|
||||
bool durable_sync, unsigned mode) {
|
||||
std::error_code ec;
|
||||
if (path.has_parent_path()) {
|
||||
std::filesystem::create_directories(path.parent_path(), ec);
|
||||
if (ec) {
|
||||
return std::unexpected{sys_err(
|
||||
ec.value(), std::format("atomic_write_bytes: create_directories failed for '{}'",
|
||||
path.string()))};
|
||||
}
|
||||
}
|
||||
Void::FileSystem::ReplaceOptions opts;
|
||||
opts.durability = durable_sync ? Void::FileSystem::ReplaceDurability::durable_sync
|
||||
: Void::FileSystem::ReplaceDurability::atomic_visibility;
|
||||
opts.mode = mode;
|
||||
auto res = Void::FileSystem::replace_file(path, bytes, opts);
|
||||
if (!res) {
|
||||
return std::unexpected{std::move(res.error().error)};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error> atomic_write_file(const std::filesystem::path &path,
|
||||
std::string_view content,
|
||||
bool durable_sync,
|
||||
unsigned mode) {
|
||||
return atomic_write_bytes(path,
|
||||
std::as_bytes(std::span<const char>{content.data(), content.size()}),
|
||||
durable_sync, mode);
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error>
|
||||
fsync_directory(const std::filesystem::path &dir_path) {
|
||||
const int fd = ::open(dir_path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("fsync_directory: open failed for '{}'", dir_path.string()))};
|
||||
}
|
||||
Void::System::OwnedFd guard{fd};
|
||||
for (;;) {
|
||||
if (::fsync(fd) == 0) {
|
||||
return {};
|
||||
}
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
const int err = errno;
|
||||
if (err == EINVAL || err == EROFS) {
|
||||
return {};
|
||||
}
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("fsync_directory: fsync failed for '{}'", dir_path.string()))};
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error>
|
||||
atomic_swap_symlink(const std::filesystem::path &link_path, const std::filesystem::path &target) {
|
||||
std::error_code ec;
|
||||
const auto parent =
|
||||
link_path.has_parent_path() ? link_path.parent_path() : std::filesystem::path{"."};
|
||||
std::filesystem::create_directories(parent, ec);
|
||||
if (ec) {
|
||||
return std::unexpected{sys_err(
|
||||
ec.value(), std::format("atomic_swap_symlink: create_directories failed for '{}'",
|
||||
parent.string()))};
|
||||
}
|
||||
const auto temp_link = parent / (link_path.filename().string() + unique_suffix());
|
||||
if (::symlink(target.c_str(), temp_link.c_str()) != 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{sys_err(
|
||||
err, std::format("atomic_swap_symlink: symlink failed for '{}'", temp_link.string()))};
|
||||
}
|
||||
if (::rename(temp_link.c_str(), link_path.c_str()) != 0) {
|
||||
const int err = errno;
|
||||
(void)::unlink(temp_link.c_str());
|
||||
return std::unexpected{sys_err(
|
||||
err, std::format("atomic_swap_symlink: rename failed for '{}'", link_path.string()))};
|
||||
}
|
||||
return fsync_directory(parent);
|
||||
}
|
||||
|
||||
bool path_is_within(const std::filesystem::path &root, const std::filesystem::path &path) {
|
||||
const auto norm_root = root.lexically_normal();
|
||||
const auto norm_path = path.lexically_normal();
|
||||
auto r_it = norm_root.begin();
|
||||
auto p_it = norm_path.begin();
|
||||
for (; r_it != norm_root.end(); ++r_it, ++p_it) {
|
||||
if (r_it->empty() || *r_it == ".") {
|
||||
continue;
|
||||
}
|
||||
if (p_it == norm_path.end() || *r_it != *p_it) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::filesystem::path, Void::Result::Error>
|
||||
resolve_confined_path(const std::filesystem::path &root, const std::filesystem::path &candidate,
|
||||
const std::vector<std::filesystem::path> &allowed_external_roots) {
|
||||
std::error_code ec;
|
||||
const auto canonical_root = std::filesystem::weakly_canonical(root, ec);
|
||||
if (ec) {
|
||||
return std::unexpected{
|
||||
sys_err(ec.value(), std::format("resolve_confined_path: cannot canonicalize root '{}'",
|
||||
root.string()))};
|
||||
}
|
||||
|
||||
std::vector<std::filesystem::path> allowed{canonical_root};
|
||||
for (const auto &ext : allowed_external_roots) {
|
||||
const auto ce = std::filesystem::weakly_canonical(ext, ec);
|
||||
if (!ec) {
|
||||
allowed.push_back(ce);
|
||||
}
|
||||
}
|
||||
|
||||
std::filesystem::path current =
|
||||
candidate.is_absolute() ? candidate : (canonical_root / candidate);
|
||||
current = current.lexically_normal();
|
||||
|
||||
// Manually walk symlinks with a strict hop budget to detect loops explicitly.
|
||||
constexpr int kMaxSymlinkHops = 40;
|
||||
int hops = 0;
|
||||
std::set<std::filesystem::path> seen;
|
||||
|
||||
for (;;) {
|
||||
std::filesystem::path acc;
|
||||
bool followed_symlink = false;
|
||||
auto it = current.begin();
|
||||
for (; it != current.end(); ++it) {
|
||||
if (*it == ".") {
|
||||
continue;
|
||||
}
|
||||
if (*it == "..") {
|
||||
acc = acc.parent_path();
|
||||
continue;
|
||||
}
|
||||
acc /= *it;
|
||||
auto meta = stat_lstat(acc);
|
||||
if (!meta) {
|
||||
return std::unexpected{meta.error()};
|
||||
}
|
||||
if (!meta->exists) {
|
||||
// Append remaining lexical components for non-existent path checks.
|
||||
++it;
|
||||
for (; it != current.end(); ++it) {
|
||||
acc /= *it;
|
||||
}
|
||||
current = acc.lexically_normal();
|
||||
break;
|
||||
}
|
||||
if (meta->is_symlink) {
|
||||
if (++hops > kMaxSymlinkHops || !seen.insert(acc).second) {
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("resolve_confined_path: symlink loop detected at '{}'",
|
||||
acc.string()),
|
||||
ELOOP)};
|
||||
}
|
||||
std::filesystem::path target_path{meta->symlink_target};
|
||||
std::filesystem::path rebuilt =
|
||||
target_path.is_absolute() ? target_path : (acc.parent_path() / target_path);
|
||||
++it;
|
||||
for (; it != current.end(); ++it) {
|
||||
rebuilt /= *it;
|
||||
}
|
||||
current = rebuilt.lexically_normal();
|
||||
followed_symlink = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!followed_symlink) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto &allowed_root : allowed) {
|
||||
if (path_is_within(allowed_root, current)) {
|
||||
return current;
|
||||
}
|
||||
}
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::SystemErrorCode::permission_denied,
|
||||
std::format("resolve_confined_path: '{}' escapes declared roots (root='{}')",
|
||||
candidate.string(), canonical_root.string()),
|
||||
EACCES)};
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Platform
|
||||
@@ -0,0 +1,530 @@
|
||||
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <csignal>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <format>
|
||||
#include <poll.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
#include <thread>
|
||||
#include <unistd.h>
|
||||
|
||||
extern char **environ;
|
||||
|
||||
namespace Void::Build::Platform {
|
||||
namespace {
|
||||
|
||||
struct ExecErrorPacket {
|
||||
int err_no{0};
|
||||
int stage{0}; // 1 = chdir, 2 = execve
|
||||
};
|
||||
|
||||
bool is_executable_file(const std::filesystem::path &p) {
|
||||
struct stat st{};
|
||||
if (::stat(p.c_str(), &st) != 0) {
|
||||
return false;
|
||||
}
|
||||
return S_ISREG(st.st_mode) && ::access(p.c_str(), X_OK) == 0;
|
||||
}
|
||||
|
||||
void set_nonblocking(int fd) noexcept {
|
||||
const int flags = ::fcntl(fd, F_GETFL, 0);
|
||||
if (flags >= 0) {
|
||||
(void)::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> build_env_strings(const ProcessEnvironment &policy) {
|
||||
std::map<std::string, std::string, std::less<>> env_map;
|
||||
if (policy.mode != EnvPolicyMode::ExplicitOnly && environ != nullptr) {
|
||||
for (char **ep = environ; *ep != nullptr; ++ep) {
|
||||
const std::string_view entry{*ep};
|
||||
const auto eq = entry.find('=');
|
||||
if (eq == std::string_view::npos) {
|
||||
continue;
|
||||
}
|
||||
const auto key = std::string{entry.substr(0, eq)};
|
||||
if (policy.mode == EnvPolicyMode::Allowlist &&
|
||||
!std::ranges::contains(policy.allowlist, key)) {
|
||||
continue;
|
||||
}
|
||||
env_map[key] = std::string{entry.substr(eq + 1)};
|
||||
}
|
||||
}
|
||||
for (const auto &k : policy.unset_keys) {
|
||||
env_map.erase(k);
|
||||
}
|
||||
for (const auto &[k, v] : policy.set_vars) {
|
||||
env_map[k] = v;
|
||||
}
|
||||
std::vector<std::string> result;
|
||||
result.reserve(env_map.size());
|
||||
for (const auto &[k, v] : env_map) {
|
||||
result.push_back(k + "=" + v);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool process_group_alive(pid_t pgid) noexcept {
|
||||
if (pgid <= 0) {
|
||||
return false;
|
||||
}
|
||||
if (::kill(-pgid, 0) == 0) {
|
||||
return true;
|
||||
}
|
||||
return errno != ESRCH;
|
||||
}
|
||||
|
||||
void reap_leader(pid_t pid, bool &reaped, int &raw_status, bool blocking) noexcept {
|
||||
if (reaped || pid <= 0) {
|
||||
return;
|
||||
}
|
||||
for (;;) {
|
||||
const pid_t r = ::waitpid(pid, &raw_status, blocking ? 0 : WNOHANG);
|
||||
if (r == pid) {
|
||||
reaped = true;
|
||||
return;
|
||||
}
|
||||
if (r == 0) {
|
||||
return;
|
||||
}
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
if (errno == ECHILD) {
|
||||
reaped = true;
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Terminates the entire process group (-pgid) and waits until every descendant
|
||||
// (even grandchildren whose group leader already exited) is gone.
|
||||
void terminate_process_group(pid_t leader_pid, pid_t pgid, bool &leader_reaped, int &raw_status,
|
||||
std::chrono::milliseconds grace) noexcept {
|
||||
if (pgid <= 0) {
|
||||
return;
|
||||
}
|
||||
const auto effective_grace = grace.count() >= 0 ? grace : std::chrono::milliseconds{200};
|
||||
(void)::kill(-pgid, SIGTERM);
|
||||
|
||||
const auto deadline = std::chrono::steady_clock::now() + effective_grace;
|
||||
while (std::chrono::steady_clock::now() < deadline) {
|
||||
reap_leader(leader_pid, leader_reaped, raw_status, false);
|
||||
if (leader_reaped && !process_group_alive(pgid)) {
|
||||
return;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
}
|
||||
|
||||
// Escalate to SIGKILL on the entire process group and verify full disappearance.
|
||||
(void)::kill(-pgid, SIGKILL);
|
||||
reap_leader(leader_pid, leader_reaped, raw_status, true);
|
||||
|
||||
const auto kill_deadline = std::chrono::steady_clock::now() + std::chrono::seconds{5};
|
||||
while (process_group_alive(pgid) && std::chrono::steady_clock::now() < kill_deadline) {
|
||||
(void)::kill(-pgid, SIGKILL);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::optional<std::filesystem::path>
|
||||
resolve_executable(const std::filesystem::path &executable,
|
||||
std::optional<std::string_view> path_override) {
|
||||
if (executable.empty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
if (executable.is_absolute() || executable.string().find('/') != std::string::npos) {
|
||||
std::error_code ec;
|
||||
const auto abs = std::filesystem::absolute(executable, ec);
|
||||
if (!ec && is_executable_file(abs)) {
|
||||
return abs.lexically_normal();
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
std::string_view path_env;
|
||||
if (path_override) {
|
||||
path_env = *path_override;
|
||||
} else if (const char *env_val = std::getenv("PATH")) {
|
||||
path_env = env_val;
|
||||
}
|
||||
std::size_t start = 0;
|
||||
while (start <= path_env.size()) {
|
||||
const auto colon = path_env.find(':', start);
|
||||
const auto segment = path_env.substr(
|
||||
start, colon == std::string_view::npos ? std::string_view::npos : colon - start);
|
||||
const std::filesystem::path dir =
|
||||
segment.empty() ? std::filesystem::path{"."} : std::filesystem::path{segment};
|
||||
const auto candidate = dir / executable;
|
||||
if (is_executable_file(candidate)) {
|
||||
std::error_code ec;
|
||||
auto abs = std::filesystem::absolute(candidate, ec);
|
||||
return ec ? candidate : abs.lexically_normal();
|
||||
}
|
||||
if (colon == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
start = colon + 1;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
Void::Result::Result<ProcessResult, Void::Result::Error>
|
||||
run_supervised(const ProcessRequest &request, std::stop_token stop) {
|
||||
if (request.executable.empty()) {
|
||||
return std::unexpected{
|
||||
Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
"run_supervised: executable path must not be empty")};
|
||||
}
|
||||
|
||||
auto env_strings = build_env_strings(request.environment);
|
||||
std::optional<std::string_view> child_path;
|
||||
for (const auto &entry : env_strings) {
|
||||
if (entry.starts_with("PATH=")) {
|
||||
child_path = std::string_view{entry}.substr(5);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
std::filesystem::path resolved_exec = request.executable;
|
||||
if (request.search_path) {
|
||||
if (auto found = resolve_executable(request.executable, child_path)) {
|
||||
resolved_exec = std::move(*found);
|
||||
}
|
||||
}
|
||||
|
||||
int stdin_pipe[2]{-1, -1};
|
||||
int stdout_pipe[2]{-1, -1};
|
||||
int stderr_pipe[2]{-1, -1};
|
||||
int err_pipe[2]{-1, -1};
|
||||
|
||||
auto close_pair = [](int p[2]) {
|
||||
if (p[0] >= 0) {
|
||||
(void)::close(p[0]);
|
||||
p[0] = -1;
|
||||
}
|
||||
if (p[1] >= 0) {
|
||||
(void)::close(p[1]);
|
||||
p[1] = -1;
|
||||
}
|
||||
};
|
||||
|
||||
if (::pipe2(stdin_pipe, O_CLOEXEC) != 0 || ::pipe2(stdout_pipe, O_CLOEXEC) != 0 ||
|
||||
::pipe2(stderr_pipe, O_CLOEXEC) != 0 || ::pipe2(err_pipe, O_CLOEXEC) != 0) {
|
||||
const int err = errno;
|
||||
close_pair(stdin_pipe);
|
||||
close_pair(stdout_pipe);
|
||||
close_pair(stderr_pipe);
|
||||
close_pair(err_pipe);
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::map_errno_to_system_code(err), "run_supervised: pipe2 failed", err)};
|
||||
}
|
||||
|
||||
std::vector<std::string> argv_storage;
|
||||
argv_storage.reserve(request.arguments.size() + 1);
|
||||
argv_storage.push_back(resolved_exec.string());
|
||||
for (const auto &arg : request.arguments) {
|
||||
argv_storage.push_back(arg);
|
||||
}
|
||||
std::vector<char *> argv_ptrs;
|
||||
argv_ptrs.reserve(argv_storage.size() + 1);
|
||||
for (auto &s : argv_storage) {
|
||||
argv_ptrs.push_back(s.data());
|
||||
}
|
||||
argv_ptrs.push_back(nullptr);
|
||||
|
||||
std::vector<char *> envp_ptrs;
|
||||
envp_ptrs.reserve(env_strings.size() + 1);
|
||||
for (auto &s : env_strings) {
|
||||
envp_ptrs.push_back(s.data());
|
||||
}
|
||||
envp_ptrs.push_back(nullptr);
|
||||
|
||||
const std::string exec_str = resolved_exec.string();
|
||||
const std::string cwd_str =
|
||||
request.working_directory ? request.working_directory->string() : std::string{};
|
||||
|
||||
const pid_t pid = ::fork();
|
||||
if (pid < 0) {
|
||||
const int err = errno;
|
||||
close_pair(stdin_pipe);
|
||||
close_pair(stdout_pipe);
|
||||
close_pair(stderr_pipe);
|
||||
close_pair(err_pipe);
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::map_errno_to_system_code(err), "run_supervised: fork failed", err)};
|
||||
}
|
||||
|
||||
if (pid == 0) {
|
||||
// Child: place into its own process group.
|
||||
(void)::setpgid(0, 0);
|
||||
// Reset signals to defaults.
|
||||
::signal(SIGINT, SIG_DFL);
|
||||
::signal(SIGTERM, SIG_DFL);
|
||||
::signal(SIGPIPE, SIG_DFL);
|
||||
|
||||
(void)::dup2(stdin_pipe[0], STDIN_FILENO);
|
||||
(void)::dup2(stdout_pipe[1], STDOUT_FILENO);
|
||||
(void)::dup2(stderr_pipe[1], STDERR_FILENO);
|
||||
|
||||
close_pair(stdin_pipe);
|
||||
close_pair(stdout_pipe);
|
||||
close_pair(stderr_pipe);
|
||||
(void)::close(err_pipe[0]);
|
||||
|
||||
if (!cwd_str.empty() && ::chdir(cwd_str.c_str()) != 0) {
|
||||
ExecErrorPacket pkt{errno, 1};
|
||||
(void)::write(err_pipe[1], &pkt, sizeof(pkt));
|
||||
::_exit(127);
|
||||
}
|
||||
|
||||
::execve(exec_str.c_str(), argv_ptrs.data(), envp_ptrs.data());
|
||||
ExecErrorPacket pkt{errno, 2};
|
||||
(void)::write(err_pipe[1], &pkt, sizeof(pkt));
|
||||
::_exit(127);
|
||||
}
|
||||
|
||||
// Parent: ensure pgid is established to avoid race with child setpgid.
|
||||
(void)::setpgid(pid, pid);
|
||||
const pid_t pgid = pid;
|
||||
|
||||
(void)::close(stdin_pipe[0]);
|
||||
(void)::close(stdout_pipe[1]);
|
||||
(void)::close(stderr_pipe[1]);
|
||||
(void)::close(err_pipe[1]);
|
||||
|
||||
int in_fd = stdin_pipe[1];
|
||||
int out_fd = stdout_pipe[0];
|
||||
int err_fd = stderr_pipe[0];
|
||||
int exec_err_fd = err_pipe[0];
|
||||
|
||||
set_nonblocking(in_fd);
|
||||
set_nonblocking(out_fd);
|
||||
set_nonblocking(err_fd);
|
||||
|
||||
if (request.stdin_data.empty()) {
|
||||
(void)::close(in_fd);
|
||||
in_fd = -1;
|
||||
}
|
||||
|
||||
// Read exec error pipe first (blocking is fine because child closes on exec or writes & exits).
|
||||
ExecErrorPacket exec_pkt{};
|
||||
ssize_t exec_read = 0;
|
||||
while (exec_read < static_cast<ssize_t>(sizeof(exec_pkt))) {
|
||||
const ssize_t n = ::read(exec_err_fd, reinterpret_cast<char *>(&exec_pkt) + exec_read,
|
||||
sizeof(exec_pkt) - static_cast<std::size_t>(exec_read));
|
||||
if (n > 0) {
|
||||
exec_read += n;
|
||||
} else if (n == 0) {
|
||||
break;
|
||||
} else if (errno != EINTR) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
(void)::close(exec_err_fd);
|
||||
|
||||
ProcessResult result;
|
||||
bool leader_reaped = false;
|
||||
int raw_status = 0;
|
||||
|
||||
if (exec_read == static_cast<ssize_t>(sizeof(exec_pkt)) && exec_pkt.err_no != 0) {
|
||||
if (in_fd >= 0) {
|
||||
(void)::close(in_fd);
|
||||
}
|
||||
(void)::close(out_fd);
|
||||
(void)::close(err_fd);
|
||||
reap_leader(pid, leader_reaped, raw_status, true);
|
||||
result.exec_failed = true;
|
||||
result.exec_errno = exec_pkt.err_no;
|
||||
result.exec_error_message =
|
||||
exec_pkt.stage == 1
|
||||
? std::format("chdir('{}') failed: {}", cwd_str, std::strerror(exec_pkt.err_no))
|
||||
: std::format("execve('{}') failed: {}", exec_str, std::strerror(exec_pkt.err_no));
|
||||
return result;
|
||||
}
|
||||
|
||||
std::size_t stdin_offset = 0;
|
||||
const auto start_time = std::chrono::steady_clock::now();
|
||||
const bool has_timeout = request.timeout.count() > 0;
|
||||
const auto deadline = start_time + request.timeout;
|
||||
|
||||
std::array<char, 16384> buf{};
|
||||
|
||||
while (in_fd >= 0 || out_fd >= 0 || err_fd >= 0) {
|
||||
if (stop.stop_requested()) {
|
||||
result.cancelled = true;
|
||||
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||
break;
|
||||
}
|
||||
if (has_timeout && std::chrono::steady_clock::now() >= deadline) {
|
||||
result.timed_out = true;
|
||||
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||
break;
|
||||
}
|
||||
|
||||
struct pollfd fds[3];
|
||||
int nfds = 0;
|
||||
int in_idx = -1;
|
||||
int out_idx = -1;
|
||||
int err_idx = -1;
|
||||
if (in_fd >= 0) {
|
||||
in_idx = nfds;
|
||||
fds[nfds++] = {in_fd, POLLOUT, 0};
|
||||
}
|
||||
if (out_fd >= 0) {
|
||||
out_idx = nfds;
|
||||
fds[nfds++] = {out_fd, POLLIN, 0};
|
||||
}
|
||||
if (err_fd >= 0) {
|
||||
err_idx = nfds;
|
||||
fds[nfds++] = {err_fd, POLLIN, 0};
|
||||
}
|
||||
|
||||
int poll_ms = 25;
|
||||
if (has_timeout) {
|
||||
const auto rem = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
deadline - std::chrono::steady_clock::now());
|
||||
poll_ms = static_cast<int>(std::clamp<long long>(rem.count(), 1, 25));
|
||||
}
|
||||
|
||||
const int ready = ::poll(fds, static_cast<nfds_t>(nfds), poll_ms);
|
||||
if (ready < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (ready == 0) {
|
||||
reap_leader(pid, leader_reaped, raw_status, false);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_idx >= 0 && (fds[in_idx].revents & (POLLOUT | POLLERR | POLLHUP))) {
|
||||
const ssize_t w = ::write(in_fd, request.stdin_data.data() + stdin_offset,
|
||||
request.stdin_data.size() - stdin_offset);
|
||||
if (w > 0) {
|
||||
stdin_offset += static_cast<std::size_t>(w);
|
||||
if (stdin_offset >= request.stdin_data.size()) {
|
||||
(void)::close(in_fd);
|
||||
in_fd = -1;
|
||||
}
|
||||
} else if (w < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
|
||||
(void)::close(in_fd);
|
||||
in_fd = -1;
|
||||
}
|
||||
}
|
||||
|
||||
auto drain_stream = [&](int &fd, std::string &target, std::size_t limit, bool &truncated,
|
||||
const std::function<void(std::string_view)> &cb) {
|
||||
for (;;) {
|
||||
const ssize_t n = ::read(fd, buf.data(), buf.size());
|
||||
if (n > 0) {
|
||||
const std::string_view chunk{buf.data(), static_cast<std::size_t>(n)};
|
||||
if (cb) {
|
||||
cb(chunk);
|
||||
}
|
||||
if (target.size() < limit) {
|
||||
const std::size_t take = std::min(chunk.size(), limit - target.size());
|
||||
target.append(chunk.data(), take);
|
||||
if (take < chunk.size()) {
|
||||
truncated = true;
|
||||
}
|
||||
} else {
|
||||
truncated = true;
|
||||
}
|
||||
if (truncated && request.fail_on_overflow) {
|
||||
result.overflowed = true;
|
||||
return;
|
||||
}
|
||||
} else if (n == 0) {
|
||||
(void)::close(fd);
|
||||
fd = -1;
|
||||
return;
|
||||
} else {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
if (errno == EAGAIN || errno == EWOULDBLOCK) {
|
||||
return;
|
||||
}
|
||||
(void)::close(fd);
|
||||
fd = -1;
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (out_idx >= 0 && (fds[out_idx].revents & (POLLIN | POLLHUP | POLLERR))) {
|
||||
drain_stream(out_fd, result.stdout_data, request.max_stdout_bytes,
|
||||
result.stdout_truncated, request.on_stdout_chunk);
|
||||
}
|
||||
if (err_idx >= 0 && (fds[err_idx].revents & (POLLIN | POLLHUP | POLLERR))) {
|
||||
drain_stream(err_fd, result.stderr_data, request.max_stderr_bytes,
|
||||
result.stderr_truncated, request.on_stderr_chunk);
|
||||
}
|
||||
if (result.overflowed) {
|
||||
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (in_fd >= 0) {
|
||||
(void)::close(in_fd);
|
||||
}
|
||||
if (out_fd >= 0) {
|
||||
(void)::close(out_fd);
|
||||
}
|
||||
if (err_fd >= 0) {
|
||||
(void)::close(err_fd);
|
||||
}
|
||||
|
||||
// Wait for leader AND any remaining process-group descendants, polling for stop/timeout.
|
||||
while (!leader_reaped || process_group_alive(pgid)) {
|
||||
reap_leader(pid, leader_reaped, raw_status, false);
|
||||
if (leader_reaped && !process_group_alive(pgid)) {
|
||||
break;
|
||||
}
|
||||
if (stop.stop_requested()) {
|
||||
result.cancelled = true;
|
||||
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||
break;
|
||||
}
|
||||
if (has_timeout && std::chrono::steady_clock::now() >= deadline) {
|
||||
result.timed_out = true;
|
||||
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||
break;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
}
|
||||
|
||||
// Even if the leader exited cleanly or early, ensure no stray process-group
|
||||
// descendants remain alive if we were cancelled/timed out/overflowed, or wait/clean them up.
|
||||
if (result.cancelled || result.timed_out || result.overflowed) {
|
||||
if (process_group_alive(pgid)) {
|
||||
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||
}
|
||||
}
|
||||
|
||||
if (leader_reaped) {
|
||||
if (WIFEXITED(raw_status)) {
|
||||
result.exited = true;
|
||||
result.exit_code = WEXITSTATUS(raw_status);
|
||||
} else if (WIFSIGNALED(raw_status)) {
|
||||
result.exited = false;
|
||||
result.term_signal = WTERMSIG(raw_status);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Platform
|
||||
@@ -0,0 +1,773 @@
|
||||
#include <Void/Build/Provider/Provider.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/Data/StrictJson.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <set>
|
||||
#include <type_traits>
|
||||
|
||||
namespace Void::Build::Provider {
|
||||
namespace {
|
||||
|
||||
using JsonVal = Void::Json::Strict::Value;
|
||||
|
||||
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
|
||||
return Void::System::make_system_error(code, std::move(msg));
|
||||
}
|
||||
|
||||
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::string get_str(const JsonVal::Object &obj, const std::string &k) {
|
||||
const auto *v = find_key(obj, k);
|
||||
if (!v) {
|
||||
return {};
|
||||
}
|
||||
const auto *s = std::get_if<std::string>(&v->value);
|
||||
return s ? *s : std::string{};
|
||||
}
|
||||
|
||||
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
|
||||
const auto *v = find_key(obj, k);
|
||||
if (!v) {
|
||||
return def;
|
||||
}
|
||||
const auto *b = std::get_if<bool>(&v->value);
|
||||
return b ? *b : def;
|
||||
}
|
||||
|
||||
std::vector<std::string> get_str_array(const JsonVal::Object &obj, const std::string &k) {
|
||||
std::vector<std::string> out;
|
||||
const auto *v = find_key(obj, k);
|
||||
if (!v) {
|
||||
return out;
|
||||
}
|
||||
if (const auto *arr = std::get_if<JsonVal::Array>(&v->value)) {
|
||||
for (const auto &item : *arr) {
|
||||
if (const auto *s = std::get_if<std::string>(&item.value)) {
|
||||
out.push_back(*s);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::optional<JsonVal> parse_json_file(const std::filesystem::path &path) {
|
||||
auto text = Void::FileSystem::read_file(path);
|
||||
if (!text) {
|
||||
return std::nullopt;
|
||||
}
|
||||
auto parsed = Void::Json::Strict::parse(*text);
|
||||
if (!parsed) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return std::move(*parsed);
|
||||
}
|
||||
|
||||
std::string serialize_export(const ProviderExport &exp) {
|
||||
using Util::json_array;
|
||||
using Util::json_quote;
|
||||
|
||||
std::string out =
|
||||
"{\"schema_version\":1,\"dependency_name\":" + json_quote(exp.dependency_name) +
|
||||
",\"builder\":" + json_quote(exp.builder) +
|
||||
",\"input_identity_hash\":" + json_quote(exp.input_identity_hash) + ",\"targets\":{";
|
||||
bool first = true;
|
||||
for (const auto &[tname, iface] : exp.targets) {
|
||||
if (!first) {
|
||||
out += ',';
|
||||
}
|
||||
first = false;
|
||||
out += json_quote(tname) + ":{\"dependency_name\":" + json_quote(iface.dependency_name) +
|
||||
",\"target_name\":" + json_quote(iface.target_name) + ",\"include_dirs\":" +
|
||||
json_array(iface.include_dirs,
|
||||
[](const std::pair<std::filesystem::path, bool> &inc) {
|
||||
return "{\"path\":" + json_quote(inc.first.string()) +
|
||||
",\"is_system\":" +
|
||||
std::string{inc.second ? "true" : "false"} + '}';
|
||||
}) +
|
||||
",\"defines\":" + json_array(iface.defines, json_quote) +
|
||||
",\"compile_options\":" + json_array(iface.compile_options, json_quote) +
|
||||
",\"link_options\":" + json_array(iface.link_options, json_quote) +
|
||||
",\"static_libraries\":" +
|
||||
json_array(iface.static_libraries,
|
||||
[](const std::filesystem::path &p) { return json_quote(p.string()); }) +
|
||||
",\"shared_libraries\":" +
|
||||
json_array(iface.shared_libraries,
|
||||
[](const std::filesystem::path &p) { return json_quote(p.string()); }) +
|
||||
",\"runtime_files\":" +
|
||||
json_array(iface.runtime_files,
|
||||
[](const std::filesystem::path &p) { return json_quote(p.string()); }) +
|
||||
'}';
|
||||
}
|
||||
out += "}}\n";
|
||||
return out;
|
||||
}
|
||||
|
||||
std::optional<ProviderExport> load_cached_export(const std::filesystem::path &export_file,
|
||||
std::string_view expected_hash) {
|
||||
auto text = Void::FileSystem::read_file(export_file);
|
||||
if (!text) {
|
||||
return std::nullopt;
|
||||
}
|
||||
auto parsed = Void::Json::Strict::parse(*text);
|
||||
if (!parsed) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
|
||||
if (!root) {
|
||||
return std::nullopt;
|
||||
}
|
||||
if (get_str(*root, "input_identity_hash") != expected_hash) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
ProviderExport exp;
|
||||
exp.dependency_name = get_str(*root, "dependency_name");
|
||||
exp.builder = get_str(*root, "builder");
|
||||
exp.input_identity_hash = std::string{expected_hash};
|
||||
exp.from_cache = true;
|
||||
|
||||
if (const auto *tv = find_key(*root, "targets")) {
|
||||
if (const auto *tobj = std::get_if<JsonVal::Object>(&tv->value)) {
|
||||
for (const auto &[k, val] : *tobj) {
|
||||
const auto *io = std::get_if<JsonVal::Object>(&val.value);
|
||||
if (!io) {
|
||||
continue;
|
||||
}
|
||||
Graph::ImportedTargetInterface iface;
|
||||
iface.dependency_name = get_str(*io, "dependency_name");
|
||||
iface.target_name = get_str(*io, "target_name");
|
||||
if (const auto *iv = find_key(*io, "include_dirs")) {
|
||||
if (const auto *iarr = std::get_if<JsonVal::Array>(&iv->value)) {
|
||||
for (const auto &item : *iarr) {
|
||||
if (const auto *inc = std::get_if<JsonVal::Object>(&item.value)) {
|
||||
iface.include_dirs.emplace_back(get_str(*inc, "path"),
|
||||
get_bool(*inc, "is_system", false));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
iface.defines = get_str_array(*io, "defines");
|
||||
iface.compile_options = get_str_array(*io, "compile_options");
|
||||
iface.link_options = get_str_array(*io, "link_options");
|
||||
for (const auto &s : get_str_array(*io, "static_libraries")) {
|
||||
iface.static_libraries.emplace_back(s);
|
||||
}
|
||||
for (const auto &s : get_str_array(*io, "shared_libraries")) {
|
||||
iface.shared_libraries.emplace_back(s);
|
||||
}
|
||||
for (const auto &s : get_str_array(*io, "runtime_files")) {
|
||||
iface.runtime_files.emplace_back(s);
|
||||
}
|
||||
// Verify materialized library artifacts still exist on disk!
|
||||
std::error_code ec;
|
||||
for (const auto &lib : iface.static_libraries) {
|
||||
if (!std::filesystem::is_regular_file(lib, ec)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
for (const auto &lib : iface.shared_libraries) {
|
||||
if (!std::filesystem::is_regular_file(lib, ec)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
exp.targets[k] = std::move(iface);
|
||||
}
|
||||
}
|
||||
}
|
||||
return exp;
|
||||
}
|
||||
|
||||
std::string cmake_option_value(const OptionValue &v) {
|
||||
return std::visit(
|
||||
[](const auto &inner) -> std::string {
|
||||
using T = std::remove_cvref_t<decltype(inner)>;
|
||||
if constexpr (std::same_as<T, std::string>) {
|
||||
return inner;
|
||||
} else if constexpr (std::same_as<T, bool>) {
|
||||
return inner ? "ON" : "OFF";
|
||||
} else {
|
||||
return std::to_string(inner);
|
||||
}
|
||||
},
|
||||
v.value);
|
||||
}
|
||||
|
||||
std::string meson_option_value(const OptionValue &v) {
|
||||
return std::visit(
|
||||
[](const auto &inner) -> std::string {
|
||||
using T = std::remove_cvref_t<decltype(inner)>;
|
||||
if constexpr (std::same_as<T, std::string>) {
|
||||
return inner;
|
||||
} else if constexpr (std::same_as<T, bool>) {
|
||||
return inner ? "true" : "false";
|
||||
} else {
|
||||
return std::to_string(inner);
|
||||
}
|
||||
},
|
||||
v.value);
|
||||
}
|
||||
|
||||
// Imports CMake File API reply (index-*.json -> codemodel-v2 -> target-*.json).
|
||||
Void::Result::Result<ProviderExport, Void::Result::Error>
|
||||
run_cmake_provider(const ProviderRequest &request, const std::filesystem::path &build_dir,
|
||||
const std::string &input_hash, std::stop_token stop) {
|
||||
auto cmake_bin = Platform::resolve_executable("cmake");
|
||||
if (!cmake_bin) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::not_found,
|
||||
"CMake provider requires 'cmake' in PATH")};
|
||||
}
|
||||
|
||||
std::error_code ec;
|
||||
// Fresh build dir whenever input hash changed so foreign timestamp shortcuts cannot retain
|
||||
// stale objects (Plan 13 acceptance #3).
|
||||
std::filesystem::remove_all(build_dir, ec);
|
||||
std::filesystem::create_directories(build_dir / ".cmake" / "api" / "v1" / "query", ec);
|
||||
(void)Platform::atomic_write_file(
|
||||
build_dir / ".cmake" / "api" / "v1" / "query" / "codemodel-v2", "", false);
|
||||
|
||||
// 1. Configure with isolated profile/toolchain context.
|
||||
{
|
||||
Platform::ProcessRequest req;
|
||||
req.executable = *cmake_bin;
|
||||
req.arguments = {"-S", request.source.source_dir.string(), "-B", build_dir.string()};
|
||||
if (Platform::resolve_executable("ninja").has_value()) {
|
||||
req.arguments.push_back("-G");
|
||||
req.arguments.push_back("Ninja");
|
||||
}
|
||||
req.arguments.push_back("-DCMAKE_CXX_COMPILER=" + request.toolchain.cxx_compiler.string());
|
||||
const std::string cfg =
|
||||
(request.profile.name == "release" || request.profile.name == "Release") ? "Release"
|
||||
: "Debug";
|
||||
req.arguments.push_back("-DCMAKE_BUILD_TYPE=" + cfg);
|
||||
for (const auto &[k, v] : request.dependency.options) {
|
||||
req.arguments.push_back("-D" + k + "=" + cmake_option_value(v));
|
||||
}
|
||||
req.timeout = std::chrono::seconds{180};
|
||||
auto proc = Platform::run_supervised(req, stop);
|
||||
if (!proc || !proc->succeeded()) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::io_error,
|
||||
std::format("CMake configure failed for '{}':\n{}", request.dependency.name,
|
||||
proc ? (proc->stderr_data + proc->stdout_data)
|
||||
: proc.error().message()))};
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Build all targets in isolated build directory.
|
||||
{
|
||||
Platform::ProcessRequest req;
|
||||
req.executable = *cmake_bin;
|
||||
req.arguments = {"--build", build_dir.string()};
|
||||
req.timeout = std::chrono::seconds{300};
|
||||
auto proc = Platform::run_supervised(req, stop);
|
||||
if (!proc || !proc->succeeded()) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error,
|
||||
std::format("CMake build failed for '{}':\n{}", request.dependency.name,
|
||||
proc ? (proc->stderr_data + proc->stdout_data)
|
||||
: proc.error().message()))};
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Parse CMake File API reply -> codemodel-v2 -> per-target metadata.
|
||||
const auto reply_dir = build_dir / ".cmake" / "api" / "v1" / "reply";
|
||||
std::filesystem::path index_file;
|
||||
for (const auto &ent : std::filesystem::directory_iterator(reply_dir, ec)) {
|
||||
if (ent.is_regular_file() && ent.path().filename().string().starts_with("index-")) {
|
||||
index_file = ent.path();
|
||||
}
|
||||
}
|
||||
if (index_file.empty()) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::io_error,
|
||||
std::format("CMake File API reply missing for '{}'", request.dependency.name))};
|
||||
}
|
||||
|
||||
auto index_json = parse_json_file(index_file);
|
||||
if (!index_json) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"failed parsing CMake File API index JSON")};
|
||||
}
|
||||
const auto *idx_obj = std::get_if<JsonVal::Object>(&index_json->value);
|
||||
std::string codemodel_file;
|
||||
if (idx_obj) {
|
||||
if (const auto *objs = find_key(*idx_obj, "objects")) {
|
||||
if (const auto *arr = std::get_if<JsonVal::Array>(&objs->value)) {
|
||||
for (const auto &item : *arr) {
|
||||
if (const auto *o = std::get_if<JsonVal::Object>(&item.value)) {
|
||||
if (get_str(*o, "kind") == "codemodel") {
|
||||
codemodel_file = get_str(*o, "jsonFile");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (codemodel_file.empty()) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"CMake File API index missing codemodel object")};
|
||||
}
|
||||
|
||||
auto cm_json = parse_json_file(reply_dir / codemodel_file);
|
||||
if (!cm_json) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"failed parsing CMake codemodel JSON")};
|
||||
}
|
||||
|
||||
struct RawTarget {
|
||||
std::string id;
|
||||
std::string name;
|
||||
std::string type;
|
||||
std::vector<std::string> dep_ids;
|
||||
Graph::ImportedTargetInterface iface;
|
||||
};
|
||||
std::map<std::string, RawTarget, std::less<>> raw_by_id;
|
||||
|
||||
if (const auto *cm_obj = std::get_if<JsonVal::Object>(&cm_json->value)) {
|
||||
if (const auto *cfgs = find_key(*cm_obj, "configurations")) {
|
||||
if (const auto *carr = std::get_if<JsonVal::Array>(&cfgs->value);
|
||||
carr && !carr->empty()) {
|
||||
if (const auto *cfg0 = std::get_if<JsonVal::Object>(&carr->front().value)) {
|
||||
if (const auto *tgts = find_key(*cfg0, "targets")) {
|
||||
if (const auto *tarr = std::get_if<JsonVal::Array>(&tgts->value)) {
|
||||
for (const auto &tv : *tarr) {
|
||||
const auto *to = std::get_if<JsonVal::Object>(&tv.value);
|
||||
if (!to) {
|
||||
continue;
|
||||
}
|
||||
const auto tfile = get_str(*to, "jsonFile");
|
||||
auto tjson = parse_json_file(reply_dir / tfile);
|
||||
if (!tjson) {
|
||||
continue;
|
||||
}
|
||||
const auto *td = std::get_if<JsonVal::Object>(&tjson->value);
|
||||
if (!td) {
|
||||
continue;
|
||||
}
|
||||
RawTarget rt;
|
||||
rt.id = get_str(*td, "id");
|
||||
rt.name = get_str(*td, "name");
|
||||
rt.type = get_str(*td, "type");
|
||||
rt.iface.dependency_name = request.dependency.name;
|
||||
rt.iface.target_name = rt.name;
|
||||
|
||||
// Extract artifacts.
|
||||
if (const auto *arts = find_key(*td, "artifacts")) {
|
||||
if (const auto *aarr =
|
||||
std::get_if<JsonVal::Array>(&arts->value)) {
|
||||
for (const auto &av : *aarr) {
|
||||
if (const auto *ao =
|
||||
std::get_if<JsonVal::Object>(&av.value)) {
|
||||
const auto p = build_dir / get_str(*ao, "path");
|
||||
if (rt.type == "STATIC_LIBRARY") {
|
||||
rt.iface.static_libraries.push_back(p);
|
||||
} else if (rt.type == "SHARED_LIBRARY") {
|
||||
rt.iface.shared_libraries.push_back(p);
|
||||
rt.iface.runtime_files.push_back(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract compile groups (includes, defines).
|
||||
if (const auto *cgs = find_key(*td, "compileGroups")) {
|
||||
if (const auto *cgarr =
|
||||
std::get_if<JsonVal::Array>(&cgs->value)) {
|
||||
for (const auto &cgv : *cgarr) {
|
||||
const auto *cgo =
|
||||
std::get_if<JsonVal::Object>(&cgv.value);
|
||||
if (!cgo) {
|
||||
continue;
|
||||
}
|
||||
if (const auto *incs = find_key(*cgo, "includes")) {
|
||||
if (const auto *iarr =
|
||||
std::get_if<JsonVal::Array>(&incs->value)) {
|
||||
for (const auto &iv : *iarr) {
|
||||
if (const auto *io =
|
||||
std::get_if<JsonVal::Object>(
|
||||
&iv.value)) {
|
||||
const std::filesystem::path ip{
|
||||
get_str(*io, "path")};
|
||||
const bool sys =
|
||||
get_bool(*io, "isSystem", false);
|
||||
if (!std::ranges::contains(
|
||||
rt.iface.include_dirs,
|
||||
std::pair{ip, sys})) {
|
||||
rt.iface.include_dirs.emplace_back(
|
||||
ip, sys);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (const auto *defs = find_key(*cgo, "defines")) {
|
||||
if (const auto *darr =
|
||||
std::get_if<JsonVal::Array>(&defs->value)) {
|
||||
for (const auto &dv : *darr) {
|
||||
if (const auto *do_obj =
|
||||
std::get_if<JsonVal::Object>(
|
||||
&dv.value)) {
|
||||
const auto d =
|
||||
get_str(*do_obj, "define");
|
||||
if (!d.empty() &&
|
||||
!std::ranges::contains(
|
||||
rt.iface.defines, d)) {
|
||||
rt.iface.defines.push_back(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract dependencies for transitive static archive ordering.
|
||||
if (const auto *deps = find_key(*td, "dependencies")) {
|
||||
if (const auto *darr =
|
||||
std::get_if<JsonVal::Array>(&deps->value)) {
|
||||
for (const auto &dv : *darr) {
|
||||
if (const auto *do_obj =
|
||||
std::get_if<JsonVal::Object>(&dv.value)) {
|
||||
rt.dep_ids.push_back(get_str(*do_obj, "id"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
raw_by_id[rt.id] = std::move(rt);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve transitive static library link order across CMake targets.
|
||||
ProviderExport exp;
|
||||
exp.dependency_name = request.dependency.name;
|
||||
exp.builder = "cmake";
|
||||
exp.input_identity_hash = input_hash;
|
||||
|
||||
for (const auto &[id, rt] : raw_by_id) {
|
||||
Graph::ImportedTargetInterface resolved = rt.iface;
|
||||
std::set<std::string> visited{id};
|
||||
std::vector<std::string> queue = rt.dep_ids;
|
||||
for (std::size_t qi = 0; qi < queue.size(); ++qi) {
|
||||
const auto &dep_id = queue[qi];
|
||||
if (!visited.insert(dep_id).second) {
|
||||
continue;
|
||||
}
|
||||
const auto dit = raw_by_id.find(dep_id);
|
||||
if (dit == raw_by_id.end()) {
|
||||
continue;
|
||||
}
|
||||
for (const auto &lib : dit->second.iface.static_libraries) {
|
||||
resolved.static_libraries.push_back(lib);
|
||||
}
|
||||
for (const auto &lib : dit->second.iface.shared_libraries) {
|
||||
resolved.shared_libraries.push_back(lib);
|
||||
}
|
||||
for (const auto &inc : dit->second.iface.include_dirs) {
|
||||
if (!std::ranges::contains(resolved.include_dirs, inc)) {
|
||||
resolved.include_dirs.push_back(inc);
|
||||
}
|
||||
}
|
||||
for (const auto &sub : dit->second.dep_ids) {
|
||||
queue.push_back(sub);
|
||||
}
|
||||
}
|
||||
exp.targets[rt.name] = resolved;
|
||||
exp.targets[request.dependency.name + "::" + rt.name] = resolved;
|
||||
}
|
||||
|
||||
// Apply explicit user overrides if supplied.
|
||||
for (const auto &[k, v] : request.explicit_overrides) {
|
||||
exp.targets[k] = v;
|
||||
}
|
||||
return exp;
|
||||
}
|
||||
|
||||
// Imports Meson introspection metadata (`meson-info/intro-targets.json`).
|
||||
Void::Result::Result<ProviderExport, Void::Result::Error>
|
||||
run_meson_provider(const ProviderRequest &request, const std::filesystem::path &build_dir,
|
||||
const std::string &input_hash, std::stop_token stop) {
|
||||
auto meson_bin = Platform::resolve_executable("meson");
|
||||
if (!meson_bin) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::not_found,
|
||||
"Meson provider requires 'meson' in PATH")};
|
||||
}
|
||||
|
||||
std::error_code ec;
|
||||
std::filesystem::remove_all(build_dir, ec);
|
||||
std::filesystem::create_directories(build_dir.parent_path(), ec);
|
||||
|
||||
{
|
||||
Platform::ProcessRequest req;
|
||||
req.executable = *meson_bin;
|
||||
req.arguments = {"setup", build_dir.string(), request.source.source_dir.string()};
|
||||
const std::string btype =
|
||||
(request.profile.name == "release" || request.profile.name == "Release") ? "release"
|
||||
: "debug";
|
||||
req.arguments.push_back("-Dbuildtype=" + btype);
|
||||
for (const auto &[k, v] : request.dependency.options) {
|
||||
req.arguments.push_back("-D" + k + "=" + meson_option_value(v));
|
||||
}
|
||||
req.environment.set_vars["CXX"] = request.toolchain.cxx_compiler.string();
|
||||
req.timeout = std::chrono::seconds{180};
|
||||
auto proc = Platform::run_supervised(req, stop);
|
||||
if (!proc || !proc->succeeded()) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error,
|
||||
std::format("Meson setup failed for '{}':\n{}", request.dependency.name,
|
||||
proc ? (proc->stderr_data + proc->stdout_data)
|
||||
: proc.error().message()))};
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
Platform::ProcessRequest req;
|
||||
req.executable = *meson_bin;
|
||||
req.arguments = {"compile", "-C", build_dir.string()};
|
||||
req.timeout = std::chrono::seconds{300};
|
||||
auto proc = Platform::run_supervised(req, stop);
|
||||
if (!proc || !proc->succeeded()) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::io_error,
|
||||
std::format("Meson compile failed for '{}':\n{}", request.dependency.name,
|
||||
proc ? (proc->stderr_data + proc->stdout_data)
|
||||
: proc.error().message()))};
|
||||
}
|
||||
}
|
||||
|
||||
const auto intro_targets = build_dir / "meson-info" / "intro-targets.json";
|
||||
auto parsed = parse_json_file(intro_targets);
|
||||
if (!parsed) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"failed parsing Meson intro-targets.json")};
|
||||
}
|
||||
|
||||
ProviderExport exp;
|
||||
exp.dependency_name = request.dependency.name;
|
||||
exp.builder = "meson";
|
||||
exp.input_identity_hash = input_hash;
|
||||
|
||||
if (const auto *arr = std::get_if<JsonVal::Array>(&parsed->value)) {
|
||||
for (const auto &tv : *arr) {
|
||||
const auto *to = std::get_if<JsonVal::Object>(&tv.value);
|
||||
if (!to) {
|
||||
continue;
|
||||
}
|
||||
const auto tname = get_str(*to, "name");
|
||||
const auto ttype = get_str(*to, "type");
|
||||
Graph::ImportedTargetInterface iface;
|
||||
iface.dependency_name = request.dependency.name;
|
||||
iface.target_name = tname;
|
||||
|
||||
for (const auto &fname : get_str_array(*to, "filename")) {
|
||||
if (ttype == "static library") {
|
||||
iface.static_libraries.emplace_back(fname);
|
||||
} else if (ttype == "shared library") {
|
||||
iface.shared_libraries.emplace_back(fname);
|
||||
iface.runtime_files.emplace_back(fname);
|
||||
}
|
||||
}
|
||||
|
||||
// Collect include directories from target_sources parameters (-I...) plus source
|
||||
// include/.
|
||||
if (const auto *ts = find_key(*to, "target_sources")) {
|
||||
if (const auto *tsarr = std::get_if<JsonVal::Array>(&ts->value)) {
|
||||
for (const auto &tsv : *tsarr) {
|
||||
if (const auto *tso = std::get_if<JsonVal::Object>(&tsv.value)) {
|
||||
const auto params = get_str_array(*tso, "parameters");
|
||||
for (std::size_t i = 0; i < params.size(); ++i) {
|
||||
if (params[i].starts_with("-I") && params[i].size() > 2) {
|
||||
std::filesystem::path p{params[i].substr(2)};
|
||||
if (!p.is_absolute()) {
|
||||
p = (build_dir / p).lexically_normal();
|
||||
}
|
||||
if (!std::ranges::contains(iface.include_dirs,
|
||||
std::pair{p, false})) {
|
||||
iface.include_dirs.emplace_back(p, false);
|
||||
}
|
||||
} else if (params[i] == "-I" && i + 1 < params.size()) {
|
||||
std::filesystem::path p{params[++i]};
|
||||
if (!p.is_absolute()) {
|
||||
p = (build_dir / p).lexically_normal();
|
||||
}
|
||||
if (!std::ranges::contains(iface.include_dirs,
|
||||
std::pair{p, false})) {
|
||||
iface.include_dirs.emplace_back(p, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (std::filesystem::is_directory(request.source.source_dir / "include", ec)) {
|
||||
const auto inc = (request.source.source_dir / "include").lexically_normal();
|
||||
if (!std::ranges::contains(iface.include_dirs, std::pair{inc, false})) {
|
||||
iface.include_dirs.emplace_back(inc, false);
|
||||
}
|
||||
}
|
||||
exp.targets[tname] = iface;
|
||||
exp.targets[request.dependency.name + "::" + tname] = iface;
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto &[k, v] : request.explicit_overrides) {
|
||||
exp.targets[k] = v;
|
||||
}
|
||||
return exp;
|
||||
}
|
||||
|
||||
Void::Result::Result<ProviderExport, Void::Result::Error>
|
||||
run_conan_provider(const ProviderRequest &request, const std::filesystem::path &build_dir,
|
||||
const std::string &input_hash, std::stop_token stop) {
|
||||
auto conan_bin = Platform::resolve_executable("conan");
|
||||
if (!conan_bin) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::not_found,
|
||||
std::format("Conan2 provider requires 'conan' in PATH for dependency '{}' "
|
||||
"(prerequisite missing; refusing empty import)",
|
||||
request.dependency.name))};
|
||||
}
|
||||
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(build_dir, ec);
|
||||
const auto host_profile = build_dir / "conan_host.profile";
|
||||
const auto build_profile = build_dir / "conan_build.profile";
|
||||
const std::string btype =
|
||||
(request.profile.name == "release" || request.profile.name == "Release") ? "Release"
|
||||
: "Debug";
|
||||
const std::string prof_text =
|
||||
std::format("[settings]\nos={}\narch={}\ncompiler={}\nbuild_type={}\n", request.profile.os,
|
||||
request.profile.architecture, compiler_name(request.profile.compiler), btype);
|
||||
(void)Platform::atomic_write_file(host_profile, prof_text, false);
|
||||
(void)Platform::atomic_write_file(build_profile, prof_text, false);
|
||||
|
||||
Platform::ProcessRequest req;
|
||||
req.executable = *conan_bin;
|
||||
req.arguments = {"install",
|
||||
"--requires",
|
||||
request.dependency.package,
|
||||
"--profile:host",
|
||||
host_profile.string(),
|
||||
"--profile:build",
|
||||
build_profile.string(),
|
||||
"--output-folder",
|
||||
build_dir.string(),
|
||||
"--format",
|
||||
"json"};
|
||||
req.timeout = std::chrono::seconds{300};
|
||||
auto proc = Platform::run_supervised(req, stop);
|
||||
if (!proc || !proc->succeeded()) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error,
|
||||
std::format("Conan2 install failed for '{}':\n{}", request.dependency.name,
|
||||
proc ? proc->stderr_data : proc.error().message()))};
|
||||
}
|
||||
|
||||
ProviderExport exp;
|
||||
exp.dependency_name = request.dependency.name;
|
||||
exp.builder = "conan";
|
||||
exp.input_identity_hash = input_hash;
|
||||
for (const auto &[k, v] : request.explicit_overrides) {
|
||||
exp.targets[k] = v;
|
||||
}
|
||||
return exp;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string compute_provider_input_hash(const ProviderRequest &request) {
|
||||
Util::Sha256Hasher h;
|
||||
h.update_length_prefixed("vbs-provider-v1");
|
||||
h.update_length_prefixed(request.dependency.name);
|
||||
h.update_length_prefixed(request.dependency.builder);
|
||||
h.update_length_prefixed(request.source.content_identity_hash);
|
||||
h.update_length_prefixed(request.profile.name);
|
||||
h.update_length_prefixed(request.toolchain.identity_hash);
|
||||
for (const auto &[k, v] : request.dependency.options) {
|
||||
h.update_length_prefixed(k);
|
||||
h.update_length_prefixed(cmake_option_value(v));
|
||||
}
|
||||
return h.finalize_hex();
|
||||
}
|
||||
|
||||
Void::Result::Result<ProviderExport, Void::Result::Error>
|
||||
resolve_foreign_provider(const ProviderRequest &request, std::stop_token stop) {
|
||||
const std::string input_hash = compute_provider_input_hash(request);
|
||||
const auto isolated_dir =
|
||||
request.provider_build_root / request.dependency.name / input_hash.substr(0, 16);
|
||||
const auto export_file = isolated_dir / "provider-export.json";
|
||||
|
||||
// Always try validated cache first (in BOTH FullBuild and MetadataOnly modes).
|
||||
if (auto cached = load_cached_export(export_file, input_hash); cached) {
|
||||
return *cached;
|
||||
}
|
||||
|
||||
// Strict MetadataOnly boundary (D-026 / Plan 10 / Plan 13):
|
||||
// NEVER invoke CMake configure, Meson setup, Conan install, or builds!
|
||||
if (request.mode == ProviderMode::MetadataOnly) {
|
||||
ProviderExport stale;
|
||||
stale.dependency_name = request.dependency.name;
|
||||
stale.builder = request.dependency.builder;
|
||||
stale.input_identity_hash = input_hash;
|
||||
stale.stale_needs_build = true;
|
||||
stale.stale_diagnostic = std::format(
|
||||
"cached {} provider metadata for '{}' is missing or stale (input={}); "
|
||||
"run 'vbs build' to configure/build dependencies",
|
||||
request.dependency.builder, request.dependency.name, input_hash.substr(0, 12));
|
||||
return stale;
|
||||
}
|
||||
|
||||
const auto lock_path = isolated_dir.parent_path() / (request.dependency.name + ".lock");
|
||||
auto lock = Platform::FileLock::acquire(lock_path, Platform::LockMode::Exclusive);
|
||||
if (!lock) {
|
||||
return std::unexpected{lock.error()};
|
||||
}
|
||||
|
||||
// Re-check cache after acquiring lock in case a peer just finished.
|
||||
if (auto cached = load_cached_export(export_file, input_hash); cached) {
|
||||
return *cached;
|
||||
}
|
||||
|
||||
const auto tool_build_dir = isolated_dir / "build";
|
||||
Void::Result::Result<ProviderExport, Void::Result::Error> res = std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("unsupported foreign builder '{}'", request.dependency.builder))};
|
||||
if (request.dependency.builder == "cmake") {
|
||||
res = run_cmake_provider(request, tool_build_dir, input_hash, stop);
|
||||
} else if (request.dependency.builder == "meson") {
|
||||
res = run_meson_provider(request, tool_build_dir, input_hash, stop);
|
||||
} else if (request.dependency.builder == "conan") {
|
||||
res = run_conan_provider(request, tool_build_dir, input_hash, stop);
|
||||
}
|
||||
if (!res) {
|
||||
return std::unexpected{res.error()};
|
||||
}
|
||||
|
||||
// Publish validated provider export atomically!
|
||||
if (auto w = Platform::atomic_write_file(export_file, serialize_export(*res), true); !w) {
|
||||
return std::unexpected{w.error()};
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Provider
|
||||
@@ -0,0 +1,89 @@
|
||||
#include <Void/Build/SelfHost/TestRegistryGen.hpp>
|
||||
|
||||
#include <Void/Build/Platform/FileOps.hpp>
|
||||
#include <Void/Build/Util/Json.hpp>
|
||||
#include <Void/Build/Util/Sha256.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <format>
|
||||
#include <regex>
|
||||
|
||||
namespace Void::Build::SelfHost {
|
||||
|
||||
Void::Result::Result<std::vector<DiscoveredTestCase>, Void::Result::Error>
|
||||
scan_void_tests(const std::filesystem::path &source_file) {
|
||||
auto text = Void::FileSystem::read_file(source_file);
|
||||
if (!text) {
|
||||
return std::unexpected{text.error()};
|
||||
}
|
||||
|
||||
const std::string suite = source_file.stem().string();
|
||||
const std::regex pattern{
|
||||
R"((?:^|[\r\n])\s*(?:Void::Testing::)?Test\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(\s*\))"};
|
||||
|
||||
std::vector<DiscoveredTestCase> found;
|
||||
std::size_t line_no = 1;
|
||||
std::size_t pos = 0;
|
||||
|
||||
while (pos < text->size()) {
|
||||
const auto nl = text->find('\n', pos);
|
||||
const auto line =
|
||||
std::string{text->substr(pos, nl == std::string::npos ? std::string::npos : nl - pos)};
|
||||
std::smatch m;
|
||||
if (std::regex_search(line, m, pattern)) {
|
||||
found.push_back(DiscoveredTestCase{suite, m[1].str(), source_file, line_no});
|
||||
}
|
||||
if (nl == std::string::npos) {
|
||||
break;
|
||||
}
|
||||
pos = nl + 1;
|
||||
++line_no;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
Void::Result::Result<GeneratedRegistration, Void::Result::Error>
|
||||
generate_test_registration_unit(const std::filesystem::path &source_file,
|
||||
const std::filesystem::path &output_dir) {
|
||||
auto cases_res = scan_void_tests(source_file);
|
||||
if (!cases_res) {
|
||||
return std::unexpected{cases_res.error()};
|
||||
}
|
||||
|
||||
std::error_code ec;
|
||||
const auto abs_src = std::filesystem::weakly_canonical(source_file, ec);
|
||||
const std::string path_hash = Util::sha256_hex(abs_src.string()).substr(0, 12);
|
||||
const auto out_cpp =
|
||||
output_dir / (source_file.stem().string() + "_" + path_hash + ".void_tests.cpp");
|
||||
|
||||
std::string code =
|
||||
"// Auto-generated by VoidBuildSystem native Void::Testing registration generator\n"
|
||||
"#include <Void/Testing/Detail/Registrar.hpp>\n"
|
||||
"#include <Void/Testing/Test.hpp>\n"
|
||||
"#include <string>\n"
|
||||
"#include <vector>\n\n";
|
||||
|
||||
for (const auto &c : *cases_res) {
|
||||
code += "Void::Testing::Test " + c.function_name + "();\n";
|
||||
}
|
||||
code += "\nnamespace {\n";
|
||||
for (std::size_t i = 0; i < cases_res->size(); ++i) {
|
||||
const auto &c = (*cases_res)[i];
|
||||
code += std::format("static Void::Testing::Detail::test_registrar<&{}> _vbs_reg_{}_{}{{\n"
|
||||
" {}, {}, {}, {}, std::vector<std::string>{{}}, false, \"\"\n"
|
||||
"}};\n",
|
||||
c.function_name, path_hash, i, Util::json_quote(c.suite_name),
|
||||
Util::json_quote(abs_src.string()), c.line_number,
|
||||
Util::json_quote(c.function_name));
|
||||
}
|
||||
code += "} // namespace\n";
|
||||
|
||||
auto wrote = Platform::atomic_write_file(out_cpp, code, false);
|
||||
if (!wrote) {
|
||||
return std::unexpected{wrote.error()};
|
||||
}
|
||||
return GeneratedRegistration{out_cpp, std::move(*cases_res)};
|
||||
}
|
||||
|
||||
} // namespace Void::Build::SelfHost
|
||||
@@ -0,0 +1,661 @@
|
||||
#include <Void/Build/Snapshot/Snapshot.hpp>
|
||||
|
||||
#include <Void/Build/Platform/FileOps.hpp>
|
||||
#include <Void/Build/Util/Json.hpp>
|
||||
#include <Void/Build/Util/Sha256.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cerrno>
|
||||
#include <dirent.h>
|
||||
#include <fcntl.h>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <set>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace Void::Build::Snapshot {
|
||||
namespace {
|
||||
|
||||
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg, int err = 0) {
|
||||
return Void::System::make_system_error(code, std::move(msg), err);
|
||||
}
|
||||
|
||||
bool is_excluded_name(std::string_view name, const std::vector<std::string> &excluded) {
|
||||
if (name == ".env" || name.starts_with(".env.")) {
|
||||
return name != ".env.example";
|
||||
}
|
||||
if (name.ends_with(".pem") || name.ends_with(".key")) {
|
||||
return true;
|
||||
}
|
||||
return std::ranges::contains(excluded, name);
|
||||
}
|
||||
|
||||
bool path_has_excluded_component(const std::filesystem::path &rel_path,
|
||||
const std::vector<std::string> &excluded) {
|
||||
for (const auto &part : rel_path) {
|
||||
const auto s = part.string();
|
||||
if (s.empty() || s == ".") {
|
||||
continue;
|
||||
}
|
||||
if (is_excluded_name(s, excluded)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::vector<std::string>, Void::Result::Error>
|
||||
read_sorted_dir_entries(const std::filesystem::path &dir_path,
|
||||
const std::vector<std::string> &excluded) {
|
||||
const int fd = ::open(dir_path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{make_error(
|
||||
Void::System::map_errno_to_system_code(err),
|
||||
std::format("snapshot: cannot open directory '{}'", dir_path.string()), err)};
|
||||
}
|
||||
DIR *dir = ::fdopendir(fd);
|
||||
if (!dir) {
|
||||
const int err = errno;
|
||||
(void)::close(fd);
|
||||
return std::unexpected{
|
||||
make_error(Void::System::map_errno_to_system_code(err),
|
||||
std::format("snapshot: fdopendir failed for '{}'", dir_path.string()), err)};
|
||||
}
|
||||
std::vector<std::string> names;
|
||||
errno = 0;
|
||||
while (const struct dirent *ent = ::readdir(dir)) {
|
||||
const std::string_view name{ent->d_name};
|
||||
if (name == "." || name == "..") {
|
||||
continue;
|
||||
}
|
||||
if (is_excluded_name(name, excluded)) {
|
||||
continue;
|
||||
}
|
||||
names.emplace_back(name);
|
||||
}
|
||||
const int read_err = errno;
|
||||
(void)::closedir(dir);
|
||||
if (read_err != 0) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::map_errno_to_system_code(read_err),
|
||||
std::format("snapshot: readdir failed for '{}'", dir_path.string()), read_err)};
|
||||
}
|
||||
std::ranges::sort(names);
|
||||
return names;
|
||||
}
|
||||
|
||||
std::string normalize_logical(const std::filesystem::path &rel) {
|
||||
std::string s = rel.lexically_normal().generic_string();
|
||||
if (s == ".") {
|
||||
return "";
|
||||
}
|
||||
if (s.starts_with("./")) {
|
||||
s.erase(0, 2);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
std::string compute_snapshot_id(const InputSnapshot &snap) {
|
||||
Util::Sha256Hasher hasher;
|
||||
hasher.update_length_prefixed("vbs-snapshot-v1");
|
||||
hasher.update_u64(static_cast<std::uint64_t>(snap.reproducibility_epoch));
|
||||
hasher.update_u64(snap.entries.size());
|
||||
for (const auto &[logical, entry] : snap.entries) {
|
||||
hasher.update_length_prefixed(logical);
|
||||
hasher.update_u64(static_cast<std::uint64_t>(entry.kind));
|
||||
hasher.update_length_prefixed(entry.sha256);
|
||||
hasher.update_u64(entry.size);
|
||||
hasher.update_u64(entry.mode & 0777u);
|
||||
hasher.update_length_prefixed(entry.symlink_target);
|
||||
}
|
||||
hasher.update_u64(snap.memberships.size());
|
||||
for (const auto &[dir, mem] : snap.memberships) {
|
||||
hasher.update_length_prefixed(dir);
|
||||
hasher.update_u64(mem.entries.size());
|
||||
for (const auto &name : mem.entries) {
|
||||
hasher.update_length_prefixed(name);
|
||||
}
|
||||
}
|
||||
hasher.update_u64(snap.lookup_guards.size());
|
||||
for (const auto &guard : snap.lookup_guards) {
|
||||
hasher.update_u64(guard.search_roots.size());
|
||||
for (const auto &r : guard.search_roots) {
|
||||
hasher.update_length_prefixed(r);
|
||||
}
|
||||
hasher.update_length_prefixed(guard.lookup_name);
|
||||
hasher.update_u64(static_cast<std::uint64_t>(guard.matched_root_index + 1));
|
||||
hasher.update_length_prefixed(guard.matched_sha256);
|
||||
}
|
||||
return hasher.finalize_hex();
|
||||
}
|
||||
|
||||
Void::Result::Result<LookupGuard, Void::Result::Error>
|
||||
evaluate_one_guard(const std::filesystem::path &project_root,
|
||||
const std::vector<std::filesystem::path> &allowed_external_roots,
|
||||
const std::vector<std::string> &search_roots, const std::string &lookup_name) {
|
||||
LookupGuard guard;
|
||||
guard.search_roots = search_roots;
|
||||
guard.lookup_name = lookup_name;
|
||||
guard.matched_root_index = -1;
|
||||
|
||||
for (std::size_t i = 0; i < search_roots.size(); ++i) {
|
||||
const std::filesystem::path root_path{search_roots[i]};
|
||||
const auto abs_root = root_path.is_absolute() ? root_path : (project_root / root_path);
|
||||
const auto candidate = abs_root / lookup_name;
|
||||
auto meta = Platform::stat_lstat(candidate);
|
||||
if (!meta) {
|
||||
return std::unexpected{meta.error()};
|
||||
}
|
||||
if (!meta->exists) {
|
||||
continue;
|
||||
}
|
||||
auto confined =
|
||||
Platform::resolve_confined_path(project_root, candidate, allowed_external_roots);
|
||||
if (!confined) {
|
||||
return std::unexpected{confined.error()};
|
||||
}
|
||||
auto target_meta = Platform::stat_lstat(*confined);
|
||||
if (!target_meta) {
|
||||
return std::unexpected{target_meta.error()};
|
||||
}
|
||||
if (target_meta->exists && target_meta->is_regular) {
|
||||
auto digest = Util::sha256_file_hex(*confined);
|
||||
if (!digest) {
|
||||
return std::unexpected{digest.error()};
|
||||
}
|
||||
guard.matched_root_index = static_cast<int>(i);
|
||||
guard.matched_sha256 = std::move(*digest);
|
||||
return guard;
|
||||
}
|
||||
}
|
||||
return guard;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<InputSnapshot, Void::Result::Error> capture_snapshot(
|
||||
const SnapshotOptions &options, const std::vector<std::filesystem::path> &explicit_files,
|
||||
const std::vector<std::filesystem::path> &directory_roots,
|
||||
const std::vector<std::pair<std::vector<std::string>, std::string>> &lookup_queries) {
|
||||
std::error_code ec;
|
||||
const auto canonical_root = std::filesystem::weakly_canonical(options.project_root, ec);
|
||||
if (ec || !std::filesystem::is_directory(canonical_root)) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::not_found,
|
||||
std::format("snapshot: project root '{}' is not a directory",
|
||||
options.project_root.string()))};
|
||||
}
|
||||
|
||||
const int attempts = std::max(1, options.max_revalidate_retries);
|
||||
for (int attempt = 0; attempt < attempts; ++attempt) {
|
||||
InputSnapshot snap;
|
||||
snap.project_root = canonical_root;
|
||||
snap.reproducibility_epoch = options.reproducibility_epoch;
|
||||
|
||||
std::map<std::string, std::filesystem::path, std::less<>> source_files_to_verify;
|
||||
std::map<std::string, std::filesystem::path, std::less<>> dirs_to_verify;
|
||||
|
||||
auto capture_single_file = [&](const std::filesystem::path &raw_path)
|
||||
-> Void::Result::Result<void, Void::Result::Error> {
|
||||
const auto abs_path = raw_path.is_absolute() ? raw_path : (canonical_root / raw_path);
|
||||
auto lmeta = Platform::stat_lstat(abs_path);
|
||||
if (!lmeta) {
|
||||
return std::unexpected{lmeta.error()};
|
||||
}
|
||||
if (!lmeta->exists) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::not_found,
|
||||
std::format("snapshot: required input '{}' does not exist", raw_path.string()),
|
||||
ENOENT)};
|
||||
}
|
||||
auto confined = Platform::resolve_confined_path(canonical_root, abs_path,
|
||||
options.allowed_external_roots);
|
||||
if (!confined) {
|
||||
return std::unexpected{confined.error()};
|
||||
}
|
||||
std::filesystem::path rel = abs_path.lexically_relative(canonical_root);
|
||||
std::string logical = normalize_logical(rel);
|
||||
if (logical.empty() || logical.starts_with("..")) {
|
||||
logical = "external/" + Util::sha256_hex(confined->string()).substr(0, 16) + "/" +
|
||||
confined->filename().string();
|
||||
}
|
||||
|
||||
if (lmeta->is_symlink) {
|
||||
SnapshotEntry sym;
|
||||
sym.logical_path = logical;
|
||||
sym.kind = EntryKind::Symlink;
|
||||
sym.symlink_target = lmeta->symlink_target;
|
||||
sym.mode = lmeta->mode;
|
||||
// Hash the resolved target content if it is a regular file so retargeting or
|
||||
// editing target bytes invalidates the snapshot.
|
||||
auto target_meta = Platform::stat_lstat(*confined);
|
||||
if (!target_meta) {
|
||||
return std::unexpected{target_meta.error()};
|
||||
}
|
||||
if (target_meta->exists && target_meta->is_regular) {
|
||||
auto digest = Util::sha256_file_hex(*confined);
|
||||
if (!digest) {
|
||||
return std::unexpected{digest.error()};
|
||||
}
|
||||
sym.sha256 = std::move(*digest);
|
||||
sym.size = target_meta->size;
|
||||
source_files_to_verify[logical] = *confined;
|
||||
}
|
||||
snap.entries[logical] = std::move(sym);
|
||||
return {};
|
||||
}
|
||||
|
||||
if (!lmeta->is_regular) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("snapshot: '{}' is not a regular file or symlink",
|
||||
abs_path.string()))};
|
||||
}
|
||||
|
||||
SnapshotEntry entry;
|
||||
entry.logical_path = logical;
|
||||
entry.kind = EntryKind::RegularFile;
|
||||
entry.size = lmeta->size;
|
||||
entry.mode = lmeta->mode;
|
||||
|
||||
if (options.materialize) {
|
||||
const auto staging_blob =
|
||||
options.snapshot_store_dir / "blobs" /
|
||||
(Util::sha256_hex(logical + "#" + std::to_string(attempt)) + ".stage");
|
||||
auto copied = Platform::copy_isolated(*confined, staging_blob, entry.mode);
|
||||
if (!copied) {
|
||||
return std::unexpected{copied.error()};
|
||||
}
|
||||
auto digest = Util::sha256_file_hex(staging_blob);
|
||||
if (!digest) {
|
||||
std::filesystem::remove(staging_blob, ec);
|
||||
return std::unexpected{digest.error()};
|
||||
}
|
||||
entry.sha256 = std::move(*digest);
|
||||
const auto final_blob =
|
||||
options.snapshot_store_dir / "blobs" / entry.sha256.substr(0, 2) / entry.sha256;
|
||||
std::filesystem::create_directories(final_blob.parent_path(), ec);
|
||||
if (!std::filesystem::exists(final_blob, ec)) {
|
||||
(void)Platform::set_canonical_mtime(staging_blob,
|
||||
options.reproducibility_epoch);
|
||||
std::filesystem::rename(staging_blob, final_blob, ec);
|
||||
if (ec) {
|
||||
std::filesystem::remove(staging_blob, ec);
|
||||
}
|
||||
} else {
|
||||
std::filesystem::remove(staging_blob, ec);
|
||||
}
|
||||
entry.materialized_path = final_blob;
|
||||
} else {
|
||||
auto digest = Util::sha256_file_hex(*confined);
|
||||
if (!digest) {
|
||||
return std::unexpected{digest.error()};
|
||||
}
|
||||
entry.sha256 = std::move(*digest);
|
||||
}
|
||||
|
||||
source_files_to_verify[logical] = *confined;
|
||||
snap.entries[logical] = std::move(entry);
|
||||
return {};
|
||||
};
|
||||
|
||||
std::function<Void::Result::Result<void, Void::Result::Error>(
|
||||
const std::filesystem::path &, std::set<std::pair<std::uint64_t, std::uint64_t>> &)>
|
||||
walk_dir;
|
||||
walk_dir = [&](const std::filesystem::path &dir_path,
|
||||
std::set<std::pair<std::uint64_t, std::uint64_t>> &visited_dirs)
|
||||
-> Void::Result::Result<void, Void::Result::Error> {
|
||||
auto confined = Platform::resolve_confined_path(canonical_root, dir_path,
|
||||
options.allowed_external_roots);
|
||||
if (!confined) {
|
||||
return std::unexpected{confined.error()};
|
||||
}
|
||||
auto meta = Platform::stat_lstat(*confined);
|
||||
if (!meta) {
|
||||
return std::unexpected{meta.error()};
|
||||
}
|
||||
if (!meta->exists) {
|
||||
// Record empty membership for absent search roots so creation invalidates.
|
||||
const std::string logical_dir =
|
||||
normalize_logical(dir_path.lexically_relative(canonical_root));
|
||||
snap.memberships[logical_dir] = DirectoryMembership{logical_dir, {}};
|
||||
dirs_to_verify[logical_dir] = dir_path;
|
||||
return {};
|
||||
}
|
||||
if (!meta->is_directory) {
|
||||
return {};
|
||||
}
|
||||
if (!visited_dirs.insert({meta->dev, meta->ino}).second) {
|
||||
return {};
|
||||
}
|
||||
|
||||
auto entries_res = read_sorted_dir_entries(*confined, options.excluded_names);
|
||||
if (!entries_res) {
|
||||
return std::unexpected{entries_res.error()};
|
||||
}
|
||||
const std::string logical_dir =
|
||||
normalize_logical(dir_path.lexically_relative(canonical_root));
|
||||
snap.memberships[logical_dir] = DirectoryMembership{logical_dir, *entries_res};
|
||||
dirs_to_verify[logical_dir] = *confined;
|
||||
|
||||
for (const auto &name : *entries_res) {
|
||||
const auto child = dir_path / name;
|
||||
const auto child_rel = child.lexically_relative(canonical_root);
|
||||
if (path_has_excluded_component(child_rel, options.excluded_names)) {
|
||||
continue;
|
||||
}
|
||||
auto cmeta = Platform::stat_lstat(child);
|
||||
if (!cmeta) {
|
||||
return std::unexpected{cmeta.error()};
|
||||
}
|
||||
if (!cmeta->exists) {
|
||||
continue;
|
||||
}
|
||||
if (cmeta->is_directory) {
|
||||
auto sub = walk_dir(child, visited_dirs);
|
||||
if (!sub) {
|
||||
return sub;
|
||||
}
|
||||
} else if (cmeta->is_regular || cmeta->is_symlink) {
|
||||
auto cap = capture_single_file(child);
|
||||
if (!cap) {
|
||||
return cap;
|
||||
}
|
||||
}
|
||||
}
|
||||
return {};
|
||||
};
|
||||
|
||||
for (const auto &file : explicit_files) {
|
||||
auto r = capture_single_file(file);
|
||||
if (!r) {
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
}
|
||||
std::set<std::pair<std::uint64_t, std::uint64_t>> visited_dirs;
|
||||
for (const auto &root : directory_roots) {
|
||||
const auto abs_dir = root.is_absolute() ? root : (canonical_root / root);
|
||||
auto r = walk_dir(abs_dir, visited_dirs);
|
||||
if (!r) {
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
}
|
||||
for (const auto &[search_roots, lookup_name] : lookup_queries) {
|
||||
auto guard = evaluate_one_guard(canonical_root, options.allowed_external_roots,
|
||||
search_roots, lookup_name);
|
||||
if (!guard) {
|
||||
return std::unexpected{guard.error()};
|
||||
}
|
||||
snap.lookup_guards.push_back(std::move(*guard));
|
||||
}
|
||||
|
||||
// Revalidation pass before sealing: detect concurrent mutations during capture.
|
||||
bool mutated = false;
|
||||
for (const auto &[logical, src_path] : source_files_to_verify) {
|
||||
auto rehash = Util::sha256_file_hex(src_path);
|
||||
if (!rehash || *rehash != snap.entries.at(logical).sha256) {
|
||||
mutated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!mutated) {
|
||||
for (const auto &[logical_dir, dir_path] : dirs_to_verify) {
|
||||
auto meta = Platform::stat_lstat(dir_path);
|
||||
if (!meta) {
|
||||
mutated = true;
|
||||
break;
|
||||
}
|
||||
if (!meta->exists) {
|
||||
if (!snap.memberships.at(logical_dir).entries.empty()) {
|
||||
mutated = true;
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
auto cur = read_sorted_dir_entries(dir_path, options.excluded_names);
|
||||
if (!cur || *cur != snap.memberships.at(logical_dir).entries) {
|
||||
mutated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (mutated) {
|
||||
continue;
|
||||
}
|
||||
|
||||
snap.snapshot_id = compute_snapshot_id(snap);
|
||||
|
||||
// Materialize a per-snapshot logical tree using private copies/reflinks (no hardlinks)
|
||||
// with canonical mtime so compiler builds see isolated, immutable bytes.
|
||||
if (options.materialize) {
|
||||
snap.materialized_root = options.snapshot_store_dir / "trees" / snap.snapshot_id;
|
||||
const auto seal_marker = snap.materialized_root / ".sealed";
|
||||
if (!std::filesystem::exists(seal_marker, ec)) {
|
||||
const auto tmp_tree = options.snapshot_store_dir / "trees" /
|
||||
(snap.snapshot_id + ".staging_" +
|
||||
std::to_string(static_cast<long long>(::getpid())));
|
||||
std::filesystem::remove_all(tmp_tree, ec);
|
||||
std::filesystem::create_directories(tmp_tree, ec);
|
||||
|
||||
for (auto &[logical, entry] : snap.entries) {
|
||||
const auto dst = tmp_tree / logical;
|
||||
std::filesystem::create_directories(dst.parent_path(), ec);
|
||||
if (entry.kind == EntryKind::RegularFile && !entry.materialized_path.empty()) {
|
||||
auto copied =
|
||||
Platform::copy_isolated(entry.materialized_path, dst, entry.mode);
|
||||
if (!copied) {
|
||||
std::filesystem::remove_all(tmp_tree, ec);
|
||||
return std::unexpected{copied.error()};
|
||||
}
|
||||
(void)Platform::set_canonical_mtime(dst, options.reproducibility_epoch);
|
||||
} else if (entry.kind == EntryKind::Symlink) {
|
||||
if (!entry.sha256.empty()) {
|
||||
// Materialize symlinked regular file target inside snapshot tree
|
||||
// safely.
|
||||
const auto src_target = source_files_to_verify.find(logical);
|
||||
if (src_target != source_files_to_verify.end()) {
|
||||
auto copied =
|
||||
Platform::copy_isolated(src_target->second, dst, entry.mode);
|
||||
if (!copied) {
|
||||
std::filesystem::remove_all(tmp_tree, ec);
|
||||
return std::unexpected{copied.error()};
|
||||
}
|
||||
(void)Platform::set_canonical_mtime(dst,
|
||||
options.reproducibility_epoch);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(void)Platform::atomic_write_file(tmp_tree / ".sealed", snap.snapshot_id + "\n",
|
||||
false);
|
||||
std::filesystem::rename(tmp_tree, snap.materialized_root, ec);
|
||||
if (ec) {
|
||||
// Another concurrent worker may have sealed the identical content-addressed
|
||||
// tree.
|
||||
std::filesystem::remove_all(tmp_tree, ec);
|
||||
if (!std::filesystem::exists(seal_marker, ec)) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error,
|
||||
std::format("snapshot: failed publishing tree '{}'",
|
||||
snap.materialized_root.string()))};
|
||||
}
|
||||
}
|
||||
}
|
||||
for (auto &[logical, entry] : snap.entries) {
|
||||
entry.materialized_path = snap.materialized_root / logical;
|
||||
}
|
||||
(void)write_snapshot_manifest(snap, options.snapshot_store_dir);
|
||||
}
|
||||
|
||||
return snap;
|
||||
}
|
||||
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::busy,
|
||||
std::format("snapshot: source tree remained unstable across {} revalidation retries",
|
||||
attempts))};
|
||||
}
|
||||
|
||||
Void::Result::Result<bool, Void::Result::Error> is_snapshot_fresh(const InputSnapshot &snapshot,
|
||||
const SnapshotOptions &options) {
|
||||
for (const auto &[logical, entry] : snapshot.entries) {
|
||||
if (logical.starts_with("external/")) {
|
||||
continue;
|
||||
}
|
||||
const auto live_path = snapshot.project_root / logical;
|
||||
auto meta = Platform::stat_lstat(live_path);
|
||||
if (!meta) {
|
||||
return std::unexpected{meta.error()};
|
||||
}
|
||||
if (!meta->exists) {
|
||||
return false;
|
||||
}
|
||||
if (entry.kind == EntryKind::Symlink) {
|
||||
if (!meta->is_symlink || meta->symlink_target != entry.symlink_target) {
|
||||
return false;
|
||||
}
|
||||
auto confined = Platform::resolve_confined_path(snapshot.project_root, live_path,
|
||||
options.allowed_external_roots);
|
||||
if (!confined) {
|
||||
return std::unexpected{confined.error()};
|
||||
}
|
||||
if (!entry.sha256.empty()) {
|
||||
auto rehash = Util::sha256_file_hex(*confined);
|
||||
if (!rehash || *rehash != entry.sha256) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else if (entry.kind == EntryKind::RegularFile) {
|
||||
if (!meta->is_regular || meta->size != entry.size) {
|
||||
return false;
|
||||
}
|
||||
// Content verification: NEVER shortcut on mtime/size alone (catches restored-mtime
|
||||
// edits!).
|
||||
auto rehash = Util::sha256_file_hex(live_path);
|
||||
if (!rehash) {
|
||||
return std::unexpected{rehash.error()};
|
||||
}
|
||||
if (*rehash != entry.sha256) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto &[logical_dir, mem] : snapshot.memberships) {
|
||||
const auto live_dir =
|
||||
logical_dir.empty() ? snapshot.project_root : (snapshot.project_root / logical_dir);
|
||||
auto meta = Platform::stat_lstat(live_dir);
|
||||
if (!meta) {
|
||||
return std::unexpected{meta.error()};
|
||||
}
|
||||
if (!meta->exists) {
|
||||
if (!mem.entries.empty()) {
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!meta->is_directory) {
|
||||
return false;
|
||||
}
|
||||
auto live_entries = read_sorted_dir_entries(live_dir, options.excluded_names);
|
||||
if (!live_entries) {
|
||||
return std::unexpected{live_entries.error()};
|
||||
}
|
||||
if (*live_entries != mem.entries) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto &guard : snapshot.lookup_guards) {
|
||||
auto live = evaluate_one_guard(snapshot.project_root, options.allowed_external_roots,
|
||||
guard.search_roots, guard.lookup_name);
|
||||
if (!live) {
|
||||
return std::unexpected{live.error()};
|
||||
}
|
||||
if (live->matched_root_index != guard.matched_root_index ||
|
||||
live->matched_sha256 != guard.matched_sha256) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
Void::Result::Result<SnapshotEntry, Void::Result::Error>
|
||||
seal_generated_artifact(const std::filesystem::path &staged_file, std::string logical_path,
|
||||
const std::filesystem::path &snapshot_store_dir,
|
||||
std::int64_t reproducibility_epoch) {
|
||||
auto meta = Platform::stat_lstat(staged_file);
|
||||
if (!meta) {
|
||||
return std::unexpected{meta.error()};
|
||||
}
|
||||
if (!meta->exists || !meta->is_regular) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::not_found,
|
||||
std::format("seal_generated_artifact: '{}' is missing or not a regular file",
|
||||
staged_file.string()))};
|
||||
}
|
||||
auto digest = Util::sha256_file_hex(staged_file);
|
||||
if (!digest) {
|
||||
return std::unexpected{digest.error()};
|
||||
}
|
||||
|
||||
const auto dst = snapshot_store_dir / "generated" / digest->substr(0, 2) / *digest;
|
||||
std::error_code ec;
|
||||
if (!std::filesystem::exists(dst, ec)) {
|
||||
auto copied = Platform::copy_isolated(staged_file, dst, meta->mode);
|
||||
if (!copied) {
|
||||
return std::unexpected{copied.error()};
|
||||
}
|
||||
(void)Platform::set_canonical_mtime(dst, reproducibility_epoch);
|
||||
}
|
||||
|
||||
SnapshotEntry entry;
|
||||
entry.logical_path = std::move(logical_path);
|
||||
entry.kind = EntryKind::RegularFile;
|
||||
entry.sha256 = std::move(*digest);
|
||||
entry.size = meta->size;
|
||||
entry.mode = meta->mode;
|
||||
entry.materialized_path = dst;
|
||||
return entry;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::filesystem::path, Void::Result::Error>
|
||||
write_snapshot_manifest(const InputSnapshot &snapshot,
|
||||
const std::filesystem::path &snapshot_store_dir) {
|
||||
using Util::json_array;
|
||||
using Util::json_quote;
|
||||
|
||||
std::string json =
|
||||
"{\"schema_version\":1,\"snapshot_id\":" + json_quote(snapshot.snapshot_id) +
|
||||
",\"reproducibility_epoch\":" + std::to_string(snapshot.reproducibility_epoch) +
|
||||
",\"entries\":";
|
||||
std::vector<const SnapshotEntry *> entry_list;
|
||||
for (const auto &[k, v] : snapshot.entries) {
|
||||
entry_list.push_back(&v);
|
||||
}
|
||||
json += json_array(entry_list, [](const SnapshotEntry *e) {
|
||||
return "{\"logical_path\":" + json_quote(e->logical_path) +
|
||||
",\"sha256\":" + json_quote(e->sha256) + ",\"size\":" + std::to_string(e->size) +
|
||||
",\"symlink_target\":" + json_quote(e->symlink_target) + '}';
|
||||
});
|
||||
json += ",\"lookup_guards\":";
|
||||
json += json_array(snapshot.lookup_guards, [](const LookupGuard &g) {
|
||||
return "{\"lookup_name\":" + json_quote(g.lookup_name) +
|
||||
",\"matched_root_index\":" + std::to_string(g.matched_root_index) +
|
||||
",\"matched_sha256\":" + json_quote(g.matched_sha256) + '}';
|
||||
});
|
||||
json += "}\n";
|
||||
|
||||
const auto manifest_path = snapshot_store_dir / "manifests" / (snapshot.snapshot_id + ".json");
|
||||
auto written = Platform::atomic_write_file(manifest_path, json, true);
|
||||
if (!written) {
|
||||
return std::unexpected{written.error()};
|
||||
}
|
||||
return manifest_path;
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Snapshot
|
||||
@@ -0,0 +1,750 @@
|
||||
#include <Void/Build/State/StateStore.hpp>
|
||||
|
||||
#include <Void/Build/Platform/FileOps.hpp>
|
||||
#include <Void/Build/Util/Json.hpp>
|
||||
#include <Void/Build/Util/Sha256.hpp>
|
||||
#include <Void/Data/StrictJson.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <csignal>
|
||||
#include <format>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Build::State {
|
||||
namespace {
|
||||
|
||||
std::atomic<std::uint64_t> g_lease_seq{0};
|
||||
|
||||
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg, int err = 0) {
|
||||
return Void::System::make_system_error(code, std::move(msg), err);
|
||||
}
|
||||
|
||||
bool is_valid_sha256_hex(std::string_view hex) {
|
||||
if (hex.size() != 64) {
|
||||
return false;
|
||||
}
|
||||
return std::ranges::all_of(
|
||||
hex, [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); });
|
||||
}
|
||||
|
||||
bool pid_is_alive(pid_t pid) noexcept {
|
||||
if (pid <= 0) {
|
||||
return false;
|
||||
}
|
||||
if (::kill(pid, 0) == 0) {
|
||||
return true;
|
||||
}
|
||||
return errno != ESRCH;
|
||||
}
|
||||
|
||||
std::string serialize_action(const ActionSuccessRecord &rec) {
|
||||
using Util::json_array;
|
||||
using Util::json_quote;
|
||||
|
||||
std::string out = "{\"action_key\":" + json_quote(rec.action_key) +
|
||||
",\"profile_identity\":" + json_quote(rec.profile_identity) +
|
||||
",\"target_name\":" + json_quote(rec.target_name) +
|
||||
",\"recorded_epoch\":" + std::to_string(rec.recorded_epoch) +
|
||||
",\"outputs\":{";
|
||||
bool first = true;
|
||||
for (const auto &[path, ref] : rec.outputs) {
|
||||
if (!first) {
|
||||
out += ',';
|
||||
}
|
||||
first = false;
|
||||
out += json_quote(path) + ":{\"sha256\":" + json_quote(ref.sha256) +
|
||||
",\"size\":" + std::to_string(ref.size) + ",\"mode\":" + std::to_string(ref.mode) +
|
||||
'}';
|
||||
}
|
||||
out += "},\"discovered_inputs\":{";
|
||||
first = true;
|
||||
for (const auto &[path, digest] : rec.discovered_inputs) {
|
||||
if (!first) {
|
||||
out += ',';
|
||||
}
|
||||
first = false;
|
||||
out += json_quote(path) + ':' + json_quote(digest);
|
||||
}
|
||||
out += "},\"lookup_guards\":";
|
||||
out += json_array(rec.lookup_guards, [](const Snapshot::LookupGuard &g) {
|
||||
return "{\"search_roots\":" + json_array(g.search_roots, json_quote) +
|
||||
",\"lookup_name\":" + json_quote(g.lookup_name) +
|
||||
",\"matched_root_index\":" + std::to_string(g.matched_root_index) +
|
||||
",\"matched_sha256\":" + json_quote(g.matched_sha256) + '}';
|
||||
});
|
||||
out += '}';
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string serialize_generation(const GraphGenerationRecord &gen) {
|
||||
using Util::json_quote;
|
||||
return "{\"generation_id\":" + json_quote(gen.generation_id) +
|
||||
",\"profile_name\":" + json_quote(gen.profile_name) +
|
||||
",\"profile_identity\":" + json_quote(gen.profile_identity) +
|
||||
",\"snapshot_id\":" + json_quote(gen.snapshot_id) +
|
||||
",\"status\":" + json_quote(gen.status) +
|
||||
",\"diagnostic\":" + json_quote(gen.diagnostic) +
|
||||
",\"sequence\":" + std::to_string(gen.sequence) + '}';
|
||||
}
|
||||
|
||||
using JsonVal = Void::Json::Strict::Value;
|
||||
|
||||
const JsonVal *find_key(const JsonVal::Object &obj, const std::string &key) {
|
||||
const auto it = obj.find(key);
|
||||
return it == obj.end() ? nullptr : &it->second;
|
||||
}
|
||||
|
||||
std::optional<std::string> get_str(const JsonVal::Object &obj, const std::string &key) {
|
||||
const auto *v = find_key(obj, key);
|
||||
if (!v) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto *s = std::get_if<std::string>(&v->value);
|
||||
return s ? std::optional<std::string>{*s} : std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<std::int64_t> get_i64(const JsonVal::Object &obj, const std::string &key) {
|
||||
const auto *v = find_key(obj, key);
|
||||
if (!v) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto *i = std::get_if<std::int64_t>(&v->value);
|
||||
return i ? std::optional<std::int64_t>{*i} : std::nullopt;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
LeaseHandle::~LeaseHandle() noexcept { release(); }
|
||||
|
||||
LeaseHandle::LeaseHandle(LeaseHandle &&other) noexcept
|
||||
: lease_id{std::move(other.lease_id)}, lease_file{std::exchange(other.lease_file, {})} {}
|
||||
|
||||
LeaseHandle &LeaseHandle::operator=(LeaseHandle &&other) noexcept {
|
||||
if (this != &other) {
|
||||
release();
|
||||
lease_id = std::move(other.lease_id);
|
||||
lease_file = std::exchange(other.lease_file, {});
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
void LeaseHandle::release() noexcept {
|
||||
if (!lease_file.empty()) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(lease_file, ec);
|
||||
lease_file.clear();
|
||||
}
|
||||
}
|
||||
|
||||
StateStore::StateStore(std::filesystem::path root)
|
||||
: root_{std::move(root)}, cas_dir_{root_ / "cas" / "blobs"}, staging_dir_{root_ / "staging"},
|
||||
leases_dir_{root_ / "leases"}, db_file_{root_ / "state" / "state.v1.json"},
|
||||
lock_file_{root_ / "state" / "state.lock"} {}
|
||||
|
||||
Void::Result::Result<StateStore, Void::Result::Error>
|
||||
StateStore::open(const std::filesystem::path &vbs_dir) {
|
||||
StateStore store{vbs_dir};
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(store.cas_dir_, ec);
|
||||
std::filesystem::create_directories(store.staging_dir_, ec);
|
||||
std::filesystem::create_directories(store.leases_dir_, ec);
|
||||
std::filesystem::create_directories(store.db_file_.parent_path(), ec);
|
||||
if (ec) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::map_errno_to_system_code(ec.value()),
|
||||
std::format("StateStore::open: cannot create directories under '{}': {}",
|
||||
vbs_dir.string(), ec.message()),
|
||||
ec.value())};
|
||||
}
|
||||
|
||||
auto lock = Platform::FileLock::acquire(store.lock_file_, Platform::LockMode::Exclusive);
|
||||
if (!lock) {
|
||||
return std::unexpected{lock.error()};
|
||||
}
|
||||
|
||||
if (std::filesystem::exists(store.db_file_, ec)) {
|
||||
auto loaded = store.load_db_locked();
|
||||
if (!loaded) {
|
||||
return std::unexpected{loaded.error()};
|
||||
}
|
||||
} else {
|
||||
DatabaseSnapshot initial;
|
||||
auto saved = store.save_db_locked(initial);
|
||||
if (!saved) {
|
||||
return std::unexpected{saved.error()};
|
||||
}
|
||||
}
|
||||
return store;
|
||||
}
|
||||
|
||||
std::filesystem::path StateStore::cas_blob_path(std::string_view sha256) const {
|
||||
if (sha256.size() < 2) {
|
||||
return cas_dir_ / std::string{sha256};
|
||||
}
|
||||
return cas_dir_ / std::string{sha256.substr(0, 2)} / std::string{sha256};
|
||||
}
|
||||
|
||||
Void::Result::Result<StateStore::DatabaseSnapshot, Void::Result::Error>
|
||||
StateStore::load_db_locked() const {
|
||||
auto content = Void::FileSystem::read_file_bounded(db_file_, {128ULL * 1024ULL * 1024ULL});
|
||||
if (!content) {
|
||||
return std::unexpected{content.error()};
|
||||
}
|
||||
if (!Util::is_valid_utf8(*content)) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error,
|
||||
std::format("StateStore: corrupt state database '{}' (invalid UTF-8)",
|
||||
db_file_.string()))};
|
||||
}
|
||||
auto parsed = Void::Json::Strict::parse(*content);
|
||||
if (!parsed) {
|
||||
return std::unexpected{
|
||||
make_error(Void::System::SystemErrorCode::io_error,
|
||||
std::format("StateStore: corrupt state database '{}' (JSON parse failure)",
|
||||
db_file_.string()))};
|
||||
}
|
||||
const auto *root_obj = std::get_if<JsonVal::Object>(&parsed->value);
|
||||
if (!root_obj) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"StateStore: root state must be a JSON object")};
|
||||
}
|
||||
|
||||
const auto version = get_i64(*root_obj, "schema_version");
|
||||
if (!version) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"StateStore: missing schema_version")};
|
||||
}
|
||||
if (*version > kStateSchemaVersion) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("StateStore: unsupported newer schema version {} (supported <= {})",
|
||||
*version, kStateSchemaVersion))};
|
||||
}
|
||||
if (*version < 1) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"StateStore: invalid schema version")};
|
||||
}
|
||||
|
||||
DatabaseSnapshot snap;
|
||||
snap.schema_version = static_cast<int>(*version);
|
||||
snap.next_sequence =
|
||||
static_cast<std::uint64_t>(get_i64(*root_obj, "next_sequence").value_or(1));
|
||||
|
||||
if (const auto *actions_val = find_key(*root_obj, "actions")) {
|
||||
const auto *arr = std::get_if<JsonVal::Array>(&actions_val->value);
|
||||
if (!arr) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"StateStore: corrupt actions array")};
|
||||
}
|
||||
for (const auto &item : *arr) {
|
||||
const auto *obj = std::get_if<JsonVal::Object>(&item.value);
|
||||
if (!obj) {
|
||||
continue;
|
||||
}
|
||||
ActionSuccessRecord rec;
|
||||
rec.action_key = get_str(*obj, "action_key").value_or("");
|
||||
rec.profile_identity = get_str(*obj, "profile_identity").value_or("");
|
||||
rec.target_name = get_str(*obj, "target_name").value_or("");
|
||||
rec.recorded_epoch = get_i64(*obj, "recorded_epoch").value_or(0);
|
||||
if (const auto *outs = find_key(*obj, "outputs")) {
|
||||
if (const auto *oobj = std::get_if<JsonVal::Object>(&outs->value)) {
|
||||
for (const auto &[path, refv] : *oobj) {
|
||||
if (const auto *robj = std::get_if<JsonVal::Object>(&refv.value)) {
|
||||
BlobRef ref;
|
||||
ref.sha256 = get_str(*robj, "sha256").value_or("");
|
||||
ref.size =
|
||||
static_cast<std::uint64_t>(get_i64(*robj, "size").value_or(0));
|
||||
ref.mode =
|
||||
static_cast<std::uint32_t>(get_i64(*robj, "mode").value_or(0644));
|
||||
rec.outputs[path] = std::move(ref);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (const auto *deps = find_key(*obj, "discovered_inputs")) {
|
||||
if (const auto *dobj = std::get_if<JsonVal::Object>(&deps->value)) {
|
||||
for (const auto &[path, dv] : *dobj) {
|
||||
if (const auto *s = std::get_if<std::string>(&dv.value)) {
|
||||
rec.discovered_inputs[path] = *s;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (const auto *guards = find_key(*obj, "lookup_guards")) {
|
||||
if (const auto *garr = std::get_if<JsonVal::Array>(&guards->value)) {
|
||||
for (const auto &gv : *garr) {
|
||||
if (const auto *gobj = std::get_if<JsonVal::Object>(&gv.value)) {
|
||||
Snapshot::LookupGuard g;
|
||||
g.lookup_name = get_str(*gobj, "lookup_name").value_or("");
|
||||
g.matched_root_index =
|
||||
static_cast<int>(get_i64(*gobj, "matched_root_index").value_or(-1));
|
||||
g.matched_sha256 = get_str(*gobj, "matched_sha256").value_or("");
|
||||
if (const auto *sr = find_key(*gobj, "search_roots")) {
|
||||
if (const auto *sarr = std::get_if<JsonVal::Array>(&sr->value)) {
|
||||
for (const auto &rv : *sarr) {
|
||||
if (const auto *rs = std::get_if<std::string>(&rv.value)) {
|
||||
g.search_roots.push_back(*rs);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
rec.lookup_guards.push_back(std::move(g));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!rec.action_key.empty()) {
|
||||
snap.actions[rec.action_key] = std::move(rec);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (const auto *gens_val = find_key(*root_obj, "generations")) {
|
||||
const auto *arr = std::get_if<JsonVal::Array>(&gens_val->value);
|
||||
if (!arr) {
|
||||
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||
"StateStore: corrupt generations array")};
|
||||
}
|
||||
for (const auto &item : *arr) {
|
||||
const auto *obj = std::get_if<JsonVal::Object>(&item.value);
|
||||
if (!obj) {
|
||||
continue;
|
||||
}
|
||||
GraphGenerationRecord gen;
|
||||
gen.generation_id = get_str(*obj, "generation_id").value_or("");
|
||||
gen.profile_name = get_str(*obj, "profile_name").value_or("");
|
||||
gen.profile_identity = get_str(*obj, "profile_identity").value_or("");
|
||||
gen.snapshot_id = get_str(*obj, "snapshot_id").value_or("");
|
||||
gen.status = get_str(*obj, "status").value_or("invalid");
|
||||
gen.diagnostic = get_str(*obj, "diagnostic").value_or("");
|
||||
gen.sequence = static_cast<std::uint64_t>(get_i64(*obj, "sequence").value_or(0));
|
||||
snap.generations.push_back(std::move(gen));
|
||||
}
|
||||
}
|
||||
|
||||
return snap;
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error>
|
||||
StateStore::save_db_locked(const DatabaseSnapshot &db) const {
|
||||
std::string json = "{\"schema_version\":" + std::to_string(db.schema_version) +
|
||||
",\"next_sequence\":" + std::to_string(db.next_sequence) + ",\"actions\":[";
|
||||
bool first = true;
|
||||
for (const auto &[key, rec] : db.actions) {
|
||||
if (!first) {
|
||||
json += ',';
|
||||
}
|
||||
first = false;
|
||||
json += serialize_action(rec);
|
||||
}
|
||||
json += "],\"generations\":[";
|
||||
first = true;
|
||||
for (const auto &gen : db.generations) {
|
||||
if (!first) {
|
||||
json += ',';
|
||||
}
|
||||
first = false;
|
||||
json += serialize_generation(gen);
|
||||
}
|
||||
json += "]}\n";
|
||||
return Platform::atomic_write_file(db_file_, json, true);
|
||||
}
|
||||
|
||||
Void::Result::Result<BlobRef, Void::Result::Error>
|
||||
StateStore::store_blob_from_file(const std::filesystem::path &file_path) {
|
||||
auto meta = Platform::stat_lstat(file_path);
|
||||
if (!meta) {
|
||||
return std::unexpected{meta.error()};
|
||||
}
|
||||
if (!meta->exists || !meta->is_regular) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::not_found,
|
||||
std::format("StateStore: cannot store non-regular file '{}'", file_path.string()))};
|
||||
}
|
||||
|
||||
const auto stage_path =
|
||||
staging_dir_ / std::format("blob_{}_{}.stage", static_cast<long long>(::getpid()),
|
||||
g_lease_seq.fetch_add(1, std::memory_order_relaxed));
|
||||
auto copied = Platform::copy_isolated(file_path, stage_path, meta->mode);
|
||||
if (!copied) {
|
||||
return std::unexpected{copied.error()};
|
||||
}
|
||||
auto digest = Util::sha256_file_hex(stage_path);
|
||||
std::error_code ec;
|
||||
if (!digest) {
|
||||
std::filesystem::remove(stage_path, ec);
|
||||
return std::unexpected{digest.error()};
|
||||
}
|
||||
|
||||
const auto final_path = cas_blob_path(*digest);
|
||||
std::filesystem::create_directories(final_path.parent_path(), ec);
|
||||
if (std::filesystem::exists(final_path, ec)) {
|
||||
// Verify existing blob integrity before deduplicating.
|
||||
auto existing_ok = verify_blob(*digest);
|
||||
if (existing_ok && *existing_ok) {
|
||||
std::filesystem::remove(stage_path, ec);
|
||||
} else {
|
||||
(void)::chmod(final_path.c_str(), 0644);
|
||||
std::filesystem::rename(stage_path, final_path, ec);
|
||||
(void)::chmod(final_path.c_str(), 0444);
|
||||
}
|
||||
} else {
|
||||
(void)::chmod(stage_path.c_str(), 0444);
|
||||
std::filesystem::rename(stage_path, final_path, ec);
|
||||
if (ec) {
|
||||
std::filesystem::remove(stage_path, ec);
|
||||
if (!std::filesystem::exists(final_path, ec)) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::io_error,
|
||||
std::format("StateStore: failed publishing CAS blob '{}'", *digest))};
|
||||
}
|
||||
}
|
||||
(void)Platform::fsync_directory(final_path.parent_path());
|
||||
}
|
||||
|
||||
BlobRef ref;
|
||||
ref.sha256 = std::move(*digest);
|
||||
ref.size = meta->size;
|
||||
ref.mode = meta->mode & 0777u;
|
||||
return ref;
|
||||
}
|
||||
|
||||
Void::Result::Result<bool, Void::Result::Error>
|
||||
StateStore::verify_blob(std::string_view sha256) const {
|
||||
if (!is_valid_sha256_hex(sha256)) {
|
||||
return false;
|
||||
}
|
||||
const auto path = cas_blob_path(sha256);
|
||||
auto meta = Platform::stat_lstat(path);
|
||||
if (!meta) {
|
||||
return std::unexpected{meta.error()};
|
||||
}
|
||||
if (!meta->exists || !meta->is_regular) {
|
||||
return false;
|
||||
}
|
||||
auto actual = Util::sha256_file_hex(path);
|
||||
if (!actual) {
|
||||
return std::unexpected{actual.error()};
|
||||
}
|
||||
return *actual == sha256;
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error>
|
||||
StateStore::materialize_blob(const BlobRef &ref, const std::filesystem::path &destination) const {
|
||||
auto ok = verify_blob(ref.sha256);
|
||||
if (!ok) {
|
||||
return std::unexpected{ok.error()};
|
||||
}
|
||||
if (!*ok) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::io_error,
|
||||
std::format("StateStore: CAS blob '{}' is missing or corrupted", ref.sha256))};
|
||||
}
|
||||
auto copied = Platform::copy_isolated(cas_blob_path(ref.sha256), destination, ref.mode);
|
||||
if (!copied) {
|
||||
return std::unexpected{copied.error()};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<ActionSuccessRecord>, Void::Result::Error>
|
||||
StateStore::lookup_action(std::string_view action_key) const {
|
||||
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Shared);
|
||||
if (!lock) {
|
||||
return std::unexpected{lock.error()};
|
||||
}
|
||||
auto db = load_db_locked();
|
||||
if (!db) {
|
||||
return std::unexpected{db.error()};
|
||||
}
|
||||
const auto it = db->actions.find(action_key);
|
||||
if (it == db->actions.end()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
// Verify every referenced CAS blob still exists and is intact.
|
||||
for (const auto &[out_path, ref] : it->second.outputs) {
|
||||
auto ok = verify_blob(ref.sha256);
|
||||
if (!ok || !*ok) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error>
|
||||
StateStore::record_action_success(const ActionSuccessRecord &record) {
|
||||
// Publication invariant: all output blobs MUST be present and verified before commit.
|
||||
for (const auto &[out_path, ref] : record.outputs) {
|
||||
auto ok = verify_blob(ref.sha256);
|
||||
if (!ok || !*ok) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format(
|
||||
"StateStore: refusing to commit action '{}' referencing unverified blob '{}'",
|
||||
record.action_key, ref.sha256))};
|
||||
}
|
||||
}
|
||||
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Exclusive);
|
||||
if (!lock) {
|
||||
return std::unexpected{lock.error()};
|
||||
}
|
||||
auto db = load_db_locked();
|
||||
if (!db) {
|
||||
return std::unexpected{db.error()};
|
||||
}
|
||||
db->actions[record.action_key] = record;
|
||||
return save_db_locked(*db);
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error>
|
||||
StateStore::record_generation(const GraphGenerationRecord &generation) {
|
||||
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Exclusive);
|
||||
if (!lock) {
|
||||
return std::unexpected{lock.error()};
|
||||
}
|
||||
auto db = load_db_locked();
|
||||
if (!db) {
|
||||
return std::unexpected{db.error()};
|
||||
}
|
||||
GraphGenerationRecord copy = generation;
|
||||
copy.sequence = db->next_sequence++;
|
||||
db->generations.push_back(std::move(copy));
|
||||
// Keep bounded recent history per store.
|
||||
if (db->generations.size() > 512) {
|
||||
db->generations.erase(db->generations.begin(),
|
||||
db->generations.begin() +
|
||||
static_cast<std::ptrdiff_t>(db->generations.size() - 512));
|
||||
}
|
||||
return save_db_locked(*db);
|
||||
}
|
||||
|
||||
Void::Result::Result<std::vector<GraphGenerationRecord>, Void::Result::Error>
|
||||
StateStore::list_generations(std::optional<std::string_view> profile_name) const {
|
||||
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Shared);
|
||||
if (!lock) {
|
||||
return std::unexpected{lock.error()};
|
||||
}
|
||||
auto db = load_db_locked();
|
||||
if (!db) {
|
||||
return std::unexpected{db.error()};
|
||||
}
|
||||
if (!profile_name) {
|
||||
return db->generations;
|
||||
}
|
||||
std::vector<GraphGenerationRecord> filtered;
|
||||
for (const auto &g : db->generations) {
|
||||
if (g.profile_name == *profile_name) {
|
||||
filtered.push_back(g);
|
||||
}
|
||||
}
|
||||
return filtered;
|
||||
}
|
||||
|
||||
Void::Result::Result<LeaseHandle, Void::Result::Error>
|
||||
StateStore::acquire_lease(std::string_view profile_name,
|
||||
const std::set<std::string> &pinned_blobs) {
|
||||
using Util::json_array;
|
||||
using Util::json_quote;
|
||||
|
||||
const auto seq = g_lease_seq.fetch_add(1, std::memory_order_relaxed);
|
||||
const auto pid = static_cast<long long>(::getpid());
|
||||
LeaseHandle handle;
|
||||
handle.lease_id = std::format("lease_{}_{}", pid, seq);
|
||||
handle.lease_file = leases_dir_ / (handle.lease_id + ".json");
|
||||
|
||||
std::string payload = "{\"pid\":" + std::to_string(pid) +
|
||||
",\"profile\":" + json_quote(profile_name) +
|
||||
",\"blobs\":" + json_array(pinned_blobs, json_quote) + "}\n";
|
||||
auto written = Platform::atomic_write_file(handle.lease_file, payload, false);
|
||||
if (!written) {
|
||||
return std::unexpected{written.error()};
|
||||
}
|
||||
return handle;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::size_t, Void::Result::Error> StateStore::recover() {
|
||||
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Exclusive);
|
||||
if (!lock) {
|
||||
return std::unexpected{lock.error()};
|
||||
}
|
||||
|
||||
std::size_t cleaned = 0;
|
||||
std::error_code ec;
|
||||
|
||||
// 1. Remove uncommitted staging files inside managed staging directory only.
|
||||
if (std::filesystem::is_directory(staging_dir_, ec)) {
|
||||
for (const auto &entry : std::filesystem::directory_iterator(staging_dir_, ec)) {
|
||||
std::filesystem::remove_all(entry.path(), ec);
|
||||
if (!ec) {
|
||||
++cleaned;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Reap dead-PID leases.
|
||||
if (std::filesystem::is_directory(leases_dir_, ec)) {
|
||||
for (const auto &entry : std::filesystem::directory_iterator(leases_dir_, ec)) {
|
||||
if (!entry.is_regular_file()) {
|
||||
continue;
|
||||
}
|
||||
auto content = Void::FileSystem::read_file(entry.path());
|
||||
if (!content) {
|
||||
continue;
|
||||
}
|
||||
auto parsed = Void::Json::Strict::parse(*content);
|
||||
if (!parsed) {
|
||||
std::filesystem::remove(entry.path(), ec);
|
||||
++cleaned;
|
||||
continue;
|
||||
}
|
||||
if (const auto *obj = std::get_if<JsonVal::Object>(&parsed->value)) {
|
||||
const auto pid = get_i64(*obj, "pid").value_or(0);
|
||||
if (!pid_is_alive(static_cast<pid_t>(pid))) {
|
||||
std::filesystem::remove(entry.path(), ec);
|
||||
++cleaned;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Validate DB parses cleanly; drop action records whose CAS blobs are missing/corrupt.
|
||||
auto db = load_db_locked();
|
||||
if (!db) {
|
||||
return std::unexpected{db.error()};
|
||||
}
|
||||
bool dirty = false;
|
||||
for (auto it = db->actions.begin(); it != db->actions.end();) {
|
||||
bool valid = true;
|
||||
for (const auto &[out_path, ref] : it->second.outputs) {
|
||||
auto ok = verify_blob(ref.sha256);
|
||||
if (!ok || !*ok) {
|
||||
valid = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!valid) {
|
||||
it = db->actions.erase(it);
|
||||
dirty = true;
|
||||
++cleaned;
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
if (dirty) {
|
||||
auto saved = save_db_locked(*db);
|
||||
if (!saved) {
|
||||
return std::unexpected{saved.error()};
|
||||
}
|
||||
}
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
Void::Result::Result<GcStats, Void::Result::Error> StateStore::gc(std::uint64_t max_cache_bytes) {
|
||||
GcStats stats;
|
||||
auto cleaned_res = recover();
|
||||
if (!cleaned_res) {
|
||||
return std::unexpected{cleaned_res.error()};
|
||||
}
|
||||
stats.cleaned_staging_files = *cleaned_res;
|
||||
|
||||
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Exclusive);
|
||||
if (!lock) {
|
||||
return std::unexpected{lock.error()};
|
||||
}
|
||||
auto db = load_db_locked();
|
||||
if (!db) {
|
||||
return std::unexpected{db.error()};
|
||||
}
|
||||
|
||||
std::set<std::string> pinned;
|
||||
for (const auto &[key, rec] : db->actions) {
|
||||
for (const auto &[out, ref] : rec.outputs) {
|
||||
pinned.insert(ref.sha256);
|
||||
}
|
||||
}
|
||||
|
||||
// Collect blobs pinned by live leases.
|
||||
std::error_code ec;
|
||||
if (std::filesystem::is_directory(leases_dir_, ec)) {
|
||||
for (const auto &entry : std::filesystem::directory_iterator(leases_dir_, ec)) {
|
||||
auto content = Void::FileSystem::read_file(entry.path());
|
||||
if (!content) {
|
||||
continue;
|
||||
}
|
||||
auto parsed = Void::Json::Strict::parse(*content);
|
||||
if (!parsed) {
|
||||
continue;
|
||||
}
|
||||
if (const auto *obj = std::get_if<JsonVal::Object>(&parsed->value)) {
|
||||
const auto pid = get_i64(*obj, "pid").value_or(0);
|
||||
if (!pid_is_alive(static_cast<pid_t>(pid))) {
|
||||
continue;
|
||||
}
|
||||
if (const auto *blobs = find_key(*obj, "blobs")) {
|
||||
if (const auto *arr = std::get_if<JsonVal::Array>(&blobs->value)) {
|
||||
for (const auto &bv : *arr) {
|
||||
if (const auto *s = std::get_if<std::string>(&bv.value)) {
|
||||
pinned.insert(*s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove unpinned blobs inside cas_dir_ ONLY.
|
||||
std::uint64_t retained_bytes = 0;
|
||||
if (std::filesystem::is_directory(cas_dir_, ec)) {
|
||||
for (const auto &bucket : std::filesystem::directory_iterator(cas_dir_, ec)) {
|
||||
if (!bucket.is_directory()) {
|
||||
continue;
|
||||
}
|
||||
for (const auto &entry : std::filesystem::directory_iterator(bucket.path(), ec)) {
|
||||
if (!entry.is_regular_file()) {
|
||||
continue;
|
||||
}
|
||||
const std::string sha = entry.path().filename().string();
|
||||
const auto fsize = entry.file_size(ec);
|
||||
if (!pinned.contains(sha)) {
|
||||
(void)::chmod(entry.path().c_str(), 0644);
|
||||
std::filesystem::remove(entry.path(), ec);
|
||||
if (!ec) {
|
||||
++stats.removed_blobs;
|
||||
stats.freed_bytes += fsize;
|
||||
}
|
||||
} else {
|
||||
++stats.retained_blobs;
|
||||
retained_bytes += fsize;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (max_cache_bytes > 0 && retained_bytes > max_cache_bytes) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::limit_exceeded,
|
||||
std::format(
|
||||
"StateStore::gc: active pinned cache size ({} bytes) exceeds quota ({} bytes)",
|
||||
retained_bytes, max_cache_bytes))};
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
|
||||
std::size_t StateStore::recorded_action_count() const {
|
||||
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Shared);
|
||||
if (!lock) {
|
||||
return 0;
|
||||
}
|
||||
auto db = load_db_locked();
|
||||
return db ? db->actions.size() : 0;
|
||||
}
|
||||
|
||||
} // namespace Void::Build::State
|
||||
@@ -0,0 +1,717 @@
|
||||
#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/Configuration/Env.hpp>
|
||||
#include <Void/Data/StrictJson.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>
|
||||
#include <sys/utsname.h>
|
||||
|
||||
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) {
|
||||
Platform::ProcessRequest req;
|
||||
req.executable = compiler;
|
||||
req.arguments = {"-x", "c++", "-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 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 += ",\"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 += ",\"archiver_sha256\":" + json_quote(cap.archiver_sha256);
|
||||
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.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.archiver_sha256 = get_str("archiver_sha256").value_or("");
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string host_os_name() {
|
||||
struct utsname u{};
|
||||
if (::uname(&u) == 0) {
|
||||
return std::string{u.sysname};
|
||||
}
|
||||
return "Linux";
|
||||
}
|
||||
|
||||
std::string host_architecture_name() {
|
||||
struct utsname u{};
|
||||
if (::uname(&u) == 0) {
|
||||
return std::string{u.machine};
|
||||
}
|
||||
return "x86_64";
|
||||
}
|
||||
|
||||
Void::Result::Result<ToolchainCapabilities, Void::Result::Error>
|
||||
discover_and_probe(const ProfileContext &context,
|
||||
const std::optional<std::filesystem::path> &cache_dir) {
|
||||
std::filesystem::path requested_compiler;
|
||||
if (!context.compiler_path.empty()) {
|
||||
requested_compiler = context.compiler_path;
|
||||
} 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::optional<std::filesystem::path> resolved_ar;
|
||||
if (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(compiler_name(context.compiler));
|
||||
key_hasher.update_length_prefixed(resolved_compiler->string());
|
||||
key_hasher.update_length_prefixed(*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();
|
||||
|
||||
if (cache_dir) {
|
||||
const auto cache_file = *cache_dir / (probe_cache_key + ".json");
|
||||
if (auto cached_text = Void::FileSystem::read_file(cache_file); cached_text) {
|
||||
if (auto cached = deserialize_capabilities(*cached_text); cached) {
|
||||
cached->relevant_env = relevant_env;
|
||||
return *cached;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ToolchainCapabilities cap;
|
||||
cap.family = context.compiler;
|
||||
cap.cxx_compiler = *resolved_compiler;
|
||||
cap.archiver = *resolved_ar;
|
||||
cap.sysroot = context.sysroot;
|
||||
cap.compiler_sha256 = *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();
|
||||
}
|
||||
|
||||
// Syntax-only capability probes (safe for cross-toolchains).
|
||||
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);
|
||||
}
|
||||
|
||||
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(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.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 = toolchain.cxx_compiler;
|
||||
|
||||
std::vector<std::string> args;
|
||||
if (!toolchain.sysroot.empty()) {
|
||||
args.push_back("--sysroot=" + toolchain.sysroot);
|
||||
}
|
||||
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.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("-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);
|
||||
}
|
||||
}
|
||||
for (const auto &[inc, is_system] : request.include_dirs) {
|
||||
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;
|
||||
|
||||
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
|
||||
@@ -0,0 +1,102 @@
|
||||
#include <Void/Build/Util/Json.hpp>
|
||||
|
||||
#ifdef VBS_HAS_VOID_UNICODE
|
||||
#include <Void/Unicode/Utf.hpp>
|
||||
#endif
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Void::Build::Util {
|
||||
|
||||
bool is_valid_utf8(std::string_view text) noexcept {
|
||||
#ifdef VBS_HAS_VOID_UNICODE
|
||||
Void::Unicode::UtfLimits limits;
|
||||
limits.max_input_units = text.size();
|
||||
limits.max_output_units = text.size();
|
||||
return Void::Unicode::validate_utf8(text, limits).has_value();
|
||||
#else
|
||||
std::size_t position = 0;
|
||||
while (position < text.size()) {
|
||||
const auto lead = static_cast<unsigned char>(text[position++]);
|
||||
if (lead < 0x80) {
|
||||
continue;
|
||||
}
|
||||
std::size_t remaining = 0;
|
||||
std::uint32_t scalar = 0;
|
||||
std::uint32_t minimum = 0;
|
||||
if (lead >= 0xc2 && lead <= 0xdf) {
|
||||
remaining = 1;
|
||||
scalar = lead & 0x1f;
|
||||
minimum = 0x80;
|
||||
} else if (lead >= 0xe0 && lead <= 0xef) {
|
||||
remaining = 2;
|
||||
scalar = lead & 0x0f;
|
||||
minimum = 0x800;
|
||||
} else if (lead >= 0xf0 && lead <= 0xf4) {
|
||||
remaining = 3;
|
||||
scalar = lead & 0x07;
|
||||
minimum = 0x10000;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
if (remaining > text.size() - position) {
|
||||
return false;
|
||||
}
|
||||
for (std::size_t i = 0; i < remaining; ++i) {
|
||||
const auto continuation = static_cast<unsigned char>(text[position++]);
|
||||
if ((continuation & 0xc0) != 0x80) {
|
||||
return false;
|
||||
}
|
||||
scalar = (scalar << 6) | (continuation & 0x3f);
|
||||
}
|
||||
if (scalar < minimum || scalar > 0x10ffff || (scalar >= 0xd800 && scalar <= 0xdfff)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
void require_valid_utf8(std::string_view text) {
|
||||
if (!is_valid_utf8(text)) {
|
||||
throw std::invalid_argument{"JSON string contains invalid UTF-8"};
|
||||
}
|
||||
}
|
||||
|
||||
std::string json_quote(std::string_view text) {
|
||||
require_valid_utf8(text);
|
||||
constexpr char hex[] = "0123456789abcdef";
|
||||
std::string output{"\""};
|
||||
output.reserve(text.size() + 2);
|
||||
for (const unsigned char c : text) {
|
||||
switch (c) {
|
||||
case '"':
|
||||
output += "\\\"";
|
||||
break;
|
||||
case '\\':
|
||||
output += "\\\\";
|
||||
break;
|
||||
case '\n':
|
||||
output += "\\n";
|
||||
break;
|
||||
case '\r':
|
||||
output += "\\r";
|
||||
break;
|
||||
case '\t':
|
||||
output += "\\t";
|
||||
break;
|
||||
default:
|
||||
if (c < 0x20) {
|
||||
output += "\\u00";
|
||||
output += hex[c >> 4];
|
||||
output += hex[c & 0x0f];
|
||||
} else {
|
||||
output += static_cast<char>(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
output += '"';
|
||||
return output;
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Util
|
||||
@@ -0,0 +1,230 @@
|
||||
#include <Void/Build/Util/Sha256.hpp>
|
||||
|
||||
#include <Void/System/Types.hpp>
|
||||
#include <Void/Text/Hex.hpp>
|
||||
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <format>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace Void::Build::Util {
|
||||
namespace {
|
||||
|
||||
constexpr std::uint32_t kRoundConstants[64] = {
|
||||
0x428a2f98u, 0x71374491u, 0xb5c0fbcfu, 0xe9b5dba5u, 0x3956c25bu, 0x59f111f1u, 0x923f82a4u,
|
||||
0xab1c5ed5u, 0xd807aa98u, 0x12835b01u, 0x243185beu, 0x550c7dc3u, 0x72be5d74u, 0x80deb1feu,
|
||||
0x9bdc06a7u, 0xc19bf174u, 0xe49b69c1u, 0xefbe4786u, 0x0fc19dc6u, 0x240ca1ccu, 0x2de92c6fu,
|
||||
0x4a7484aau, 0x5cb0a9dcu, 0x76f988dau, 0x983e5152u, 0xa831c66du, 0xb00327c8u, 0xbf597fc7u,
|
||||
0xc6e00bf3u, 0xd5a79147u, 0x06ca6351u, 0x14292967u, 0x27b70a85u, 0x2e1b2138u, 0x4d2c6dfcu,
|
||||
0x53380d13u, 0x650a7354u, 0x766a0abbu, 0x81c2c92eu, 0x92722c85u, 0xa2bfe8a1u, 0xa81a664bu,
|
||||
0xc24b8b70u, 0xc76c51a3u, 0xd192e819u, 0xd6990624u, 0xf40e3585u, 0x106aa070u, 0x19a4c116u,
|
||||
0x1e376c08u, 0x2748774cu, 0x34b0bcb5u, 0x391c0cb3u, 0x4ed8aa4au, 0x5b9cca4fu, 0x682e6ff3u,
|
||||
0x748f82eeu, 0x78a5636fu, 0x84c87814u, 0x8cc70208u, 0x90befffau, 0xa4506cebu, 0xbef9a3f7u,
|
||||
0xc67178f2u};
|
||||
|
||||
constexpr std::uint32_t rotr(std::uint32_t x, unsigned n) noexcept {
|
||||
return (x >> n) | (x << (32u - n));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Sha256Hasher::Sha256Hasher() noexcept
|
||||
: state_{0x6a09e667u, 0xbb67ae85u, 0x3c6ef372u, 0xa54ff53au,
|
||||
0x510e527fu, 0x9b05688cu, 0x1f83d9abu, 0x5be0cd19u} {}
|
||||
|
||||
void Sha256Hasher::transform(const std::uint8_t block[64]) noexcept {
|
||||
std::uint32_t w[64];
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
w[i] = (static_cast<std::uint32_t>(block[i * 4]) << 24) |
|
||||
(static_cast<std::uint32_t>(block[i * 4 + 1]) << 16) |
|
||||
(static_cast<std::uint32_t>(block[i * 4 + 2]) << 8) |
|
||||
static_cast<std::uint32_t>(block[i * 4 + 3]);
|
||||
}
|
||||
for (int i = 16; i < 64; ++i) {
|
||||
const std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
|
||||
const std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
|
||||
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||
}
|
||||
|
||||
std::uint32_t a = state_[0];
|
||||
std::uint32_t b = state_[1];
|
||||
std::uint32_t c = state_[2];
|
||||
std::uint32_t d = state_[3];
|
||||
std::uint32_t e = state_[4];
|
||||
std::uint32_t f = state_[5];
|
||||
std::uint32_t g = state_[6];
|
||||
std::uint32_t h = state_[7];
|
||||
|
||||
for (int i = 0; i < 64; ++i) {
|
||||
const std::uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
||||
const std::uint32_t ch = (e & f) ^ ((~e) & g);
|
||||
const std::uint32_t temp1 = h + S1 + ch + kRoundConstants[i] + w[i];
|
||||
const std::uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
|
||||
const std::uint32_t maj = (a & b) ^ (a & c) ^ (b & c);
|
||||
const std::uint32_t temp2 = S0 + maj;
|
||||
|
||||
h = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = d + temp1;
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = temp1 + temp2;
|
||||
}
|
||||
|
||||
state_[0] += a;
|
||||
state_[1] += b;
|
||||
state_[2] += c;
|
||||
state_[3] += d;
|
||||
state_[4] += e;
|
||||
state_[5] += f;
|
||||
state_[6] += g;
|
||||
state_[7] += h;
|
||||
}
|
||||
|
||||
void Sha256Hasher::update(std::span<const std::uint8_t> data) noexcept {
|
||||
if (finalized_ || data.empty()) {
|
||||
return;
|
||||
}
|
||||
const std::uint8_t *ptr = data.data();
|
||||
std::size_t remaining = data.size();
|
||||
bit_count_ += static_cast<std::uint64_t>(remaining) * 8u;
|
||||
|
||||
if (buffer_len_ > 0) {
|
||||
const std::size_t take = std::min(remaining, std::size_t{64} - buffer_len_);
|
||||
std::memcpy(buffer_ + buffer_len_, ptr, take);
|
||||
buffer_len_ += take;
|
||||
ptr += take;
|
||||
remaining -= take;
|
||||
if (buffer_len_ == 64) {
|
||||
transform(buffer_);
|
||||
buffer_len_ = 0;
|
||||
}
|
||||
}
|
||||
while (remaining >= 64) {
|
||||
transform(ptr);
|
||||
ptr += 64;
|
||||
remaining -= 64;
|
||||
}
|
||||
if (remaining > 0) {
|
||||
std::memcpy(buffer_, ptr, remaining);
|
||||
buffer_len_ = remaining;
|
||||
}
|
||||
}
|
||||
|
||||
void Sha256Hasher::update(std::span<const std::byte> data) noexcept {
|
||||
update(std::span<const std::uint8_t>{reinterpret_cast<const std::uint8_t *>(data.data()),
|
||||
data.size()});
|
||||
}
|
||||
|
||||
void Sha256Hasher::update(std::string_view text) noexcept {
|
||||
update(std::span<const std::uint8_t>{reinterpret_cast<const std::uint8_t *>(text.data()),
|
||||
text.size()});
|
||||
}
|
||||
|
||||
void Sha256Hasher::update_u64(std::uint64_t value) noexcept {
|
||||
std::uint8_t bytes[8];
|
||||
for (int i = 7; i >= 0; --i) {
|
||||
bytes[i] = static_cast<std::uint8_t>(value & 0xffu);
|
||||
value >>= 8;
|
||||
}
|
||||
update(bytes);
|
||||
}
|
||||
|
||||
void Sha256Hasher::update_length_prefixed(std::string_view text) noexcept {
|
||||
update_u64(static_cast<std::uint64_t>(text.size()));
|
||||
update(text);
|
||||
}
|
||||
|
||||
Sha256Digest Sha256Hasher::finalize() noexcept {
|
||||
if (!finalized_) {
|
||||
finalized_ = true;
|
||||
buffer_[buffer_len_++] = 0x80u;
|
||||
if (buffer_len_ > 56) {
|
||||
std::memset(buffer_ + buffer_len_, 0, 64 - buffer_len_);
|
||||
transform(buffer_);
|
||||
buffer_len_ = 0;
|
||||
}
|
||||
std::memset(buffer_ + buffer_len_, 0, 56 - buffer_len_);
|
||||
std::uint64_t bits = bit_count_;
|
||||
for (int i = 7; i >= 0; --i) {
|
||||
buffer_[56 + i] = static_cast<std::uint8_t>(bits & 0xffu);
|
||||
bits >>= 8;
|
||||
}
|
||||
transform(buffer_);
|
||||
}
|
||||
|
||||
Sha256Digest out{};
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
out[static_cast<std::size_t>(i * 4)] = static_cast<std::uint8_t>((state_[i] >> 24) & 0xffu);
|
||||
out[static_cast<std::size_t>(i * 4 + 1)] =
|
||||
static_cast<std::uint8_t>((state_[i] >> 16) & 0xffu);
|
||||
out[static_cast<std::size_t>(i * 4 + 2)] =
|
||||
static_cast<std::uint8_t>((state_[i] >> 8) & 0xffu);
|
||||
out[static_cast<std::size_t>(i * 4 + 3)] = static_cast<std::uint8_t>(state_[i] & 0xffu);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string Sha256Hasher::finalize_hex() noexcept { return to_hex(finalize()); }
|
||||
|
||||
std::string to_hex(const Sha256Digest &digest) {
|
||||
return Void::Encoding::Hex::encode(std::span<const std::uint8_t>{digest.data(), digest.size()});
|
||||
}
|
||||
|
||||
Sha256Digest sha256_bytes(std::span<const std::byte> data) noexcept {
|
||||
Sha256Hasher hasher;
|
||||
hasher.update(data);
|
||||
return hasher.finalize();
|
||||
}
|
||||
|
||||
std::string sha256_hex(std::string_view text) {
|
||||
Sha256Hasher hasher;
|
||||
hasher.update(text);
|
||||
return hasher.finalize_hex();
|
||||
}
|
||||
|
||||
std::string sha256_hex(std::span<const std::byte> data) { return to_hex(sha256_bytes(data)); }
|
||||
|
||||
Void::Result::Result<std::string, Void::Result::Error>
|
||||
sha256_file_hex(const std::filesystem::path &path) {
|
||||
const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::map_errno_to_system_code(err),
|
||||
std::format("sha256_file_hex: cannot open '{}'", path.string()), err)};
|
||||
}
|
||||
Void::System::OwnedFd guard{fd};
|
||||
Sha256Hasher hasher;
|
||||
std::array<std::uint8_t, 65536> buf{};
|
||||
for (;;) {
|
||||
const ssize_t n = ::read(fd, buf.data(), buf.size());
|
||||
if (n > 0) {
|
||||
hasher.update(std::span<const std::uint8_t>{buf.data(), static_cast<std::size_t>(n)});
|
||||
} else if (n == 0) {
|
||||
break;
|
||||
} else if (errno != EINTR) {
|
||||
const int err = errno;
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::map_errno_to_system_code(err),
|
||||
std::format("sha256_file_hex: read failed for '{}'", path.string()), err)};
|
||||
}
|
||||
}
|
||||
return hasher.finalize_hex();
|
||||
}
|
||||
|
||||
bool constant_time_equal(std::string_view a, std::string_view b) noexcept {
|
||||
if (a.size() != b.size()) {
|
||||
return false;
|
||||
}
|
||||
unsigned char diff = 0;
|
||||
for (std::size_t i = 0; i < a.size(); ++i) {
|
||||
diff |= static_cast<unsigned char>(a[i]) ^ static_cast<unsigned char>(b[i]);
|
||||
}
|
||||
return diff == 0;
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Util
|
||||
@@ -0,0 +1,500 @@
|
||||
#include <Void/Build/Watch/Watcher.hpp>
|
||||
|
||||
#include <Void/Build/Toolchain/Driver.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <format>
|
||||
#include <poll.h>
|
||||
#include <set>
|
||||
#include <sys/inotify.h>
|
||||
#include <unistd.h>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Build::Watch {
|
||||
namespace {
|
||||
|
||||
Void::Result::Error sys_err(int err, std::string msg) {
|
||||
return Void::System::make_system_error(Void::System::map_errno_to_system_code(err),
|
||||
std::move(msg), err);
|
||||
}
|
||||
|
||||
constexpr std::uint32_t kWatchMask = IN_CREATE | IN_DELETE | IN_MODIFY | IN_CLOSE_WRITE |
|
||||
IN_MOVED_FROM | IN_MOVED_TO | IN_ATTRIB | IN_DELETE_SELF |
|
||||
IN_MOVE_SELF;
|
||||
|
||||
} // namespace
|
||||
|
||||
InotifyWatcher::InotifyWatcher(int fd, std::filesystem::path root,
|
||||
std::vector<std::string> excluded)
|
||||
: fd_{fd}, root_{std::move(root)}, excluded_{std::move(excluded)} {}
|
||||
|
||||
InotifyWatcher::~InotifyWatcher() noexcept { close_fd(); }
|
||||
|
||||
InotifyWatcher::InotifyWatcher(InotifyWatcher &&other) noexcept
|
||||
: fd_{std::exchange(other.fd_, -1)}, root_{std::move(other.root_)},
|
||||
excluded_{std::move(other.excluded_)}, wd_to_path_{std::move(other.wd_to_path_)} {}
|
||||
|
||||
InotifyWatcher &InotifyWatcher::operator=(InotifyWatcher &&other) noexcept {
|
||||
if (this != &other) {
|
||||
close_fd();
|
||||
fd_ = std::exchange(other.fd_, -1);
|
||||
root_ = std::move(other.root_);
|
||||
excluded_ = std::move(other.excluded_);
|
||||
wd_to_path_ = std::move(other.wd_to_path_);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
void InotifyWatcher::close_fd() noexcept {
|
||||
if (fd_ >= 0) {
|
||||
(void)::close(fd_);
|
||||
fd_ = -1;
|
||||
}
|
||||
wd_to_path_.clear();
|
||||
}
|
||||
|
||||
bool InotifyWatcher::is_excluded(const std::filesystem::path &rel) const {
|
||||
for (const auto &part : rel) {
|
||||
const auto s = part.string();
|
||||
if (s.empty() || s == ".") {
|
||||
continue;
|
||||
}
|
||||
if (std::ranges::contains(excluded_, s)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error>
|
||||
InotifyWatcher::watch_tree(const std::filesystem::path &dir) {
|
||||
std::error_code ec;
|
||||
if (!std::filesystem::is_directory(dir, ec)) {
|
||||
return {};
|
||||
}
|
||||
auto add_dir =
|
||||
[&](const std::filesystem::path &p) -> Void::Result::Result<void, Void::Result::Error> {
|
||||
const int wd = ::inotify_add_watch(fd_, p.c_str(), kWatchMask);
|
||||
if (wd < 0) {
|
||||
const int err = errno;
|
||||
if (err == ENOENT || err == ENOTDIR) {
|
||||
return {};
|
||||
}
|
||||
return std::unexpected{sys_err(
|
||||
err, std::format("InotifyWatcher: inotify_add_watch failed for '{}'", p.string()))};
|
||||
}
|
||||
wd_to_path_[wd] = p;
|
||||
return {};
|
||||
};
|
||||
|
||||
if (auto r = add_dir(dir); !r) {
|
||||
return r;
|
||||
}
|
||||
std::filesystem::recursive_directory_iterator it{
|
||||
dir, std::filesystem::directory_options::skip_permission_denied, ec};
|
||||
for (; !ec && it != std::filesystem::recursive_directory_iterator{}; it.increment(ec)) {
|
||||
const auto rel = it->path().lexically_relative(root_);
|
||||
if (is_excluded(rel)) {
|
||||
if (it->is_directory(ec)) {
|
||||
it.disable_recursion_pending();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (it->is_directory(ec)) {
|
||||
if (auto r = add_dir(it->path()); !r) {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<InotifyWatcher, Void::Result::Error>
|
||||
InotifyWatcher::create(const std::filesystem::path &root_dir,
|
||||
std::vector<std::string> excluded_names) {
|
||||
std::error_code ec;
|
||||
const auto canon = std::filesystem::weakly_canonical(root_dir, ec);
|
||||
if (ec || !std::filesystem::is_directory(canon)) {
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::SystemErrorCode::not_found,
|
||||
std::format("InotifyWatcher: root '{}' is not a directory", root_dir.string()))};
|
||||
}
|
||||
const int fd = ::inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{sys_err(err, "InotifyWatcher: inotify_init1 failed")};
|
||||
}
|
||||
InotifyWatcher watcher{fd, canon, std::move(excluded_names)};
|
||||
if (auto r = watcher.watch_tree(canon); !r) {
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
return watcher;
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error> InotifyWatcher::rescan_watches() {
|
||||
for (const auto &[wd, path] : wd_to_path_) {
|
||||
(void)::inotify_rm_watch(fd_, wd);
|
||||
}
|
||||
wd_to_path_.clear();
|
||||
return watch_tree(root_);
|
||||
}
|
||||
|
||||
Void::Result::Result<WatchBatch, Void::Result::Error>
|
||||
InotifyWatcher::poll_events(std::chrono::milliseconds timeout, std::chrono::milliseconds debounce) {
|
||||
WatchBatch batch;
|
||||
if (fd_ < 0) {
|
||||
batch.rescan_required = true;
|
||||
return batch;
|
||||
}
|
||||
|
||||
struct pollfd pfd{fd_, POLLIN, 0};
|
||||
const int ready = ::poll(&pfd, 1, static_cast<int>(std::max<long long>(0, timeout.count())));
|
||||
if (ready < 0) {
|
||||
if (errno == EINTR) {
|
||||
return batch;
|
||||
}
|
||||
return std::unexpected{sys_err(errno, "InotifyWatcher: poll failed")};
|
||||
}
|
||||
if (ready == 0) {
|
||||
return batch;
|
||||
}
|
||||
|
||||
std::set<std::filesystem::path> unique_paths;
|
||||
alignas(struct inotify_event) std::array<char, 32768> buf{};
|
||||
|
||||
auto drain_now = [&]() {
|
||||
for (;;) {
|
||||
const ssize_t n = ::read(fd_, buf.data(), buf.size());
|
||||
if (n <= 0) {
|
||||
break;
|
||||
}
|
||||
ssize_t off = 0;
|
||||
while (off < n) {
|
||||
const auto *ev = reinterpret_cast<const struct inotify_event *>(buf.data() + off);
|
||||
off += static_cast<ssize_t>(sizeof(struct inotify_event) + ev->len);
|
||||
|
||||
if (ev->mask & IN_Q_OVERFLOW) {
|
||||
batch.overflowed = true;
|
||||
batch.rescan_required = true;
|
||||
continue;
|
||||
}
|
||||
if (ev->mask & IN_IGNORED) {
|
||||
wd_to_path_.erase(ev->wd);
|
||||
continue;
|
||||
}
|
||||
|
||||
const auto dir_it = wd_to_path_.find(ev->wd);
|
||||
if (dir_it == wd_to_path_.end()) {
|
||||
batch.rescan_required = true;
|
||||
continue;
|
||||
}
|
||||
std::filesystem::path full = dir_it->second;
|
||||
if (ev->len > 0 && ev->name[0] != '\0') {
|
||||
full /= ev->name;
|
||||
}
|
||||
const auto rel = full.lexically_relative(root_);
|
||||
if (is_excluded(rel)) {
|
||||
continue;
|
||||
}
|
||||
unique_paths.insert(full);
|
||||
|
||||
if ((ev->mask & (IN_CREATE | IN_MOVED_TO)) && (ev->mask & IN_ISDIR)) {
|
||||
auto attached = watch_tree(full);
|
||||
if (!attached) {
|
||||
batch.rescan_required = true;
|
||||
}
|
||||
}
|
||||
if (ev->mask & (IN_DELETE_SELF | IN_MOVE_SELF)) {
|
||||
batch.rescan_required = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
drain_now();
|
||||
|
||||
// Coalesce burst edits across the debounce window.
|
||||
if (debounce.count() > 0 && (!unique_paths.empty() || batch.rescan_required)) {
|
||||
const auto settle_deadline = std::chrono::steady_clock::now() + debounce;
|
||||
while (std::chrono::steady_clock::now() < settle_deadline) {
|
||||
const auto rem = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
settle_deadline - std::chrono::steady_clock::now());
|
||||
if (rem.count() <= 0) {
|
||||
break;
|
||||
}
|
||||
struct pollfd spfd{fd_, POLLIN, 0};
|
||||
const int sr = ::poll(&spfd, 1, static_cast<int>(rem.count()));
|
||||
if (sr > 0) {
|
||||
drain_now();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (batch.rescan_required) {
|
||||
(void)rescan_watches();
|
||||
}
|
||||
batch.changed_paths.assign(unique_paths.begin(), unique_paths.end());
|
||||
return batch;
|
||||
}
|
||||
|
||||
WatchCycleReport run_reconcile_cycle(const WatchLoopOptions &options, std::size_t cycle_index,
|
||||
bool allow_selection_update,
|
||||
std::optional<std::uint64_t> reserved_ticket,
|
||||
std::stop_token stop) {
|
||||
WatchCycleReport rep;
|
||||
rep.cycle_index = cycle_index;
|
||||
|
||||
// Resolve profile name: explicit profile, or active editor selection in MetadataOnly, or
|
||||
// "debug".
|
||||
std::string profile_name = options.explicit_profile.value_or("");
|
||||
if (profile_name.empty()) {
|
||||
if (auto sel = Editor::read_selection_state(options.frontend.project_root);
|
||||
sel && sel->has_value() && !(*sel)->selected_profile.empty()) {
|
||||
profile_name = (*sel)->selected_profile;
|
||||
} else {
|
||||
profile_name = "debug";
|
||||
}
|
||||
}
|
||||
rep.profile_name = profile_name;
|
||||
|
||||
// 1. Compile or reuse host build description (allowed in both FullBuild and MetadataOnly).
|
||||
auto compiled = Config::compile_descriptor(options.frontend);
|
||||
if (!compiled) {
|
||||
rep.diagnostic = compiled.error().message();
|
||||
(void)Editor::mark_profile_stale(options.frontend.build_root, profile_name,
|
||||
Editor::GenerationStatus::Invalid, rep.diagnostic);
|
||||
return rep;
|
||||
}
|
||||
|
||||
// 2. Discover profiles and resolve target ProfileContext.
|
||||
auto profs = Config::discover_profiles(*compiled, options.frontend);
|
||||
if (!profs) {
|
||||
rep.diagnostic = profs.error().message();
|
||||
(void)Editor::mark_profile_stale(options.frontend.build_root, profile_name,
|
||||
Editor::GenerationStatus::Invalid, rep.diagnostic);
|
||||
return rep;
|
||||
}
|
||||
|
||||
ProfileContext ctx;
|
||||
try {
|
||||
ctx = profs->resolve(profile_name, options.compiler_override, Toolchain::host_os_name(),
|
||||
Toolchain::host_architecture_name());
|
||||
} catch (const std::exception &ex) {
|
||||
rep.diagnostic = ex.what();
|
||||
(void)Editor::mark_profile_stale(options.frontend.build_root, profile_name,
|
||||
Editor::GenerationStatus::Invalid, rep.diagnostic);
|
||||
return rep;
|
||||
}
|
||||
|
||||
// 3. Probe target toolchain (safe syntax-only probes, never builds targets).
|
||||
auto tc = Toolchain::discover_and_probe(ctx, options.frontend.build_root / ".vbs" / "probes");
|
||||
if (!tc) {
|
||||
rep.diagnostic = tc.error().message();
|
||||
(void)Editor::mark_profile_stale(options.frontend.build_root, profile_name,
|
||||
Editor::GenerationStatus::Invalid, rep.diagnostic);
|
||||
return rep;
|
||||
}
|
||||
|
||||
// 4. Evaluate build(Project&) for this ProfileContext.
|
||||
auto desc = Config::evaluate_project(*compiled, ctx, options.frontend);
|
||||
if (!desc) {
|
||||
rep.diagnostic = desc.error().message();
|
||||
(void)Editor::mark_profile_stale(options.frontend.build_root, profile_name,
|
||||
Editor::GenerationStatus::Invalid, rep.diagnostic);
|
||||
return rep;
|
||||
}
|
||||
|
||||
// 5. Provider metadata boundary: in MetadataOnly mode, read ONLY validated cached exports;
|
||||
// NEVER invoke CMake configure, Meson setup, Conan install, fetch, or lock writes!
|
||||
CachedProviderSnapshot provider_meta;
|
||||
if (options.provider_reader) {
|
||||
provider_meta = options.provider_reader(*desc, options.mode);
|
||||
}
|
||||
if (!provider_meta.valid) {
|
||||
rep.provider_stale = true;
|
||||
rep.diagnostic = provider_meta.stale_diagnostic.empty()
|
||||
? "cached dependency metadata is stale; run 'vbs build' to refresh"
|
||||
: provider_meta.stale_diagnostic;
|
||||
(void)Editor::mark_profile_stale(options.frontend.build_root, profile_name,
|
||||
Editor::GenerationStatus::Stale, rep.diagnostic);
|
||||
return rep;
|
||||
}
|
||||
|
||||
// 6. Capture input snapshot (content-verified; materialize only for FullBuild execution).
|
||||
std::vector<std::filesystem::path> scan_roots;
|
||||
std::error_code ec;
|
||||
for (const char *d : {"src", "source", "include", "tests"}) {
|
||||
if (std::filesystem::is_directory(options.frontend.project_root / d, ec)) {
|
||||
scan_roots.push_back(options.frontend.project_root / d);
|
||||
}
|
||||
}
|
||||
for (const auto &t : desc->targets) {
|
||||
for (const auto &inc : t.include_directories) {
|
||||
if (!inc.path.starts_with("$GEN/") && !inc.path.starts_with("gen/")) {
|
||||
const auto p = std::filesystem::path{inc.path}.is_absolute()
|
||||
? std::filesystem::path{inc.path}
|
||||
: (options.frontend.project_root / inc.path);
|
||||
if (std::filesystem::is_directory(p, ec) && !std::ranges::contains(scan_roots, p)) {
|
||||
scan_roots.push_back(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Snapshot::SnapshotOptions sopts;
|
||||
sopts.project_root = options.frontend.project_root;
|
||||
sopts.snapshot_store_dir = options.frontend.build_root / ".vbs" / "snapshots";
|
||||
sopts.reproducibility_epoch = ctx.reproducibility_epoch;
|
||||
sopts.materialize = (options.mode == WatchMode::FullBuild);
|
||||
|
||||
auto snap = Snapshot::capture_snapshot(sopts, {}, scan_roots);
|
||||
if (!snap) {
|
||||
rep.diagnostic = snap.error().message();
|
||||
(void)Editor::mark_profile_stale(options.frontend.build_root, profile_name,
|
||||
Editor::GenerationStatus::Invalid, rep.diagnostic);
|
||||
return rep;
|
||||
}
|
||||
|
||||
// 7. Lower target graph.
|
||||
Graph::GraphLowerOptions gopts;
|
||||
gopts.project_root = options.frontend.project_root;
|
||||
gopts.build_root = options.frontend.build_root;
|
||||
gopts.snapshot = &(*snap);
|
||||
gopts.imported_targets = std::move(provider_meta.imported_targets);
|
||||
|
||||
auto graph = Graph::lower_project_graph(*desc, *tc, gopts);
|
||||
if (!graph) {
|
||||
rep.diagnostic = graph.error().message();
|
||||
(void)Editor::mark_profile_stale(options.frontend.build_root, profile_name,
|
||||
Editor::GenerationStatus::Invalid, rep.diagnostic);
|
||||
return rep;
|
||||
}
|
||||
rep.config_succeeded = true;
|
||||
|
||||
// 8. Publish compilation database BEFORE target compilation so valid source/flag edits
|
||||
// refresh editors immediately even if target compilation fails (Plan 09/10)!
|
||||
Editor::PublishOptions popts;
|
||||
popts.project_root = options.frontend.project_root;
|
||||
popts.build_root = options.frontend.build_root;
|
||||
popts.update_selection = allow_selection_update;
|
||||
popts.reserved_ticket = reserved_ticket;
|
||||
auto pub = Editor::publish_profile_compdb(*graph, popts);
|
||||
if (!pub) {
|
||||
rep.diagnostic = pub.error().message();
|
||||
return rep;
|
||||
}
|
||||
rep.compdb_published = true;
|
||||
|
||||
// Record graph generation in state store.
|
||||
if (auto state = State::StateStore::open(options.frontend.build_root / ".vbs"); state) {
|
||||
State::GraphGenerationRecord gen_rec;
|
||||
gen_rec.generation_id = pub->generation_id;
|
||||
gen_rec.profile_name = profile_name;
|
||||
gen_rec.profile_identity = graph->profile_identity;
|
||||
gen_rec.snapshot_id = snap->snapshot_id;
|
||||
gen_rec.status = "valid";
|
||||
(void)state->record_generation(gen_rec);
|
||||
|
||||
// 9. In MetadataOnly mode: STOP HERE! Never schedule target builds or generators!
|
||||
if (options.mode == WatchMode::MetadataOnly) {
|
||||
rep.build_succeeded = true;
|
||||
return rep;
|
||||
}
|
||||
|
||||
// 10. FullBuild mode: execute selected actions.
|
||||
Execution::ExecutionOptions eopts;
|
||||
eopts.jobs = options.jobs;
|
||||
eopts.selected_targets = options.selected_targets;
|
||||
auto exec = Execution::execute_graph(*graph, *state, eopts, stop);
|
||||
if (!exec) {
|
||||
rep.diagnostic = exec.error().message();
|
||||
return rep;
|
||||
}
|
||||
rep.executed_actions = exec->executed_count;
|
||||
rep.cached_actions = exec->cached_count;
|
||||
rep.build_succeeded = exec->succeeded;
|
||||
rep.diagnostic = exec->diagnostic;
|
||||
}
|
||||
return rep;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::vector<WatchCycleReport>, Void::Result::Error>
|
||||
run_watch_loop(const WatchLoopOptions &options, std::stop_token stop) {
|
||||
auto watcher = InotifyWatcher::create(options.frontend.project_root);
|
||||
if (!watcher) {
|
||||
return std::unexpected{watcher.error()};
|
||||
}
|
||||
|
||||
std::vector<WatchCycleReport> reports;
|
||||
std::size_t cycle = 0;
|
||||
|
||||
// Initial reconciliation pass (watchers NEVER steal editor selection:
|
||||
// allow_selection_update=false).
|
||||
{
|
||||
auto rep = run_reconcile_cycle(options, cycle++, false, std::nullopt, stop);
|
||||
if (options.on_cycle) {
|
||||
options.on_cycle(rep);
|
||||
}
|
||||
reports.push_back(std::move(rep));
|
||||
if (options.max_cycles > 0 && reports.size() >= options.max_cycles) {
|
||||
return reports;
|
||||
}
|
||||
}
|
||||
|
||||
auto last_reconcile = std::chrono::steady_clock::now();
|
||||
std::string last_observed_selection;
|
||||
if (auto sel = Editor::read_selection_state(options.frontend.project_root);
|
||||
sel && sel->has_value()) {
|
||||
last_observed_selection = (*sel)->selected_profile;
|
||||
}
|
||||
|
||||
while (!stop.stop_requested()) {
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
const auto elapsed_since_reconcile =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(now - last_reconcile);
|
||||
const auto poll_wait = std::min<std::chrono::milliseconds>(
|
||||
std::chrono::milliseconds{100},
|
||||
options.reconcile_interval > elapsed_since_reconcile
|
||||
? (options.reconcile_interval - elapsed_since_reconcile)
|
||||
: std::chrono::milliseconds{10});
|
||||
|
||||
auto batch = watcher->poll_events(poll_wait, options.debounce);
|
||||
if (stop.stop_requested()) {
|
||||
break;
|
||||
}
|
||||
|
||||
bool selection_changed = false;
|
||||
if (!options.explicit_profile) {
|
||||
if (auto sel = Editor::read_selection_state(options.frontend.project_root);
|
||||
sel && sel->has_value() && (*sel)->selected_profile != last_observed_selection) {
|
||||
last_observed_selection = (*sel)->selected_profile;
|
||||
selection_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
const bool periodic_due =
|
||||
(std::chrono::steady_clock::now() - last_reconcile) >= options.reconcile_interval;
|
||||
const bool event_triggered =
|
||||
!batch || batch->overflowed || batch->rescan_required || !batch->changed_paths.empty();
|
||||
|
||||
if (event_triggered || periodic_due || selection_changed) {
|
||||
last_reconcile = std::chrono::steady_clock::now();
|
||||
auto rep = run_reconcile_cycle(options, cycle++, false, std::nullopt, stop);
|
||||
if (options.on_cycle) {
|
||||
options.on_cycle(rep);
|
||||
}
|
||||
reports.push_back(std::move(rep));
|
||||
if (options.max_cycles > 0 && reports.size() >= options.max_cycles) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return reports;
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Watch
|
||||
-448
@@ -1,448 +0,0 @@
|
||||
#include <vbs/build.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <type_traits>
|
||||
|
||||
namespace vbs {
|
||||
namespace detail {
|
||||
struct ProjectState {
|
||||
ProfileContext context;
|
||||
std::vector<TargetRecord> targets;
|
||||
std::vector<DependencyRecord> dependencies;
|
||||
};
|
||||
} // namespace detail
|
||||
namespace {
|
||||
void require_text(std::string_view text, std::string_view field) {
|
||||
if (text.empty()) {
|
||||
throw std::invalid_argument{std::string{field} + " must not be empty"};
|
||||
}
|
||||
}
|
||||
|
||||
auto owner(const std::weak_ptr<detail::ProjectState> &weak) {
|
||||
auto state = weak.lock();
|
||||
if (!state) {
|
||||
throw std::logic_error{"declaration handle's Project has expired"};
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
std::string_view visibility_name(Visibility visibility) {
|
||||
switch (visibility) {
|
||||
case Visibility::private_:
|
||||
return "private";
|
||||
case Visibility::public_:
|
||||
return "public";
|
||||
case Visibility::interface_:
|
||||
return "interface";
|
||||
}
|
||||
throw std::invalid_argument{"unknown visibility"};
|
||||
}
|
||||
|
||||
void validate_context(const ProfileContext &context) {
|
||||
require_text(context.name, "profile name");
|
||||
(void)compiler_name(context.compiler);
|
||||
require_text(context.os, "target OS");
|
||||
require_text(context.architecture, "target architecture");
|
||||
for (const auto &option : context.compile_options) {
|
||||
require_text(option, "compile option");
|
||||
}
|
||||
}
|
||||
|
||||
void require_utf8(std::string_view text) {
|
||||
std::size_t position = 0;
|
||||
const auto invalid = [] { throw std::invalid_argument{"JSON string contains invalid UTF-8"}; };
|
||||
while (position < text.size()) {
|
||||
const auto lead = static_cast<unsigned char>(text[position++]);
|
||||
if (lead < 0x80) {
|
||||
continue;
|
||||
}
|
||||
std::size_t remaining = 0;
|
||||
std::uint32_t scalar = 0;
|
||||
std::uint32_t minimum = 0;
|
||||
if (lead >= 0xc2 && lead <= 0xdf) {
|
||||
remaining = 1;
|
||||
scalar = lead & 0x1f;
|
||||
minimum = 0x80;
|
||||
} else if (lead >= 0xe0 && lead <= 0xef) {
|
||||
remaining = 2;
|
||||
scalar = lead & 0x0f;
|
||||
minimum = 0x800;
|
||||
} else if (lead >= 0xf0 && lead <= 0xf4) {
|
||||
remaining = 3;
|
||||
scalar = lead & 0x07;
|
||||
minimum = 0x10000;
|
||||
} else {
|
||||
invalid();
|
||||
}
|
||||
if (remaining > text.size() - position) {
|
||||
invalid();
|
||||
}
|
||||
for (std::size_t i = 0; i < remaining; ++i) {
|
||||
const auto continuation = static_cast<unsigned char>(text[position++]);
|
||||
if ((continuation & 0xc0) != 0x80) {
|
||||
invalid();
|
||||
}
|
||||
scalar = (scalar << 6) | (continuation & 0x3f);
|
||||
}
|
||||
// JSON strings contain Unicode scalar values: no overlong forms or surrogates.
|
||||
if (scalar < minimum || scalar > 0x10ffff || (scalar >= 0xd800 && scalar <= 0xdfff)) {
|
||||
invalid();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::string quote(std::string_view text) {
|
||||
require_utf8(text);
|
||||
constexpr char hex[] = "0123456789abcdef";
|
||||
std::string output{"\""};
|
||||
for (const unsigned char c : text) {
|
||||
switch (c) {
|
||||
case '"':
|
||||
output += "\\\"";
|
||||
break;
|
||||
case '\\':
|
||||
output += "\\\\";
|
||||
break;
|
||||
case '\n':
|
||||
output += "\\n";
|
||||
break;
|
||||
case '\r':
|
||||
output += "\\r";
|
||||
break;
|
||||
case '\t':
|
||||
output += "\\t";
|
||||
break;
|
||||
default:
|
||||
if (c < 0x20) {
|
||||
output += "\\u00";
|
||||
output += hex[c >> 4];
|
||||
output += hex[c & 0x0f];
|
||||
} else {
|
||||
output += static_cast<char>(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
output += '"';
|
||||
return output;
|
||||
}
|
||||
|
||||
template <typename Range, typename Serialize>
|
||||
std::string array(const Range &range, Serialize serialize) {
|
||||
std::string output{"["};
|
||||
bool first = true;
|
||||
for (const auto &item : range) {
|
||||
if (!first)
|
||||
output += ',';
|
||||
first = false;
|
||||
output += serialize(item);
|
||||
}
|
||||
return output + ']';
|
||||
}
|
||||
|
||||
std::string options_json(const OptionMap &options) {
|
||||
std::string output{"{"};
|
||||
bool first = true;
|
||||
for (const auto &[name, option] : options) {
|
||||
if (!first)
|
||||
output += ',';
|
||||
first = false;
|
||||
output += quote(name) + ':';
|
||||
output += std::visit(
|
||||
[](const auto &value) -> std::string {
|
||||
using Type = std::remove_cvref_t<decltype(value)>;
|
||||
if constexpr (std::same_as<Type, std::string>)
|
||||
return quote(value);
|
||||
else if constexpr (std::same_as<Type, bool>)
|
||||
return value ? "true" : "false";
|
||||
else
|
||||
return std::to_string(value);
|
||||
},
|
||||
option.value);
|
||||
}
|
||||
return output + '}';
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string_view compiler_name(CompilerFamily compiler) {
|
||||
switch (compiler) {
|
||||
case CompilerFamily::gcc:
|
||||
return "gcc";
|
||||
case CompilerFamily::clang:
|
||||
return "clang";
|
||||
}
|
||||
throw std::invalid_argument{"unknown compiler family"};
|
||||
}
|
||||
|
||||
CompilerFamily parse_compiler(std::string_view name) {
|
||||
if (name == "gcc")
|
||||
return CompilerFamily::gcc;
|
||||
if (name == "clang")
|
||||
return CompilerFamily::clang;
|
||||
throw std::invalid_argument{"unknown compiler '" + std::string{name} +
|
||||
"' (expected gcc or clang)"};
|
||||
}
|
||||
|
||||
void Profiles::add(std::string name, std::vector<std::string> compile_options) {
|
||||
require_text(name, "profile name");
|
||||
if (std::ranges::any_of(records_, [&](const auto &record) { return record.name == name; })) {
|
||||
throw std::invalid_argument{"duplicate profile '" + name + "'"};
|
||||
}
|
||||
for (const auto &option : compile_options)
|
||||
require_text(option, "compile option");
|
||||
records_.push_back({std::move(name), std::move(compile_options)});
|
||||
}
|
||||
|
||||
const std::vector<ProfileDescription> &Profiles::records() const noexcept { return records_; }
|
||||
|
||||
ProfileContext Profiles::resolve(std::string_view name, CompilerFamily compiler, std::string os,
|
||||
std::string architecture) const {
|
||||
const auto found = std::ranges::find(records_, name, &ProfileDescription::name);
|
||||
if (found == records_.end()) {
|
||||
throw std::invalid_argument{"unknown profile '" + std::string{name} + "'"};
|
||||
}
|
||||
ProfileContext context{found->name, compiler, std::move(os), std::move(architecture),
|
||||
found->compile_options};
|
||||
validate_context(context);
|
||||
return context;
|
||||
}
|
||||
|
||||
Profiles default_profiles() {
|
||||
Profiles result;
|
||||
result.add("debug", {"-O0", "-g"});
|
||||
result.add("release", {"-O3", "-DNDEBUG"});
|
||||
return result;
|
||||
}
|
||||
|
||||
SourceSet::SourceSet(std::initializer_list<std::string_view> files) {
|
||||
for (const auto path : files) {
|
||||
require_text(path, "source path");
|
||||
records_.push_back({SourceKind::file, std::string{path}});
|
||||
}
|
||||
}
|
||||
|
||||
SourceSet SourceSet::file(std::string path) {
|
||||
require_text(path, "source path");
|
||||
SourceSet result;
|
||||
result.records_.push_back({SourceKind::file, std::move(path)});
|
||||
return result;
|
||||
}
|
||||
|
||||
SourceSet SourceSet::glob(std::string pattern) {
|
||||
require_text(pattern, "glob pattern");
|
||||
SourceSet result;
|
||||
result.records_.push_back({SourceKind::glob, std::move(pattern)});
|
||||
return result;
|
||||
}
|
||||
|
||||
const std::vector<SourceRecord> &SourceSet::records() const noexcept { return records_; }
|
||||
|
||||
Target::Target(std::weak_ptr<detail::ProjectState> state, std::size_t index)
|
||||
: owner_{std::move(state)}, index_{index} {}
|
||||
|
||||
Target &Target::sources(const SourceSet &sources) {
|
||||
auto state = owner(owner_);
|
||||
auto &records = state->targets.at(index_).sources;
|
||||
records.insert(records.end(), sources.records().begin(), sources.records().end());
|
||||
return *this;
|
||||
}
|
||||
|
||||
Target &Target::include_directory(std::string path, Visibility visibility) {
|
||||
require_text(path, "include directory");
|
||||
(void)visibility_name(visibility);
|
||||
owner(owner_)->targets.at(index_).include_directories.push_back({std::move(path), visibility});
|
||||
return *this;
|
||||
}
|
||||
|
||||
Target &Target::compile_option(std::string option) {
|
||||
require_text(option, "compile option");
|
||||
owner(owner_)->targets.at(index_).compile_options.push_back(std::move(option));
|
||||
return *this;
|
||||
}
|
||||
|
||||
Target &Target::link(const Target &target, Visibility visibility) {
|
||||
auto state = owner(owner_);
|
||||
if (owner(target.owner_) != state) {
|
||||
throw std::invalid_argument{"cannot link a target from another Project"};
|
||||
}
|
||||
(void)visibility_name(visibility);
|
||||
state->targets.at(index_).links.push_back(
|
||||
{LinkKind::local, state->targets.at(target.index_).name, {}, visibility});
|
||||
return *this;
|
||||
}
|
||||
|
||||
Target &Target::link(const ImportedTarget &target, Visibility visibility) {
|
||||
auto state = owner(owner_);
|
||||
if (owner(target.owner_) != state) {
|
||||
throw std::invalid_argument{"cannot link an imported target from another Project"};
|
||||
}
|
||||
(void)visibility_name(visibility);
|
||||
state->targets.at(index_).links.push_back({LinkKind::imported, target.name_,
|
||||
state->dependencies.at(target.dependency_).name,
|
||||
visibility});
|
||||
return *this;
|
||||
}
|
||||
|
||||
const TargetRecord &Target::record() const { return owner(owner_)->targets.at(index_); }
|
||||
|
||||
ImportedTarget::ImportedTarget(std::weak_ptr<detail::ProjectState> state, std::size_t dependency,
|
||||
std::string name)
|
||||
: owner_{std::move(state)}, dependency_{dependency}, name_{std::move(name)} {}
|
||||
|
||||
Dependency::Dependency(std::weak_ptr<detail::ProjectState> state, std::size_t index)
|
||||
: owner_{std::move(state)}, index_{index} {}
|
||||
|
||||
Dependency &Dependency::git(std::string url, Commit commit) {
|
||||
require_text(url, "Git URL");
|
||||
if (commit.sha.size() != 40 || !std::ranges::all_of(commit.sha, [](char c) {
|
||||
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
|
||||
})) {
|
||||
throw std::invalid_argument{"Commit must contain an exact 40-digit hexadecimal Git SHA"};
|
||||
}
|
||||
auto state = owner(owner_);
|
||||
auto &record = state->dependencies.at(index_);
|
||||
if (record.source_kind != DependencySourceKind::unspecified) {
|
||||
throw std::invalid_argument{"dependency '" + record.name +
|
||||
"' already has a source provider"};
|
||||
}
|
||||
record.source_kind = DependencySourceKind::git;
|
||||
record.location = std::move(url);
|
||||
record.revision = std::move(commit.sha);
|
||||
return *this;
|
||||
}
|
||||
|
||||
Dependency &Dependency::cmake(OptionMap options) {
|
||||
for (const auto &[key, value] : options) {
|
||||
(void)value;
|
||||
require_text(key, "CMake option name");
|
||||
}
|
||||
auto state = owner(owner_);
|
||||
auto &record = state->dependencies.at(index_);
|
||||
if (record.source_kind == DependencySourceKind::package || !record.builder.empty()) {
|
||||
throw std::invalid_argument{"contradictory builder for dependency '" + record.name + "'"};
|
||||
}
|
||||
record.builder = "cmake";
|
||||
record.options = std::move(options);
|
||||
return *this;
|
||||
}
|
||||
|
||||
Dependency &Dependency::package(std::string id, std::string range) {
|
||||
require_text(id, "package identifier");
|
||||
require_text(range, "package version range");
|
||||
auto state = owner(owner_);
|
||||
auto &record = state->dependencies.at(index_);
|
||||
if (record.source_kind != DependencySourceKind::unspecified || !record.builder.empty()) {
|
||||
throw std::invalid_argument{"dependency '" + record.name +
|
||||
"' already has a source/provider"};
|
||||
}
|
||||
record.source_kind = DependencySourceKind::package;
|
||||
record.package = std::move(id);
|
||||
record.version = std::move(range);
|
||||
return *this;
|
||||
}
|
||||
|
||||
ImportedTarget Dependency::target(std::string exported_name) const {
|
||||
(void)owner(owner_);
|
||||
require_text(exported_name, "exported target name");
|
||||
return ImportedTarget{owner_, index_, std::move(exported_name)};
|
||||
}
|
||||
|
||||
const DependencyRecord &Dependency::record() const {
|
||||
return owner(owner_)->dependencies.at(index_);
|
||||
}
|
||||
|
||||
Project::Project(ProfileContext context) : state_{std::make_shared<detail::ProjectState>()} {
|
||||
validate_context(context);
|
||||
state_->context = std::move(context);
|
||||
}
|
||||
Project::~Project() = default;
|
||||
const ProfileContext &Project::context() const noexcept { return state_->context; }
|
||||
|
||||
Target Project::add_target(std::string name, TargetKind kind) {
|
||||
require_text(name, "target name");
|
||||
if (std::ranges::any_of(state_->targets,
|
||||
[&](const auto &record) { return record.name == name; })) {
|
||||
throw std::invalid_argument{"duplicate target '" + name + "'"};
|
||||
}
|
||||
state_->targets.push_back({std::move(name), kind, {}, {}, {}, {}});
|
||||
return Target{state_, state_->targets.size() - 1};
|
||||
}
|
||||
Target Project::executable(std::string name) {
|
||||
return add_target(std::move(name), TargetKind::executable);
|
||||
}
|
||||
Target Project::static_library(std::string name) {
|
||||
return add_target(std::move(name), TargetKind::static_library);
|
||||
}
|
||||
Dependency Project::dependency(std::string name) {
|
||||
require_text(name, "dependency name");
|
||||
if (std::ranges::any_of(state_->dependencies,
|
||||
[&](const auto &record) { return record.name == name; })) {
|
||||
throw std::invalid_argument{"duplicate dependency '" + name + "'"};
|
||||
}
|
||||
DependencyRecord record;
|
||||
record.name = std::move(name);
|
||||
state_->dependencies.push_back(std::move(record));
|
||||
return Dependency{state_, state_->dependencies.size() - 1};
|
||||
}
|
||||
SourceSet Project::glob(std::string pattern) const { return SourceSet::glob(std::move(pattern)); }
|
||||
const std::vector<TargetRecord> &Project::targets() const noexcept { return state_->targets; }
|
||||
const std::vector<DependencyRecord> &Project::dependencies() const noexcept {
|
||||
return state_->dependencies;
|
||||
}
|
||||
|
||||
std::string Project::to_json() const {
|
||||
const auto &profile = context();
|
||||
std::string output =
|
||||
"{\"schema_version\":" + std::to_string(schema_version) +
|
||||
",\"profile\":{\"name\":" + quote(profile.name) +
|
||||
",\"compiler\":" + quote(compiler_name(profile.compiler)) + ",\"os\":" + quote(profile.os) +
|
||||
",\"architecture\":" + quote(profile.architecture) +
|
||||
",\"compile_options\":" + array(profile.compile_options, quote) + "},\"targets\":";
|
||||
output += array(targets(), [](const TargetRecord &target) {
|
||||
return "{\"name\":" + quote(target.name) + ",\"kind\":" +
|
||||
quote(target.kind == TargetKind::executable ? "executable" : "static_library") +
|
||||
",\"sources\":" +
|
||||
array(target.sources,
|
||||
[](const SourceRecord &source) {
|
||||
return "{\"kind\":" +
|
||||
quote(source.kind == SourceKind::file ? "file" : "glob") +
|
||||
",\"path\":" + quote(source.path) + '}';
|
||||
}) +
|
||||
",\"include_directories\":" +
|
||||
array(target.include_directories,
|
||||
[](const IncludeDirectory &directory) {
|
||||
return "{\"path\":" + quote(directory.path) +
|
||||
",\"visibility\":" + quote(visibility_name(directory.visibility)) +
|
||||
'}';
|
||||
}) +
|
||||
",\"compile_options\":" + array(target.compile_options, quote) + ",\"links\":" +
|
||||
array(target.links,
|
||||
[](const LinkRecord &link) {
|
||||
return "{\"kind\":" +
|
||||
quote(link.kind == LinkKind::local ? "local" : "imported") +
|
||||
",\"target\":" + quote(link.target) +
|
||||
",\"dependency\":" + quote(link.dependency) +
|
||||
",\"visibility\":" + quote(visibility_name(link.visibility)) + '}';
|
||||
}) +
|
||||
'}';
|
||||
});
|
||||
output += ",\"dependencies\":" + array(dependencies(), [](const DependencyRecord &dependency) {
|
||||
if (dependency.source_kind == DependencySourceKind::unspecified) {
|
||||
throw std::invalid_argument{"dependency '" + dependency.name +
|
||||
"' has no source provider"};
|
||||
}
|
||||
std::string result =
|
||||
"{\"name\":" + quote(dependency.name) + ",\"source\":{\"kind\":";
|
||||
if (dependency.source_kind == DependencySourceKind::git) {
|
||||
result += "\"git\",\"location\":" + quote(dependency.location) +
|
||||
",\"revision\":" + quote(dependency.revision);
|
||||
} else {
|
||||
result += "\"package\",\"package\":" + quote(dependency.package) +
|
||||
",\"version\":" + quote(dependency.version);
|
||||
}
|
||||
return result + "},\"builder\":" + quote(dependency.builder) +
|
||||
",\"options\":" + options_json(dependency.options) + '}';
|
||||
});
|
||||
return output + '}';
|
||||
}
|
||||
|
||||
} // namespace vbs
|
||||
@@ -1,43 +0,0 @@
|
||||
#include <Void/Configuration/Argparse.hpp>
|
||||
#include <vbs/bootstrap_config.hpp>
|
||||
|
||||
#include <iostream>
|
||||
#include <string_view>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
bool version = false;
|
||||
Void::Argparse::Parser parser{
|
||||
"vbs", "VoidBuildSystem bootstrap: help and version only.\n"
|
||||
"Native build, test, compdb, deps and watch commands are planned and unavailable."};
|
||||
parser.flag("--version", "-V", "show bootstrap version", version);
|
||||
const bool standalone_help =
|
||||
argc == 2 && (std::string_view{argv[1]} == "--help" || std::string_view{argv[1]} == "-h");
|
||||
if (argc == 1 || standalone_help) {
|
||||
std::cout << parser.help();
|
||||
return 0;
|
||||
}
|
||||
// Reject mixed help requests: Parser reports help through the same error channel as bad input.
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string_view arg{argv[i]};
|
||||
if (arg == "--help" || arg == "-h") {
|
||||
std::cerr << "vbs: --help must be used alone\n";
|
||||
return 2;
|
||||
}
|
||||
if (arg == "build" || arg == "test" || arg == "compdb" || arg == "deps" || arg == "watch") {
|
||||
std::cerr << "vbs: native command '" << arg
|
||||
<< "' is not implemented in this bootstrap\n";
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
const auto parsed = parser.parse(argc, argv);
|
||||
if (!parsed) {
|
||||
std::cerr << "vbs: " << parsed.error() << '\n';
|
||||
return 2;
|
||||
}
|
||||
if (version) {
|
||||
std::cout << "vbs " << vbs::bootstrap::version << " (bootstrap)\n";
|
||||
return 0;
|
||||
}
|
||||
std::cerr << "vbs: no supported request; use --help\n";
|
||||
return 2;
|
||||
}
|
||||
Reference in new issue
Block a user