feat: adopt VoidLibrary VL-001..VL-013, self-building build.cpp, live logs, and generated CLI help
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 10s
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 10s
This commit is contained in:
1 parent
ab64147f9d
commit
363fb8200e
33 files changed
+1754
-3155
No files matched your search
+7
-12
@@ -12,22 +12,17 @@ int main(int argc, char **argv) {
|
||||
"Evaluate the compiled example description; no target compiler is invoked."};
|
||||
parser.option_default("--profile", "", "profile: debug or release", profile, "debug")
|
||||
.option_default("--compiler", "", "target compiler context: gcc or clang", compiler, "gcc");
|
||||
if (argc == 2 && (std::string_view{argv[1]} == "--help" || std::string_view{argv[1]} == "-h")) {
|
||||
std::cout << parser.help();
|
||||
|
||||
const auto parsed = parser.parse_detailed(argc, argv);
|
||||
if (parsed.is_help()) {
|
||||
std::cout << parsed.message;
|
||||
return 0;
|
||||
}
|
||||
// Help is deliberately successful only as a standalone request.
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
if (std::string_view{argv[i]} == "--help" || std::string_view{argv[i]} == "-h") {
|
||||
std::cerr << "vbs_describe: --help must be used alone\n";
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
const auto parsed = parser.parse(argc, argv);
|
||||
if (!parsed) {
|
||||
std::cerr << "vbs_describe: " << parsed.error() << '\n';
|
||||
if (parsed.is_error()) {
|
||||
std::cerr << "vbs_describe: " << parsed.message << '\n';
|
||||
return 2;
|
||||
}
|
||||
|
||||
try {
|
||||
Void::Build::Profiles descriptions;
|
||||
profiles(descriptions);
|
||||
|
||||
+57
-10
@@ -4,6 +4,7 @@
|
||||
#include <Void/Build/Platform/FileOps.hpp>
|
||||
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||
#include <Void/Build/Util/Sha256.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
#include <Void/Time/Stopwatch.hpp>
|
||||
@@ -266,17 +267,53 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state,
|
||||
|
||||
std::size_t active_workers = 0;
|
||||
std::size_t completed_count = 0;
|
||||
std::atomic<std::size_t> started_exec_count{0};
|
||||
bool abort_scheduling = false;
|
||||
|
||||
auto action_label = [&](const Graph::ActionNode &act) -> std::string {
|
||||
auto rel_name = [&](const std::filesystem::path &p) -> std::string {
|
||||
if (p.empty()) {
|
||||
return act.target_name;
|
||||
}
|
||||
if (!graph.project_root.empty() && Platform::path_is_within(graph.project_root, p)) {
|
||||
return p.lexically_relative(graph.project_root).generic_string();
|
||||
}
|
||||
return p.filename().string();
|
||||
};
|
||||
switch (act.kind) {
|
||||
case Graph::ActionKind::Compile:
|
||||
return std::format("Compile {}", rel_name(!act.logical_source_file.empty()
|
||||
? act.logical_source_file
|
||||
: act.logical_output_file));
|
||||
case Graph::ActionKind::PrecompiledHeader:
|
||||
return std::format("PCH {}", rel_name(act.logical_source_file));
|
||||
case Graph::ActionKind::HeaderUnit:
|
||||
return std::format("HdrUnit {}", rel_name(act.logical_source_file));
|
||||
case Graph::ActionKind::ModuleScan:
|
||||
return std::format("ModScan {}", rel_name(act.logical_source_file));
|
||||
case Graph::ActionKind::ModuleBmi:
|
||||
return std::format("BMI {}", rel_name(act.logical_source_file));
|
||||
case Graph::ActionKind::Archive:
|
||||
return std::format("Archive {}", rel_name(act.logical_output_file));
|
||||
case Graph::ActionKind::Link:
|
||||
return std::format("Link {}", rel_name(act.logical_output_file));
|
||||
case Graph::ActionKind::Custom:
|
||||
return std::format("Action {}", act.target_name);
|
||||
}
|
||||
return act.id;
|
||||
};
|
||||
|
||||
auto emit_event = [&](ExecutionEvent::Kind kind, const Graph::ActionNode &act,
|
||||
std::size_t completed, std::string msg = {}) {
|
||||
const std::string &label, std::size_t completed,
|
||||
std::chrono::milliseconds elapsed = {}, std::string msg = {}) {
|
||||
if (options.on_event) {
|
||||
options.on_event(ExecutionEvent{kind, act.id, act.target_name, completed,
|
||||
selected_indices.size(), std::move(msg)});
|
||||
options.on_event(ExecutionEvent{kind, act.id, act.target_name, label, completed,
|
||||
selected_indices.size(), elapsed, std::move(msg)});
|
||||
}
|
||||
};
|
||||
|
||||
auto run_one_action = [&](const Graph::ActionNode &act) -> ActionExecutionResult {
|
||||
auto run_one_action = [&](const Graph::ActionNode &act,
|
||||
const std::string &label) -> ActionExecutionResult {
|
||||
const auto timer = Void::Time::Stopwatch::started();
|
||||
ActionExecutionResult res;
|
||||
res.action_id = act.id;
|
||||
@@ -308,6 +345,10 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state,
|
||||
}
|
||||
}
|
||||
|
||||
const std::size_t seq = started_exec_count.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
Void::Log::info("Build", "[{:>2}/{}] {}", seq, selected_indices.size(), label);
|
||||
emit_event(ExecutionEvent::Kind::ActionStarted, act, label, seq);
|
||||
|
||||
// 2. Prepare output directories and response file.
|
||||
std::error_code ec;
|
||||
for (const auto &out : act.declared_outputs) {
|
||||
@@ -477,8 +518,8 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state,
|
||||
}
|
||||
|
||||
const auto &act = graph.actions[idx];
|
||||
emit_event(ExecutionEvent::Kind::ActionStarted, act, completed_count);
|
||||
auto ares = run_one_action(act);
|
||||
const std::string label = action_label(act);
|
||||
auto ares = run_one_action(act, label);
|
||||
|
||||
{
|
||||
std::lock_guard lk{mu};
|
||||
@@ -487,10 +528,14 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state,
|
||||
if (ares.succeeded) {
|
||||
if (ares.from_cache) {
|
||||
++report.cached_count;
|
||||
emit_event(ExecutionEvent::Kind::ActionCached, act, completed_count);
|
||||
Void::Log::debug("Build", "[cached] {}", label);
|
||||
emit_event(ExecutionEvent::Kind::ActionCached, act, label, completed_count,
|
||||
ares.elapsed);
|
||||
} else {
|
||||
++report.executed_count;
|
||||
emit_event(ExecutionEvent::Kind::ActionSucceeded, act, completed_count);
|
||||
Void::Log::debug("Build", "Done {} ({}ms)", label, ares.elapsed.count());
|
||||
emit_event(ExecutionEvent::Kind::ActionSucceeded, act, label,
|
||||
completed_count, ares.elapsed);
|
||||
}
|
||||
for (const std::size_t dep_idx : dependents[idx]) {
|
||||
if (--in_degree[dep_idx] == 0) {
|
||||
@@ -505,8 +550,10 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state,
|
||||
if (report.diagnostic.empty()) {
|
||||
report.diagnostic = act.id + ": " + ares.error_message;
|
||||
}
|
||||
emit_event(ExecutionEvent::Kind::ActionFailed, act, completed_count,
|
||||
ares.error_message);
|
||||
Void::Log::error("Build", "FAILED {} ({}): {}", label, act.id,
|
||||
ares.error_message);
|
||||
emit_event(ExecutionEvent::Kind::ActionFailed, act, label, completed_count,
|
||||
ares.elapsed, ares.error_message);
|
||||
if (options.fail_fast) {
|
||||
abort_scheduling = true;
|
||||
internal_stop.request_stop();
|
||||
|
||||
+24
-5
@@ -565,8 +565,9 @@ lower_project_graph(const ProjectDescription &description,
|
||||
graph.toolchain = toolchain;
|
||||
graph.profile_identity = Toolchain::compute_profile_identity(description.profile, toolchain);
|
||||
graph.project_root = canonical_root;
|
||||
graph.profile_build_dir = std::filesystem::weakly_canonical(options.build_root, ec) /
|
||||
"profiles" / sanitize_id_component(description.profile.name);
|
||||
const auto canonical_build_root = std::filesystem::weakly_canonical(options.build_root, ec);
|
||||
graph.profile_build_dir =
|
||||
canonical_build_root / "profiles" / sanitize_id_component(description.profile.name);
|
||||
if (options.snapshot) {
|
||||
graph.snapshot_id = options.snapshot->snapshot_id;
|
||||
graph.snapshot_materialized_root = options.snapshot->materialized_root;
|
||||
@@ -691,9 +692,14 @@ lower_project_graph(const ProjectDescription &description,
|
||||
return logical_abs;
|
||||
}
|
||||
if (Platform::path_is_within(canonical_root, logical_abs) &&
|
||||
!Platform::path_is_within(canonical_build_root, logical_abs) &&
|
||||
!Platform::path_is_within(graph.profile_build_dir, logical_abs)) {
|
||||
const auto rel = logical_abs.lexically_relative(canonical_root);
|
||||
return graph.snapshot_materialized_root / rel;
|
||||
const auto candidate = graph.snapshot_materialized_root / rel;
|
||||
std::error_code mec;
|
||||
if (std::filesystem::exists(candidate, mec)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return logical_abs;
|
||||
};
|
||||
@@ -742,9 +748,22 @@ lower_project_graph(const ProjectDescription &description,
|
||||
act.id = "custom:" + sanitize_id_component(t.name);
|
||||
act.kind = ActionKind::Custom;
|
||||
act.target_name = t.name;
|
||||
act.executable = t.command_argv.front();
|
||||
auto expand_vars = [&](std::string text) {
|
||||
auto replace_all = [&](std::string_view token, const std::string &val) {
|
||||
std::size_t pos = 0;
|
||||
while ((pos = text.find(token, pos)) != std::string::npos) {
|
||||
text.replace(pos, token.size(), val);
|
||||
pos += val.size();
|
||||
}
|
||||
};
|
||||
replace_all("$GEN", generated_root.string());
|
||||
replace_all("$PROJECT_ROOT", canonical_root.string());
|
||||
replace_all("$BUILD_DIR", graph.profile_build_dir.string());
|
||||
return text;
|
||||
};
|
||||
act.executable = expand_vars(t.command_argv.front());
|
||||
for (std::size_t i = 1; i < t.command_argv.size(); ++i) {
|
||||
act.arguments.push_back(t.command_argv[i]);
|
||||
act.arguments.push_back(expand_vars(t.command_argv[i]));
|
||||
}
|
||||
act.environment = t.environment;
|
||||
if (!t.nondeterministic && !description.profile.nondeterministic) {
|
||||
|
||||
+691
-525
File diff suppressed because it is too large.
Load diff
+68
-498
@@ -1,18 +1,13 @@
|
||||
#include <Void/Build/Package/Archive.hpp>
|
||||
|
||||
#include <Void/Archive/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 {
|
||||
@@ -21,157 +16,13 @@ Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string m
|
||||
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) {
|
||||
bool is_excluded_package_path(const std::filesystem::path &rel) {
|
||||
for (const auto &part : rel) {
|
||||
const auto s = part.string();
|
||||
if (s == ".git" || s == ".vbs" || s == "build" || s == ".serena" || s == ".cache" ||
|
||||
s == "keys" || s == ".env" || s == "WG.conf") {
|
||||
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;
|
||||
}
|
||||
@@ -182,140 +33,39 @@ 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::ranges::sort(entries, {}, &ArchiveEntrySpec::archive_path);
|
||||
|
||||
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")};
|
||||
}
|
||||
std::vector<Void::Archive::CreateEntry> v_entries;
|
||||
v_entries.reserve(entries.size());
|
||||
for (const auto &e : entries) {
|
||||
Void::Archive::CreateEntry ce;
|
||||
ce.path = e.archive_path;
|
||||
ce.type = Void::Archive::EntryType::RegularFile;
|
||||
ce.executable = (e.mode & 0111u) != 0;
|
||||
ce.source_file = e.source_file;
|
||||
ce.mode = e.mode & 0777u;
|
||||
v_entries.push_back(std::move(ce));
|
||||
}
|
||||
|
||||
// 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")};
|
||||
}
|
||||
Void::Archive::CreationOptions opts;
|
||||
opts.compression = Void::Archive::ArchiveCompression::None;
|
||||
opts.reproducible = true;
|
||||
opts.canonical_mtime = reproducibility_epoch;
|
||||
opts.canonical_uid = 0;
|
||||
opts.canonical_gid = 0;
|
||||
opts.prefer_builtin_tar = true;
|
||||
|
||||
if (const auto closed = guard.close(); !closed) {
|
||||
std::filesystem::remove(temp_tar, ec);
|
||||
return std::unexpected{closed.error()};
|
||||
// Delegate deterministic PAX/USTAR tar creation directly to Void::Archive (VL-006).
|
||||
auto created = Void::Archive::create(output_tar, v_entries, opts);
|
||||
if (!created) {
|
||||
return std::unexpected{std::move(created.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();
|
||||
return Util::sha256_file_hex(output_tar);
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string, Void::Result::Error>
|
||||
@@ -324,8 +74,9 @@ create_source_package(const std::filesystem::path &project_root,
|
||||
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")};
|
||||
return std::unexpected{make_error(
|
||||
Void::System::SystemErrorCode::not_found,
|
||||
std::format("create_source_package: '{}' is not a directory", project_root.string()))};
|
||||
}
|
||||
|
||||
std::vector<ArchiveEntrySpec> entries;
|
||||
@@ -333,23 +84,19 @@ create_source_package(const std::filesystem::path &project_root,
|
||||
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 (is_excluded_package_path(rel)) {
|
||||
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});
|
||||
auto meta = Platform::stat_lstat(it->path());
|
||||
if (!meta || !meta->exists || meta->is_symlink) {
|
||||
continue;
|
||||
}
|
||||
if (meta->is_regular) {
|
||||
entries.push_back({rel.lexically_normal().generic_string(), it->path(),
|
||||
(meta->mode & 0111u) ? 0755u : 0644u});
|
||||
}
|
||||
}
|
||||
return create_deterministic_tar(output_tar, std::move(entries), reproducibility_epoch);
|
||||
@@ -358,222 +105,45 @@ create_source_package(const std::filesystem::path &project_root,
|
||||
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();
|
||||
const auto parent = destination_dir.has_parent_path() ? destination_dir.parent_path()
|
||||
: std::filesystem::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);
|
||||
if (ec) {
|
||||
return std::unexpected{make_error(
|
||||
Void::System::map_errno_to_system_code(ec.value()),
|
||||
std::format("extract_safe_tar: failed creating parent '{}'", parent.string()),
|
||||
ec.value())};
|
||||
}
|
||||
|
||||
auto abort_extract = [&] { std::filesystem::remove_all(stage_dir, ec); };
|
||||
// Delegate safe staged extraction (rejecting traversal, absolute paths, symlinks,
|
||||
// hardlinks, duplicates, and quota overflows) directly to Void::Archive (VL-006).
|
||||
Void::Archive::StagedExtractionOptions opts;
|
||||
opts.limits.max_entries = limits.max_entries;
|
||||
opts.limits.max_file_bytes = limits.max_file_bytes;
|
||||
opts.limits.max_total_bytes = limits.max_total_bytes;
|
||||
opts.preserve_executable_bit = true;
|
||||
|
||||
auto staged = Void::Archive::extract_staged(tar_path, parent, opts);
|
||||
if (!staged) {
|
||||
return std::unexpected{std::move(staged.error())};
|
||||
}
|
||||
|
||||
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")};
|
||||
stats.entries = staged->entries();
|
||||
stats.total_bytes = staged->bytes();
|
||||
for (const auto &info : staged->inventory()) {
|
||||
if (info.type == Void::Archive::EntryType::RegularFile) {
|
||||
stats.extracted_files.emplace_back(info.path);
|
||||
}
|
||||
}
|
||||
|
||||
// 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())};
|
||||
auto pub = staged->publish(destination_dir.filename().string());
|
||||
if (!pub) {
|
||||
return std::unexpected{std::move(pub.error())};
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||
#include <Void/Build/Snapshot/Snapshot.hpp>
|
||||
#include <Void/Build/Util/Sha256.hpp>
|
||||
#include <Void/Configuration/Env.hpp>
|
||||
#include <Void/Core/Scope.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
#include <Void/Text/Str.hpp>
|
||||
|
||||
@@ -265,6 +267,26 @@ materialize_dependency_source(const DependencyRecord &dep, const FetchOptions &o
|
||||
|
||||
// 3. Exact pinned Git revision source.
|
||||
if (dep.source_kind == DependencySourceKind::Git) {
|
||||
if (dep.name == "VoidLibrary") {
|
||||
if (auto override_dir = Void::Configuration::get_env("VBS_VOID_SOURCE_DIR");
|
||||
override_dir && !override_dir->empty()) {
|
||||
const std::filesystem::path raw{*override_dir};
|
||||
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)) {
|
||||
Void::Log::info("Fetch",
|
||||
"Using VBS_VOID_SOURCE_DIR override for 'VoidLibrary': {}",
|
||||
canon.string());
|
||||
MaterializedSource out;
|
||||
out.alias = dep.name;
|
||||
out.source_dir = canon;
|
||||
out.content_identity_hash = dep.revision + "-local";
|
||||
out.from_cache = true;
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const auto git_dir =
|
||||
options.cache_dir / "git" / (sanitize_key(dep.name) + "_" + dep.revision);
|
||||
const auto marker = git_dir / ".vbs_verified_rev";
|
||||
@@ -275,6 +297,8 @@ materialize_dependency_source(const DependencyRecord &dep, const FetchOptions &o
|
||||
}
|
||||
|
||||
if (std::filesystem::is_regular_file(marker, ec)) {
|
||||
Void::Log::info("Fetch", "Using cached git dependency '{}' @ {}", dep.name,
|
||||
dep.revision.substr(0, 12));
|
||||
MaterializedSource out;
|
||||
out.alias = dep.name;
|
||||
out.source_dir = git_dir;
|
||||
@@ -283,6 +307,9 @@ materialize_dependency_source(const DependencyRecord &dep, const FetchOptions &o
|
||||
return out;
|
||||
}
|
||||
|
||||
Void::Log::info("Fetch", "Fetching git dependency '{}' from {} @ {}...", dep.name,
|
||||
redact_secrets(dep.location), dep.revision.substr(0, 12));
|
||||
|
||||
const bool is_local_repo = dep.location.starts_with("file://") ||
|
||||
dep.location.starts_with("/") ||
|
||||
std::filesystem::is_directory(dep.location, ec);
|
||||
|
||||
+2
-93
@@ -1,7 +1,6 @@
|
||||
#include <Void/Build/Package/Solver.hpp>
|
||||
|
||||
#include <Void/System/Types.hpp>
|
||||
#include <Void/Text/Str.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
@@ -16,99 +15,9 @@ Void::Result::Error solve_err(std::string msg) {
|
||||
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.
|
||||
// Delegates directly to Void::Semver::parse_range (VL-013 shorthand comparators now upstream).
|
||||
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);
|
||||
return Void::Semver::parse_range(expr);
|
||||
}
|
||||
|
||||
struct ActiveConstraint {
|
||||
|
||||
+92
-642
@@ -1,13 +1,11 @@
|
||||
#include <Void/Build/Package/Toml.hpp>
|
||||
|
||||
#include <Void/Build/Util/Json.hpp>
|
||||
#include <Void/Data/Toml.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <charconv>
|
||||
#include <cmath>
|
||||
#include <format>
|
||||
#include <set>
|
||||
|
||||
@@ -19,652 +17,101 @@ Void::Result::Error parse_err(const SourceOrigin &orig, std::string msg) {
|
||||
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)} {}
|
||||
TomlValue convert_from_void_toml(const Void::Data::Toml::Value &src,
|
||||
const std::string &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());
|
||||
TomlTable convert_table_from_void_toml(const Void::Data::Toml::Table &src,
|
||||
const std::string &source_name) {
|
||||
TomlTable dst;
|
||||
for (const auto &[k, v] : src.entries) {
|
||||
dst.emplace(k, convert_from_void_toml(v, source_name));
|
||||
}
|
||||
|
||||
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);
|
||||
return dst;
|
||||
}
|
||||
|
||||
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]);
|
||||
TomlValue convert_from_void_toml(const Void::Data::Toml::Value &src,
|
||||
const std::string &source_name) {
|
||||
const SourceOrigin orig{source_name, src.origin.line, src.origin.column};
|
||||
switch (src.kind()) {
|
||||
case Void::Data::Toml::ValueKind::String:
|
||||
return TomlValue{*src.as_string(), orig};
|
||||
case Void::Data::Toml::ValueKind::Boolean:
|
||||
return TomlValue{*src.as_bool(), orig};
|
||||
case Void::Data::Toml::ValueKind::Integer:
|
||||
return TomlValue{*src.as_integer(), orig};
|
||||
case Void::Data::Toml::ValueKind::Float:
|
||||
return TomlValue{*src.as_float(), orig};
|
||||
case Void::Data::Toml::ValueKind::DateTime:
|
||||
return TomlValue{src.as_datetime()->to_string(), orig};
|
||||
case Void::Data::Toml::ValueKind::Array: {
|
||||
TomlValue out = TomlValue::make_array(orig);
|
||||
for (const auto &el : src.as_array()->elements) {
|
||||
out.as_array_mut().push_back(convert_from_void_toml(el, source_name));
|
||||
}
|
||||
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);
|
||||
case Void::Data::Toml::ValueKind::Table: {
|
||||
TomlValue out = TomlValue::make_table(orig);
|
||||
out.as_table_mut() = convert_table_from_void_toml(*src.as_table(), source_name);
|
||||
return out;
|
||||
}
|
||||
out += "}";
|
||||
return out;
|
||||
case Void::Data::Toml::ValueKind::ArrayOfTables: {
|
||||
TomlValue out = TomlValue::make_array(orig);
|
||||
for (const auto &tbl : src.as_array_of_tables()->tables) {
|
||||
TomlValue item = TomlValue::make_table(orig);
|
||||
item.as_table_mut() = convert_table_from_void_toml(tbl, source_name);
|
||||
out.as_array_mut().push_back(std::move(item));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
return TomlValue{std::string{}, orig};
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
Void::Data::Toml::Value convert_to_void_toml(const TomlValue &src);
|
||||
|
||||
Void::Data::Toml::Table convert_table_to_void_toml(const TomlTable &src) {
|
||||
Void::Data::Toml::Table dst;
|
||||
for (const auto &[k, v] : src) {
|
||||
dst.entries.emplace(k, convert_to_void_toml(v));
|
||||
}
|
||||
return dst;
|
||||
}
|
||||
|
||||
bool option_value_equal(const OptionValue &a, const OptionValue &b) { return a.value == b.value; }
|
||||
Void::Data::Toml::Value convert_to_void_toml(const TomlValue &src) {
|
||||
if (src.is_string()) {
|
||||
return Void::Data::Toml::Value{src.as_string()};
|
||||
}
|
||||
if (src.is_bool()) {
|
||||
return Void::Data::Toml::Value{src.as_bool()};
|
||||
}
|
||||
if (src.is_int()) {
|
||||
return Void::Data::Toml::Value{src.as_int()};
|
||||
}
|
||||
if (src.is_double()) {
|
||||
return Void::Data::Toml::Value{src.as_double()};
|
||||
}
|
||||
if (src.is_array()) {
|
||||
Void::Data::Toml::Array arr;
|
||||
for (const auto &el : src.as_array()) {
|
||||
arr.elements.push_back(convert_to_void_toml(el));
|
||||
}
|
||||
return Void::Data::Toml::Value{std::move(arr)};
|
||||
}
|
||||
return Void::Data::Toml::Value{convert_table_to_void_toml(src.as_table())};
|
||||
}
|
||||
|
||||
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()) {
|
||||
if (a.name != b.name || a.source_kind != b.source_kind || a.location != b.location ||
|
||||
a.revision != b.revision || a.sha256 != b.sha256 || a.package != b.package ||
|
||||
a.version != b.version || a.registry_authority != b.registry_authority ||
|
||||
a.builder != b.builder || 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)) {
|
||||
const auto it = b.options.find(k);
|
||||
if (it == b.options.end() || av.value != it->second.value) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -675,23 +122,29 @@ bool dependency_records_equal(const DependencyRecord &a, const DependencyRecord
|
||||
|
||||
std::string SourceOrigin::format() const {
|
||||
if (line == 0) {
|
||||
return file.empty() ? "<unknown>" : file;
|
||||
return 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_table(SourceOrigin orig) {
|
||||
return TomlValue{std::make_shared<TomlTable>(), std::move(orig)};
|
||||
}
|
||||
|
||||
TomlValue TomlValue::make_array(SourceOrigin origin) {
|
||||
return TomlValue{std::make_shared<TomlArray>(), std::move(origin)};
|
||||
TomlValue TomlValue::make_array(SourceOrigin orig) {
|
||||
return TomlValue{std::make_shared<TomlArray>(), std::move(orig)};
|
||||
}
|
||||
|
||||
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();
|
||||
// Delegate full TOML 1.0 parsing directly to Void::Data::Toml (VL-002).
|
||||
auto parsed = Void::Data::Toml::parse(text);
|
||||
if (!parsed) {
|
||||
const SourceOrigin err_orig{std::string{source_name}, parsed.error().origin.line,
|
||||
parsed.error().origin.column};
|
||||
return std::unexpected{parse_err(err_orig, parsed.error().message)};
|
||||
}
|
||||
return convert_table_from_void_toml(parsed->root, std::string{source_name});
|
||||
}
|
||||
|
||||
Void::Result::Result<TomlTable, Void::Result::Error>
|
||||
@@ -704,9 +157,7 @@ parse_toml_file(const std::filesystem::path &path) {
|
||||
}
|
||||
|
||||
std::string serialize_toml(const TomlTable &table) {
|
||||
std::string out;
|
||||
serialize_table_section(table, "", out);
|
||||
return out;
|
||||
return Void::Data::Toml::serialize_table(convert_table_to_void_toml(table));
|
||||
}
|
||||
|
||||
Void::Result::Result<std::vector<NormalizedDependency>, Void::Result::Error>
|
||||
@@ -717,7 +168,6 @@ load_dependencies_toml(const std::filesystem::path &toml_path) {
|
||||
}
|
||||
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(
|
||||
|
||||
+28
-159
@@ -1,17 +1,11 @@
|
||||
#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>
|
||||
@@ -19,13 +13,6 @@
|
||||
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);
|
||||
@@ -33,26 +20,6 @@ Void::Result::Error sys_err(int err, std::string message) {
|
||||
|
||||
} // 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;
|
||||
@@ -64,28 +31,25 @@ FileLock::acquire(const std::filesystem::path &lock_path, LockMode mode, bool no
|
||||
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;
|
||||
const auto vl_mode = (mode == LockMode::Exclusive) ? Void::FileSystem::LockMode::Exclusive
|
||||
: Void::FileSystem::LockMode::Shared;
|
||||
if (non_blocking) {
|
||||
op |= LOCK_NB;
|
||||
}
|
||||
for (;;) {
|
||||
if (::flock(fd, op) == 0) {
|
||||
return FileLock{fd};
|
||||
auto res = Void::FileSystem::FileLock::try_lock(lock_path, vl_mode);
|
||||
if (!res) {
|
||||
return std::unexpected{std::move(res.error())};
|
||||
}
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
if (!res->has_value()) {
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::SystemErrorCode::busy,
|
||||
std::format("FileLock: '{}' is already locked", lock_path.string()), EWOULDBLOCK)};
|
||||
}
|
||||
const int err = errno;
|
||||
(void)::close(fd);
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("FileLock: flock failed for '{}'", lock_path.string()))};
|
||||
return FileLock{std::move(**res)};
|
||||
}
|
||||
auto res = Void::FileSystem::FileLock::lock(lock_path, vl_mode);
|
||||
if (!res) {
|
||||
return std::unexpected{std::move(res.error())};
|
||||
}
|
||||
return FileLock{std::move(*res)};
|
||||
}
|
||||
|
||||
Void::Result::Result<FileMetadata, Void::Result::Error>
|
||||
@@ -140,26 +104,6 @@ stat_lstat(const std::filesystem::path &path) {
|
||||
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);
|
||||
@@ -169,86 +113,24 @@ copy_isolated(const std::filesystem::path &src, const std::filesystem::path &dst
|
||||
dst.string(), ec.message()))};
|
||||
}
|
||||
}
|
||||
Void::FileSystem::CopyOptions opts;
|
||||
opts.overwrite = true;
|
||||
opts.preserve_permissions = !mode_override.has_value();
|
||||
opts.durability = Void::FileSystem::ReplaceDurability::atomic_visibility;
|
||||
|
||||
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()))};
|
||||
auto res = Void::FileSystem::reflink_copy_file(src, dst, opts);
|
||||
if (!res) {
|
||||
return std::unexpected{std::move(res.error())};
|
||||
}
|
||||
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;
|
||||
if (mode_override) {
|
||||
(void)::chmod(dst.c_str(), static_cast<mode_t>(*mode_override));
|
||||
}
|
||||
#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;
|
||||
return res->method == Void::FileSystem::CopyMethod::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 {};
|
||||
return Void::FileSystem::set_canonical_mtime(path, epoch_seconds, 0);
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error>
|
||||
@@ -319,19 +201,8 @@ atomic_swap_symlink(const std::filesystem::path &link_path, const std::filesyste
|
||||
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);
|
||||
return Void::FileSystem::atomic_symlink_swap(link_path, target,
|
||||
Void::FileSystem::ReplaceDurability::durable_sync);
|
||||
}
|
||||
|
||||
bool path_is_within(const std::filesystem::path &root, const std::filesystem::path &path) {
|
||||
@@ -373,7 +244,6 @@ resolve_confined_path(const std::filesystem::path &root, const std::filesystem::
|
||||
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;
|
||||
@@ -396,7 +266,6 @@ resolve_confined_path(const std::filesystem::path &root, const std::filesystem::
|
||||
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;
|
||||
|
||||
+104
-435
@@ -1,31 +1,19 @@
|
||||
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||
|
||||
#include <Void/Configuration/Env.hpp>
|
||||
#include <Void/System/Process.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 <chrono>
|
||||
#include <mutex>
|
||||
#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) {
|
||||
@@ -34,106 +22,9 @@ bool is_executable_file(const std::filesystem::path &p) {
|
||||
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});
|
||||
}
|
||||
void ensure_subreaper() noexcept {
|
||||
static std::once_flag once;
|
||||
std::call_once(once, [] { (void)Void::Process::enable_subreaper(); });
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -152,11 +43,13 @@ resolve_executable(const std::filesystem::path &executable,
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
std::string owned_env;
|
||||
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;
|
||||
} else if (auto env_val = Void::Configuration::get_env("PATH"); env_val) {
|
||||
owned_env = std::move(*env_val);
|
||||
path_env = owned_env;
|
||||
}
|
||||
std::size_t start = 0;
|
||||
while (start <= path_env.size()) {
|
||||
@@ -187,343 +80,119 @@ run_supervised(const ProcessRequest &request, std::stop_token stop) {
|
||||
"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;
|
||||
}
|
||||
ensure_subreaper();
|
||||
|
||||
// Delegate process spawning, streaming, timeout/cancellation, and robust -pgid
|
||||
// descendant SIGTERM -> SIGKILL supervision directly to Void::Process (VL-001).
|
||||
Void::Process::SpawnOptions opts;
|
||||
opts.executable = request.executable;
|
||||
opts.arguments = request.arguments;
|
||||
opts.working_directory = request.working_directory;
|
||||
opts.search_path = request.search_path;
|
||||
opts.new_process_group = true;
|
||||
opts.kill_grace = request.kill_grace;
|
||||
opts.stdin_pipe = true;
|
||||
opts.stdout_pipe = true;
|
||||
opts.stderr_pipe = true;
|
||||
|
||||
switch (request.environment.mode) {
|
||||
case EnvPolicyMode::Inherit:
|
||||
opts.environment.mode = Void::Process::EnvMode::inherit;
|
||||
break;
|
||||
case EnvPolicyMode::Allowlist:
|
||||
opts.environment.mode = Void::Process::EnvMode::allowlist;
|
||||
break;
|
||||
case EnvPolicyMode::ExplicitOnly:
|
||||
opts.environment.mode = Void::Process::EnvMode::explicit_only;
|
||||
break;
|
||||
}
|
||||
opts.environment.allowlist = request.environment.allowlist;
|
||||
opts.environment.unset_keys = request.environment.unset_keys;
|
||||
for (const auto &[k, v] : request.environment.set_vars) {
|
||||
opts.environment.set_vars.emplace_back(k, v);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
auto child = Void::Process::spawn(opts);
|
||||
if (!child) {
|
||||
ProcessResult fail;
|
||||
fail.exec_failed = true;
|
||||
fail.exec_error_message = child.error().message();
|
||||
return fail;
|
||||
}
|
||||
|
||||
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{};
|
||||
Void::Process::CaptureLimits limits;
|
||||
limits.max_stdout_bytes = request.max_stdout_bytes;
|
||||
limits.max_stderr_bytes = request.max_stderr_bytes;
|
||||
limits.max_line_bytes = 0; // Do not reject long compiler/linker diagnostic lines.
|
||||
limits.max_stdin_bytes = std::max(limits.max_stdin_bytes, request.stdin_data.size() + 1);
|
||||
limits.overflow_policy = request.fail_on_overflow
|
||||
? Void::Process::OverflowPolicy::fail_and_terminate
|
||||
: Void::Process::OverflowPolicy::drain_and_truncate;
|
||||
|
||||
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;
|
||||
}
|
||||
Void::Process::StreamCallbacks callbacks;
|
||||
const Void::Process::StreamCallbacks *cb_ptr = nullptr;
|
||||
if (request.on_stdout_chunk || request.on_stderr_chunk) {
|
||||
callbacks.on_stdout = request.on_stdout_chunk;
|
||||
callbacks.on_stderr = request.on_stderr_chunk;
|
||||
cb_ptr = &callbacks;
|
||||
}
|
||||
|
||||
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};
|
||||
}
|
||||
auto comm = Void::Process::communicate_blocking(*child, request.stdin_data, limits,
|
||||
request.timeout, stop, cb_ptr);
|
||||
if (!comm) {
|
||||
(void)child->terminate(request.kill_grace);
|
||||
return std::unexpected{std::move(comm.error())};
|
||||
}
|
||||
|
||||
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;
|
||||
// If the leader exited cleanly while descendants in its process group are still alive
|
||||
// (e.g. background child with redirected stdio), supervise the process group until it
|
||||
// drains, times out, or is cancelled, then escalate via SIGTERM -> kill_grace -> SIGKILL.
|
||||
bool group_timed_out = comm->timed_out;
|
||||
bool group_cancelled = comm->cancelled;
|
||||
const pid_t pgid = static_cast<pid_t>(child->pgid());
|
||||
if (!group_timed_out && !group_cancelled && !comm->overflowed) {
|
||||
while (child->process_group_alive()) {
|
||||
// Reap any adopted descendants in this process group (subreaper) so zombies clear.
|
||||
int wstatus = 0;
|
||||
while (pgid > 0 && ::waitpid(-pgid, &wstatus, WNOHANG) > 0) {
|
||||
}
|
||||
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;
|
||||
if (!child->process_group_alive()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
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 (stop.stop_requested()) {
|
||||
group_cancelled = true;
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
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 (has_timeout && std::chrono::steady_clock::now() >= deadline) {
|
||||
group_timed_out = true;
|
||||
break;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{10});
|
||||
}
|
||||
}
|
||||
|
||||
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 (group_cancelled || group_timed_out || comm->overflowed || child->process_group_alive()) {
|
||||
(void)child->terminate(request.kill_grace);
|
||||
int wstatus = 0;
|
||||
while (pgid > 0 && ::waitpid(-pgid, &wstatus, WNOHANG) > 0) {
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
ProcessResult result;
|
||||
result.exited = comm->status.exited;
|
||||
result.exit_code = comm->status.code;
|
||||
result.term_signal = comm->status.signal;
|
||||
result.stdout_data = std::move(comm->out);
|
||||
result.stderr_data = std::move(comm->err);
|
||||
result.stdout_truncated = comm->stdout_truncated;
|
||||
result.stderr_truncated = comm->stderr_truncated;
|
||||
result.timed_out = group_timed_out;
|
||||
result.cancelled = group_cancelled;
|
||||
result.overflowed = comm->overflowed;
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
+192
-17
@@ -5,8 +5,10 @@
|
||||
#include <Void/Build/Util/Json.hpp>
|
||||
#include <Void/Build/Util/Sha256.hpp>
|
||||
#include <Void/Data/StrictJson.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
#include <Void/Time/Stopwatch.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
@@ -237,6 +239,9 @@ run_cmake_provider(const ProviderRequest &request, const std::filesystem::path &
|
||||
build_dir / ".cmake" / "api" / "v1" / "query" / "codemodel-v2", "", false);
|
||||
|
||||
// 1. Configure with isolated profile/toolchain context.
|
||||
const auto sw = Void::Time::Stopwatch::started();
|
||||
Void::Log::info("Provider", "Configuring CMake dependency '{}' (profile='{}')...",
|
||||
request.dependency.name, request.profile.name);
|
||||
{
|
||||
Platform::ProcessRequest req;
|
||||
req.executable = *cmake_bin;
|
||||
@@ -254,6 +259,14 @@ run_cmake_provider(const ProviderRequest &request, const std::filesystem::path &
|
||||
req.arguments.push_back("-D" + k + "=" + cmake_option_value(v));
|
||||
}
|
||||
req.timeout = std::chrono::seconds{180};
|
||||
if (Void::Log::enabled(Void::Log::Level::Debug, "Provider")) {
|
||||
req.on_stdout_chunk = [&](std::string_view line) {
|
||||
Void::Log::debug("Provider", "[cmake:{}] {}", request.dependency.name, line);
|
||||
};
|
||||
req.on_stderr_chunk = [&](std::string_view line) {
|
||||
Void::Log::debug("Provider", "[cmake:{}] {}", request.dependency.name, line);
|
||||
};
|
||||
}
|
||||
auto proc = Platform::run_supervised(req, stop);
|
||||
if (!proc || !proc->succeeded()) {
|
||||
return std::unexpected{make_error(
|
||||
@@ -265,11 +278,20 @@ run_cmake_provider(const ProviderRequest &request, const std::filesystem::path &
|
||||
}
|
||||
|
||||
// 2. Build all targets in isolated build directory.
|
||||
Void::Log::info("Provider", "Building CMake dependency '{}'...", request.dependency.name);
|
||||
{
|
||||
Platform::ProcessRequest req;
|
||||
req.executable = *cmake_bin;
|
||||
req.arguments = {"--build", build_dir.string()};
|
||||
req.arguments = {"--build", build_dir.string(), "--parallel"};
|
||||
req.timeout = std::chrono::seconds{300};
|
||||
if (Void::Log::enabled(Void::Log::Level::Debug, "Provider")) {
|
||||
req.on_stdout_chunk = [&](std::string_view line) {
|
||||
Void::Log::debug("Provider", "[build:{}] {}", request.dependency.name, line);
|
||||
};
|
||||
req.on_stderr_chunk = [&](std::string_view line) {
|
||||
Void::Log::debug("Provider", "[build:{}] {}", request.dependency.name, line);
|
||||
};
|
||||
}
|
||||
auto proc = Platform::run_supervised(req, stop);
|
||||
if (!proc || !proc->succeeded()) {
|
||||
return std::unexpected{
|
||||
@@ -435,6 +457,37 @@ run_cmake_provider(const ProviderRequest &request, const std::filesystem::path &
|
||||
}
|
||||
}
|
||||
|
||||
// Extract link command fragments (-pthread, -ldl, -lm, etc.).
|
||||
if (const auto *lnk = find_key(*td, "link")) {
|
||||
if (const auto *lobj =
|
||||
std::get_if<JsonVal::Object>(&lnk->value)) {
|
||||
if (const auto *frags =
|
||||
find_key(*lobj, "commandFragments")) {
|
||||
if (const auto *farr =
|
||||
std::get_if<JsonVal::Array>(&frags->value)) {
|
||||
for (const auto &fv : *farr) {
|
||||
const auto *fo =
|
||||
std::get_if<JsonVal::Object>(&fv.value);
|
||||
if (!fo) {
|
||||
continue;
|
||||
}
|
||||
const auto role = get_str(*fo, "role");
|
||||
const auto frag = get_str(*fo, "fragment");
|
||||
if ((role == "libraries" || role == "flags") &&
|
||||
(frag == "-pthread" ||
|
||||
frag == "-lpthread" || frag == "-ldl" ||
|
||||
frag == "-lm" || frag == "-lrt")) {
|
||||
if (!std::ranges::contains(
|
||||
rt.iface.link_options, frag)) {
|
||||
rt.iface.link_options.push_back(frag);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract dependencies for transitive static archive ordering.
|
||||
if (const auto *deps = find_key(*td, "dependencies")) {
|
||||
if (const auto *darr =
|
||||
@@ -457,7 +510,8 @@ run_cmake_provider(const ProviderRequest &request, const std::filesystem::path &
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve transitive static library link order across CMake targets.
|
||||
// Resolve transitive static library link order across CMake targets using post-order DFS
|
||||
// reversed so every dependent library strictly precedes all of its dependencies on `ld`.
|
||||
ProviderExport exp;
|
||||
exp.dependency_name = request.dependency.name;
|
||||
exp.builder = "cmake";
|
||||
@@ -465,36 +519,157 @@ run_cmake_provider(const ProviderRequest &request, const std::filesystem::path &
|
||||
|
||||
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;
|
||||
std::vector<std::string> post_order;
|
||||
std::set<std::string> visited;
|
||||
auto dfs = [&](auto &&self, const std::string &cur_id) -> void {
|
||||
if (!visited.insert(cur_id).second) {
|
||||
return;
|
||||
}
|
||||
const auto dit = raw_by_id.find(dep_id);
|
||||
const auto dit = raw_by_id.find(cur_id);
|
||||
if (dit == raw_by_id.end()) {
|
||||
continue;
|
||||
return;
|
||||
}
|
||||
for (const auto &lib : dit->second.iface.static_libraries) {
|
||||
resolved.static_libraries.push_back(lib);
|
||||
for (const auto &sub : dit->second.dep_ids) {
|
||||
self(self, sub);
|
||||
}
|
||||
for (const auto &lib : dit->second.iface.shared_libraries) {
|
||||
resolved.shared_libraries.push_back(lib);
|
||||
post_order.push_back(cur_id);
|
||||
};
|
||||
for (const auto &dep_id : rt.dep_ids) {
|
||||
dfs(dfs, dep_id);
|
||||
}
|
||||
std::ranges::reverse(post_order);
|
||||
for (const auto &dep_id : post_order) {
|
||||
const auto &dep_rt = raw_by_id.at(dep_id);
|
||||
for (const auto &lib : dep_rt.iface.static_libraries) {
|
||||
if (!std::ranges::contains(resolved.static_libraries, lib)) {
|
||||
resolved.static_libraries.push_back(lib);
|
||||
}
|
||||
}
|
||||
for (const auto &inc : dit->second.iface.include_dirs) {
|
||||
for (const auto &lib : dep_rt.iface.shared_libraries) {
|
||||
if (!std::ranges::contains(resolved.shared_libraries, lib)) {
|
||||
resolved.shared_libraries.push_back(lib);
|
||||
}
|
||||
}
|
||||
for (const auto &inc : dep_rt.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);
|
||||
for (const auto &def : dep_rt.iface.defines) {
|
||||
if (!std::ranges::contains(resolved.defines, def)) {
|
||||
resolved.defines.push_back(def);
|
||||
}
|
||||
}
|
||||
for (const auto &lo : dep_rt.iface.link_options) {
|
||||
if (!std::ranges::contains(resolved.link_options, lo)) {
|
||||
resolved.link_options.push_back(lo);
|
||||
}
|
||||
}
|
||||
}
|
||||
// CMake targets linking Threads::Threads on GCC need -pthread at final link time.
|
||||
if ((rt.name.starts_with("Void_") || request.dependency.name == "VoidLibrary") &&
|
||||
!std::ranges::contains(resolved.link_options, std::string{"-pthread"})) {
|
||||
resolved.link_options.push_back("-pthread");
|
||||
}
|
||||
|
||||
exp.targets[rt.name] = resolved;
|
||||
exp.targets[request.dependency.name + "::" + rt.name] = resolved;
|
||||
// Register CMake `Namespace::Component` alias convention (e.g. `Void_Configuration` ->
|
||||
// `Void::Configuration`) because CMake File API codemodel-v2 omits ALIAS targets.
|
||||
if (const auto us = rt.name.find('_'); us != std::string::npos && us > 0) {
|
||||
const std::string alias = rt.name.substr(0, us) + "::" + rt.name.substr(us + 1);
|
||||
exp.targets[alias] = resolved;
|
||||
exp.targets[request.dependency.name + "::" + alias] = resolved;
|
||||
}
|
||||
}
|
||||
|
||||
// CMake File API codemodel-v2 omits INTERFACE (header-only) libraries. For VoidLibrary,
|
||||
// synthesize `Void::<Mod>` interfaces for any module directory under `src/` that CMake
|
||||
// configured as header-only (e.g. Text, Unicode, Async, Algorithms, Core, Data, Time,
|
||||
// Functional), propagating compiled `INTERNAL_DEPS` (such as LogState) automatically.
|
||||
if (request.dependency.name == "VoidLibrary" &&
|
||||
std::filesystem::is_directory(request.source.source_dir / "include", ec) &&
|
||||
std::filesystem::is_directory(request.source.source_dir / "src", ec)) {
|
||||
std::vector<std::string> hdr_mods;
|
||||
for (const auto &entry :
|
||||
std::filesystem::directory_iterator(request.source.source_dir / "src", ec)) {
|
||||
if (!entry.is_directory(ec)) {
|
||||
continue;
|
||||
}
|
||||
const std::string mod = entry.path().filename().string();
|
||||
const std::string alias = "Void::" + mod;
|
||||
if (!exp.targets.contains(alias)) {
|
||||
hdr_mods.push_back(mod);
|
||||
Graph::ImportedTargetInterface hi;
|
||||
hi.dependency_name = request.dependency.name;
|
||||
hi.target_name = alias;
|
||||
hi.include_dirs.emplace_back(request.source.source_dir / "include", false);
|
||||
hi.link_options.push_back("-pthread");
|
||||
exp.targets[alias] = hi;
|
||||
exp.targets[request.dependency.name + "::" + alias] = std::move(hi);
|
||||
}
|
||||
}
|
||||
// Attach compiled INTERNAL_DEPS (e.g. Void_LogState for Async/Log) to synthesized
|
||||
// header-only targets so linking any header-only Void module standalone works cleanly.
|
||||
for (const auto &mod : hdr_mods) {
|
||||
const auto mod_cmake = request.source.source_dir / "src" / mod / "module.cmake";
|
||||
if (!std::filesystem::is_regular_file(mod_cmake, ec)) {
|
||||
continue;
|
||||
}
|
||||
auto text = Void::FileSystem::read_file(mod_cmake);
|
||||
if (!text) {
|
||||
continue;
|
||||
}
|
||||
const auto pos = text->find("INTERNAL_DEPS");
|
||||
if (pos == std::string::npos) {
|
||||
continue;
|
||||
}
|
||||
const std::string alias = "Void::" + mod;
|
||||
auto &hi = exp.targets[alias];
|
||||
const std::string_view rest = std::string_view{*text}.substr(pos + 13);
|
||||
std::size_t idx = 0;
|
||||
while (idx < rest.size()) {
|
||||
while (idx < rest.size() && (rest[idx] == ' ' || rest[idx] == '\t' ||
|
||||
rest[idx] == '\r' || rest[idx] == '\n')) {
|
||||
++idx;
|
||||
}
|
||||
if (idx >= rest.size() || rest[idx] == ')') {
|
||||
break;
|
||||
}
|
||||
const std::size_t start = idx;
|
||||
while (idx < rest.size() && rest[idx] != ' ' && rest[idx] != '\t' &&
|
||||
rest[idx] != '\r' && rest[idx] != '\n' && rest[idx] != ')') {
|
||||
++idx;
|
||||
}
|
||||
const std::string dep_name{rest.substr(start, idx - start)};
|
||||
if (dep_name == "EXTERNAL_DEPS" || dep_name == "OPTIONAL_DEPS" ||
|
||||
dep_name == "DEPS_WIN32" || dep_name == "DEPS_UNIX" ||
|
||||
dep_name == "OPTIONS_WIN32" || dep_name == "OPTIONS_UNIX" ||
|
||||
dep_name == "EXTRA_HEADERS" || dep_name == "EXCLUDE_HEADERS") {
|
||||
break;
|
||||
}
|
||||
const auto dit = exp.targets.find("Void::" + dep_name);
|
||||
if (dit != exp.targets.end()) {
|
||||
for (const auto &lib : dit->second.static_libraries) {
|
||||
if (!std::ranges::contains(hi.static_libraries, lib)) {
|
||||
hi.static_libraries.push_back(lib);
|
||||
}
|
||||
}
|
||||
for (const auto &def : dit->second.defines) {
|
||||
if (!std::ranges::contains(hi.defines, def)) {
|
||||
hi.defines.push_back(def);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
exp.targets[request.dependency.name + "::" + alias] = hi;
|
||||
}
|
||||
}
|
||||
|
||||
Void::Log::info("Provider", "CMake dependency '{}' ready ({} targets in {}ms)",
|
||||
request.dependency.name, exp.targets.size(),
|
||||
sw.elapsed_as<std::chrono::milliseconds>().count());
|
||||
|
||||
// Apply explicit user overrides if supplied.
|
||||
for (const auto &[k, v] : request.explicit_overrides) {
|
||||
exp.targets[k] = v;
|
||||
|
||||
+42
-156
@@ -1,127 +1,45 @@
|
||||
#include <Void/Build/Util/Sha256.hpp>
|
||||
|
||||
#include <Void/System/Types.hpp>
|
||||
#include <Void/Text/Hex.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#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));
|
||||
Sha256Digest copy_digest(const Void::Crypto::Digest &src) noexcept {
|
||||
Sha256Digest out{};
|
||||
if (src.size() == out.size()) {
|
||||
std::memcpy(out.data(), src.data(), out.size());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // 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;
|
||||
Sha256Hasher::Sha256Hasher() {
|
||||
if (auto h = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256); h) {
|
||||
hasher_.emplace(std::move(*h));
|
||||
}
|
||||
}
|
||||
|
||||
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()});
|
||||
if (finalized_ || !hasher_ || data.empty()) {
|
||||
return;
|
||||
}
|
||||
(void)hasher_->update(data);
|
||||
}
|
||||
|
||||
void Sha256Hasher::update(std::span<const std::uint8_t> data) noexcept {
|
||||
update(std::as_bytes(data));
|
||||
}
|
||||
|
||||
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()});
|
||||
if (finalized_ || !hasher_ || text.empty()) {
|
||||
return;
|
||||
}
|
||||
(void)hasher_->update(text);
|
||||
}
|
||||
|
||||
void Sha256Hasher::update_u64(std::uint64_t value) noexcept {
|
||||
@@ -141,31 +59,14 @@ void Sha256Hasher::update_length_prefixed(std::string_view text) noexcept {
|
||||
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;
|
||||
if (hasher_) {
|
||||
if (auto d = hasher_->finalize(); d) {
|
||||
cached_digest_ = copy_digest(*d);
|
||||
}
|
||||
hasher_.reset();
|
||||
}
|
||||
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;
|
||||
return cached_digest_;
|
||||
}
|
||||
|
||||
std::string Sha256Hasher::finalize_hex() noexcept { return to_hex(finalize()); }
|
||||
@@ -175,45 +76,30 @@ std::string to_hex(const Sha256Digest &digest) {
|
||||
}
|
||||
|
||||
Sha256Digest sha256_bytes(std::span<const std::byte> data) noexcept {
|
||||
Sha256Hasher hasher;
|
||||
hasher.update(data);
|
||||
return hasher.finalize();
|
||||
if (auto d = Void::Crypto::sha256(data); d) {
|
||||
return copy_digest(*d);
|
||||
}
|
||||
return Sha256Digest{};
|
||||
}
|
||||
|
||||
std::string sha256_hex(std::string_view text) {
|
||||
Sha256Hasher hasher;
|
||||
hasher.update(text);
|
||||
return hasher.finalize_hex();
|
||||
if (auto d = Void::Crypto::sha256(text); d) {
|
||||
return Void::Encoding::Hex::encode(std::span<const std::uint8_t>{
|
||||
reinterpret_cast<const std::uint8_t *>(d->data()), d->size()});
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
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)};
|
||||
auto d = Void::Crypto::sha256_file(path);
|
||||
if (!d) {
|
||||
return std::unexpected{std::move(d.error())};
|
||||
}
|
||||
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();
|
||||
return Void::Encoding::Hex::encode(std::span<const std::uint8_t>{
|
||||
reinterpret_cast<const std::uint8_t *>(d->data()), d->size()});
|
||||
}
|
||||
|
||||
bool constant_time_equal(std::string_view a, std::string_view b) noexcept {
|
||||
|
||||
+57
-178
@@ -4,113 +4,10 @@
|
||||
#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,
|
||||
@@ -122,99 +19,70 @@ InotifyWatcher::create(const std::filesystem::path &root_dir,
|
||||
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")};
|
||||
|
||||
Void::FileSystem::DirectoryWatcherOptions opts;
|
||||
opts.ignore = [canon, excluded = std::move(excluded_names)](const std::filesystem::path &path,
|
||||
bool /*is_directory*/) {
|
||||
const auto rel = path.lexically_relative(canon);
|
||||
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;
|
||||
};
|
||||
|
||||
auto watcher = Void::FileSystem::DirectoryWatcher::create(canon, std::move(opts));
|
||||
if (!watcher) {
|
||||
return std::unexpected{std::move(watcher.error())};
|
||||
}
|
||||
InotifyWatcher watcher{fd, canon, std::move(excluded_names)};
|
||||
if (auto r = watcher.watch_tree(canon); !r) {
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
return watcher;
|
||||
return InotifyWatcher{std::move(*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);
|
||||
if (!watcher_) {
|
||||
return {};
|
||||
}
|
||||
wd_to_path_.clear();
|
||||
return watch_tree(root_);
|
||||
return watcher_->rescan();
|
||||
}
|
||||
|
||||
Void::Result::Result<WatchBatch, Void::Result::Error>
|
||||
InotifyWatcher::poll_events(std::chrono::milliseconds timeout, std::chrono::milliseconds debounce) {
|
||||
WatchBatch batch;
|
||||
if (fd_ < 0) {
|
||||
if (!watcher_) {
|
||||
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")};
|
||||
auto events = watcher_->poll(timeout);
|
||||
if (!events) {
|
||||
return std::unexpected{std::move(events.error())};
|
||||
}
|
||||
if (ready == 0) {
|
||||
if (events->empty()) {
|
||||
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;
|
||||
auto ingest = [&](const std::vector<Void::FileSystem::DirectoryEvent> &evs) {
|
||||
for (const auto &ev : evs) {
|
||||
if (ev.kind == Void::FileSystem::DirectoryEventKind::RescanRequired) {
|
||||
batch.overflowed = true;
|
||||
batch.rescan_required = true;
|
||||
continue;
|
||||
}
|
||||
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;
|
||||
}
|
||||
if (!ev.path.empty()) {
|
||||
unique_paths.insert(ev.path);
|
||||
}
|
||||
if (!ev.old_path.empty()) {
|
||||
unique_paths.insert(ev.old_path);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
drain_now();
|
||||
ingest(*events);
|
||||
|
||||
// Coalesce burst edits across the debounce window.
|
||||
if (debounce.count() > 0 && (!unique_paths.empty() || batch.rescan_required)) {
|
||||
@@ -225,13 +93,11 @@ InotifyWatcher::poll_events(std::chrono::milliseconds timeout, std::chrono::mill
|
||||
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 {
|
||||
auto more = watcher_->poll(rem);
|
||||
if (!more || more->empty()) {
|
||||
break;
|
||||
}
|
||||
ingest(*more);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -344,6 +210,19 @@ WatchCycleReport run_reconcile_cycle(const WatchLoopOptions &options, std::size_
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const auto &src : t.sources) {
|
||||
if (src.kind == SourceKind::File && !src.path.starts_with("$GEN/") &&
|
||||
!src.path.starts_with("gen/")) {
|
||||
const auto p = std::filesystem::path{src.path}.is_absolute()
|
||||
? std::filesystem::path{src.path}
|
||||
: (options.frontend.project_root / src.path);
|
||||
const auto dir = p.parent_path();
|
||||
if (!dir.empty() && std::filesystem::is_directory(dir, ec) &&
|
||||
!std::ranges::contains(scan_roots, dir)) {
|
||||
scan_roots.push_back(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Snapshot::SnapshotOptions sopts;
|
||||
|
||||
Reference in new issue
Block a user