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

This commit is contained in:
faumaray committed 2026-11-27 01:43:06 +03:00
1 parent ab64147f9d
commit 363fb8200e
33 files changed
+1754 -3155

No files matched your search

+68 -498
View File
@@ -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;
}