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

+1 -1
View File
@@ -14,7 +14,7 @@ The user's environment provides `dev cpp-gcc -c COMMAND...` (GCC 16.2,
CMake 4.4.4, Ninja 1.13.2, Meson 1.12.1) and `dev cpp -c COMMAND...`
(Clang 23.1.3). Use the GCC environment for this C++26 bootstrap.
The bootstrap's source dependency is VoidLibrary at
9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5.
3e254055e081a104f08df68dde39711bc7813518.
An explicit VBS_VOID_SOURCE_DIR override is development-only; never change
that external checkout. It may contain untracked secrets.
+5 -10
View File
@@ -18,7 +18,7 @@ endif()
option(VBS_BUILD_TESTS "Build declaration SDK and native engine test suites" ON)
option(VBS_BUILD_BENCHMARKS "Build reproducible VBS benchmark harness" ON)
set(VBS_VOID_SOURCE_DIR "" CACHE PATH "Development-only VoidLibrary source override (bypasses pin)")
set(VBS_VOID_REVISION "9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5")
set(VBS_VOID_REVISION "3e254055e081a104f08df68dde39711bc7813518")
include(cmake/VoidDependency.cmake)
vbs_add_void_dependency()
@@ -69,19 +69,14 @@ target_link_libraries(VoidBuild_Core PUBLIC
Void::Text
Void::Unicode
Void::Async
Void::Algorithms)
Void::Algorithms
Void::Crypto
Void::Archive)
target_compile_definitions(VoidBuild_Core PUBLIC VBS_HAS_VOID_CRYPTO=1 VBS_HAS_VOID_ARCHIVE=1)
if(VBS_HAS_VOID_SQLITE)
target_link_libraries(VoidBuild_Core PUBLIC Void::Sqlite)
target_compile_definitions(VoidBuild_Core PUBLIC VBS_HAS_VOID_SQLITE=1)
endif()
if(VBS_HAS_VOID_CRYPTO)
target_link_libraries(VoidBuild_Core PUBLIC Void::Crypto)
target_compile_definitions(VoidBuild_Core PUBLIC VBS_HAS_VOID_CRYPTO=1)
endif()
if(VBS_HAS_VOID_ARCHIVE)
target_link_libraries(VoidBuild_Core PUBLIC Void::Archive)
target_compile_definitions(VoidBuild_Core PUBLIC VBS_HAS_VOID_ARCHIVE=1)
endif()
add_library(VoidBuild_Registry STATIC
registry/service/HttpServer.cpp
+25 -7
View File
@@ -8,11 +8,12 @@ profile definitions live in ordinary `build.cpp`, `build.profiles.cpp`, and
**Implemented scope (Plans 01–19):**
- **Declaration SDK (`Void::Build`, `<Void/Build.hpp>`)**: `VoidBuild_Sdk` / `Void::BuildSdk` with version-1 deterministic UTF-8 JSON schema, profile inheritance and cycle detection, all seven `TargetKind`s, scoped options/defines/links, modern C++ flags, install rules, and symbolic TOML manifest references.
- **Native Core Engine (`VoidBuild_Core` / `Void::BuildCore`)**: out-of-process host descriptor compilation, graph lowering and transitive visibility resolution, GCC 16 & Clang 23 toolchain discovery/capability probing, content-verified immutable snapshots (`FICLONE`/isolated copies, lookup guards), transactional CAS store (`StateStore`), and bounded-parallel DAG execution (`ProcessSupervisor` with `-pgid` `SIGTERM -> SIGKILL` cleanup).
- **Modern C++, Editor Metadata & Watchers**: Full graph-integrated P1689r5 named modules & module partitions (GCC `-fmodule-mapper` and Clang two-step `--precompile` `.pcm` -> `.o` + transitive `-fmodule-file=`), explicit `SourceKind::HeaderUnit` compilation, unity batches (excluding modules and per-file overrides), incompatible sanitizer rejection, per-profile `compile_commands.json` with monotonic selection tickets and user-file preservation, and Linux `inotify` build/metadata watching (`MetadataOnly` never triggers builds or foreign configures).
- **Native Package Manager, Foreign Providers, Bridge & Install**: TOML 1.0 parser/merger, PubGrub-style SemVer solver, context-aware CAS `vbs.lock`, live registry HTTP/1.1 client (`vbs publish`, `vbs deps resolve|update`, `vbs build --locked` against `vbs-registry`), deterministic PAX/USTAR `.tar` packaging with safe extraction, CMake File API & Meson introspection providers (plus explicit-error Conan2 adapter), `cmake/bridge/VbsDeps.cmake`, and staged relocatable install/export/uninstall.
- **Native Core Engine (`VoidBuild_Core` / `Void::BuildCore`)**: out-of-process host descriptor compilation, graph lowering and transitive visibility resolution, GCC 16 & Clang 23 toolchain discovery/capability probing, content-verified immutable snapshots (`FICLONE`/isolated copies, lookup guards), transactional CAS store (`StateStore`), bounded-parallel DAG execution (`ProcessSupervisor` with `-pgid` `SIGTERM -> SIGKILL` cleanup), and live `Void::Log` progress logging (`--verbose`/`-v`, `--quiet`/`-q`).
- **Self-Building `build.cpp`**: Root [build.cpp](build.cpp) declares the full `VoidBuildSystem` (`VoidBuildSdk`, `VoidBuildCore`, `GenerateBootstrapConfig`, `vbs`, `VoidBuildRegistry`, `vbs-registry`) so `vbs build` compiles and links `VoidBuildSystem` itself end-to-end.
- **Modern C++, Editor Metadata & Watchers**: Full graph-integrated P1689r5 named modules & module partitions (GCC `-fmodule-mapper` and Clang two-step `--precompile` `.pcm` -> `.o` + transitive `-fmodule-file=`), explicit `SourceKind::HeaderUnit` compilation, unity batches (excluding modules and per-file overrides), incompatible sanitizer rejection, per-profile `compile_commands.json` with monotonic selection tickets and user-file preservation, and Linux `inotify` build/metadata watching via `Void::FileSystem::DirectoryWatcher` (`MetadataOnly` never triggers builds or foreign configures).
- **Native Package Manager, Foreign Providers, Bridge & Install**: `Void::Data::Toml` 1.0 parser/merger, PubGrub-style SemVer solver (`Void::Semver::parse_range`), context-aware CAS `vbs.lock`, live registry HTTP/1.1 client (`vbs publish`, `vbs deps resolve|update`, `vbs build --locked` against `vbs-registry`), deterministic PAX/USTAR `.tar` packaging & staged safe extraction (`Void::Archive`), CMake File API & Meson introspection providers (plus explicit-error Conan2 adapter), `cmake/bridge/VbsDeps.cmake`, and staged relocatable install/export/uninstall.
- **Registry Service, Web Admin UI & Native Self-Hosting**: `vbs-registry` HTTP/1.1 service (`VoidBuild_Registry` / `Void::BuildRegistry`) with RBAC, salted password hashes, CSRF/HttpOnly session auth, immutable releases, backup/restore, XSS-safe DOM-only web UI (`registry/web/`), native `VoidLibrary` & full `VbsSelfHostRecipe` recipes (`recipes/VoidLibrary/`, `recipes/SelfHost/`) compiling the full Stage 1 `vbs` binary without CMake to build & test Stage 2 projects, and non-CMake `Void::Testing` registration generator (`vbs gen-tests`).
- **VoidLibrary Reuse**: Built directly on VoidLibrary `Configuration` (`Void::Argparse::Parser` across `vbs`, `vbs-registry`, `vbs_describe`, and `vbs_benchmarks`; `Void::Configuration::get_env`/`get_env_or`), `Algorithms` (`Void::Algorithms::topological_order`), `Async` (`Void::Concurrency::ThreadPool`), `Unicode` (`Void::Unicode::validate_utf8`), `Text` (`Void::Str`, `Void::Encoding::Hex`, `Void::Encoding::Url`, `Void::Semver`), `Core` (`Void::Scope::on_exit`), `Time` (`Void::Time::Stopwatch`), `Data` (`Void::Json::Strict`), `System` (`Void::FileSystem`, `Void::Process::SignalWatcher`), and `Testing`.
- **Maximal VoidLibrary Reuse (`3e254055...`)**: Built directly on VoidLibrary `Configuration` (`Void::Argparse::Parser` with nested subcommands, `option_many`, and 100% auto-generated `--help` across `vbs`, `vbs-registry`, `vbs_describe`, and `vbs_benchmarks`; `Void::Configuration::get_env`/`get_env_or`), `Crypto` (`Void::Crypto::Hasher` zero-dep SHA-256), `Archive` (`Void::Archive::create` & `extract_staged`), `Data` (`Void::Data::Toml`, `Void::Json::Strict`), `System` (`Void::Process::spawn`/`communicate_blocking`/`enable_subreaper`, `Void::FileSystem::DirectoryWatcher`/`FileLock`/`reflink_copy_file`/`set_canonical_mtime`/`atomic_symlink_swap`, `Void::Process::SignalWatcher`), `Algorithms` (`Void::Algorithms::topological_order`), `Async` (`Void::Concurrency::ThreadPool`), `Unicode` (`Void::Unicode::validate_utf8`), `Text` (`Void::Str`, `Void::Encoding::Hex`, `Void::Encoding::Url`, `Void::Semver::parse_range`), `Log` (`Void::Log`), `Core` (`Void::Scope::on_exit`), `Time` (`Void::Time::Stopwatch`), and `Testing`.
- **Remaining future design scope**: [Plan 20 — Later native foreign execution and platform ports](docs/roadmap/20-future-translation-platforms.md) (native foreign graph translation and Windows/macOS ports) remains planned architectural scope.
Start with the [twenty roadmap plans](docs/roadmap/README.md),
@@ -33,6 +34,8 @@ Start with the [twenty roadmap plans](docs/roadmap/README.md),
Requirements: GCC 16+ with C++26 `-freflection`, CMake 4.0+, Git, and Ninja (verified on NixOS via `dev cpp-gcc` with GCC 16.2.0, CMake 4.4.4, Ninja 1.13.2, Meson 1.12.1; Clang target matrix verified via `dev cpp` with Clang 23.1.3 and `clang-scan-deps`).
### Bootstrap build (CMake)
```sh
dev cpp-gcc -c cmake -S . -B build/dev -G Ninja \
-DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
@@ -41,7 +44,7 @@ dev cpp-gcc -c ctest --test-dir build/dev --output-on-failure
dev cpp-gcc -c build/dev/bin/vbs_benchmarks --files 15
```
CMake fetches VoidLibrary at pinned commit `9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5`.
CMake fetches VoidLibrary at pinned commit `3e254055e081a104f08df68dde39711bc7813518`.
For development against a local checkout without mutating the pin:
```sh
@@ -49,11 +52,26 @@ dev cpp-gcc -c cmake -S . -B build/dev-local -G Ninja \
-DCMAKE_BUILD_TYPE=Debug -DVBS_VOID_SOURCE_DIR=../VoidLibrary
```
Note on optional system dependencies: `dev cpp-gcc` provides pure-C++/Threads dependencies without external `SQLite3`, `OpenSSL`, `LibArchive`, or `conan`. `Void::BuildCore` links optional VoidLibrary modules when available and provides verified swappable local adapters in the meantime (tracked in [docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md](docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md)). Note that `conan` invocation requires `conan` in `PATH` and fails explicitly with a missing-prerequisite diagnostic when absent.
### Self-building VoidBuildSystem with `vbs`
Once the bootstrap `vbs` binary is built, `VoidBuildSystem` builds itself directly from root [build.cpp](build.cpp) with live progress logs (`-v`/`--verbose` for debug detail, `-q`/`--quiet` for warnings/errors only):
```sh
dev cpp-gcc -c build/dev/bin/vbs build --build-dir build/vbs-self
build/vbs-self/profiles/debug/out/bin/vbs --version
build/vbs-self/profiles/debug/out/bin/vbs --help
```
For offline/local VoidLibrary development during `vbs build`, set `VBS_VOID_SOURCE_DIR=/path/to/VoidLibrary`.
Note on optional system dependencies: `Void::Crypto` (`VL-007`) and `Void::Archive` (`VL-006`) now build cleanly with zero external system dependencies in `dev cpp-gcc`. `SQLite3`, `Boost`/`OpenSSL` (for `Void::Net`), and `conan` remain optional; VBS links `Void::Sqlite` automatically when system `SQLite3` is installed and uses its verified pure-C++/POSIX adapters otherwise (tracked in [docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md](docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md)). `conan` invocation requires `conan` in `PATH` and fails explicitly with a missing-prerequisite diagnostic when absent.
## CLI Reference
- `vbs build [--project DIR] [--build-dir DIR] [--profile NAME]... [--target NAME]... [--compiler gcc|clang] [--editor-profile NAME] [--build-source FILE]... [--jobs N] [--locked] [--offline] [--no-cache]`
All CLI help text (`vbs --help`, `vbs <command> --help`, `vbs compdb --help`, `vbs deps --help`, `vbs-registry --help`, etc.) is auto-generated directly by `Void::Argparse::Parser`:
- `vbs [--version] [--verbose] [--quiet] <command>`
- `vbs build [--project DIR] [--build-dir DIR] [--profile NAME]... [--target NAME]... [--compiler gcc|clang] [--editor-profile NAME] [--build-source FILE]... [--jobs N] [--locked] [--offline] [--no-cache] [--verbose] [--quiet]`
- `vbs test ...` (same flags as `vbs build`, then runs selected `TargetKind::Test` binaries)
- `vbs describe [--project DIR] [--build-dir DIR] [--profile NAME] [--compiler gcc|clang]`
- `vbs compdb use|show|export|watch ...`
+26 -25
View File
@@ -11,48 +11,49 @@
#include <chrono>
#include <iostream>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
using namespace Void::Build;
int main(int argc, char **argv) {
std::string files_opt;
std::string jobs_opt;
std::vector<std::string> positional_files;
Void::Argparse::Parser parser{
"vbs_benchmarks",
"Run reproducible snapshot, cold build, and warm no-op timings for VoidBuildSystem."};
parser.option_default("--files", "-n", "number of generated source units", files_opt, "20")
.option_default("--jobs", "-j", "parallel worker count", jobs_opt, "4");
.option_default("--jobs", "-j", "parallel worker count", jobs_opt, "4")
.positional_many("count", "optional positional file count override", positional_files,
false);
// Preserve positional shorthand `vbs_benchmarks 15` alongside `--files 15`.
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;
}
if (parsed.is_error()) {
std::cerr << "vbs_benchmarks: " << parsed.message << '\n';
return 2;
}
if (positional_files.size() > 1) {
std::cerr << "vbs_benchmarks: expected at most one positional count argument\n";
return 2;
}
if (!positional_files.empty()) {
files_opt = positional_files.front();
}
int parsed_files = 20;
int parsed_jobs = 4;
if (argc == 2 && Void::Str::to_int(argv[1], parsed_files)) {
if (parsed_files <= 0) {
std::cerr << "vbs_benchmarks: file count must be positive\n";
return 2;
}
} else {
auto parsed = parser.parse(argc, argv);
if (!parsed) {
std::cerr << "vbs_benchmarks: " << parsed.error() << '\n';
return 2;
}
if (!Void::Str::to_int(files_opt, parsed_files) || parsed_files <= 0) {
std::cerr << "vbs_benchmarks: invalid --files value '" << files_opt << "'\n";
return 2;
}
if (!Void::Str::to_int(jobs_opt, parsed_jobs) || parsed_jobs <= 0) {
std::cerr << "vbs_benchmarks: invalid --jobs value '" << jobs_opt << "'\n";
return 2;
}
if (!Void::Str::to_int(files_opt, parsed_files) || parsed_files <= 0) {
std::cerr << "vbs_benchmarks: invalid --files value '" << files_opt << "'\n";
return 2;
}
if (!Void::Str::to_int(jobs_opt, parsed_jobs) || parsed_jobs <= 0) {
std::cerr << "vbs_benchmarks: invalid --jobs value '" << jobs_opt << "'\n";
return 2;
}
const auto file_count = static_cast<std::size_t>(parsed_files);
+107 -9
View File
@@ -1,20 +1,118 @@
#include "build-support/Defaults.hpp"
void build(Void::Build::Project &project) {
const auto &ctx = project.context();
auto library = project.dependency("VoidLibrary");
library
.git("https://git.faumaray.com/Void/VoidLibrary.git",
Void::Build::Commit{"9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5"})
.cmake({{"VOID_ENABLED_MODULES", "Configuration;Testing"},
{"VOID_ENABLE_TESTING", false},
{"VOID_ENABLE_BENCHMARKS", false},
{"BUILD_SHARED_LIBS", false}});
Void::Build::Commit{"3e254055e081a104f08df68dde39711bc7813518"})
.cmake(
{{"VOID_ENABLED_MODULES", "Configuration;Text;Unicode;Async;Algorithms;Crypto;Archive"},
{"VOID_ENABLE_TESTING", false},
{"VOID_ENABLE_BENCHMARKS", false},
{"VOID_FETCH_SQLITE3", false},
{"BUILD_SHARED_LIBS", false}});
auto sdk = project.static_library("VoidBuildSdk");
sdk.sources({"src/Build.cpp"}).include_directory("include", Void::Build::Visibility::Public);
BuildSupport::compiler_warnings(sdk, project.context());
sdk.cxx_standard(Void::Build::CxxStandard::Cxx26)
.sources({"src/Build.cpp", "src/Util/Json.cpp"})
.include_directory("include", Void::Build::Visibility::Public);
BuildSupport::compiler_warnings(sdk, ctx);
if (ctx.compiler == Void::Build::CompilerFamily::Gcc) {
sdk.compile_option("-freflection", Void::Build::Visibility::Public);
}
auto core = project.static_library("VoidBuildCore");
core.cxx_standard(Void::Build::CxxStandard::Cxx26)
.sources({
"src/Util/Sha256.cpp",
"src/Platform/FileOps.cpp",
"src/Platform/ProcessSupervisor.cpp",
"src/Toolchain/Driver.cpp",
"src/Snapshot/Snapshot.cpp",
"src/State/StateStore.cpp",
"src/Graph/Graph.cpp",
"src/Execution/Scheduler.cpp",
"src/Config/Frontend.cpp",
"src/Editor/CompDb.cpp",
"src/Watch/Watcher.cpp",
"src/Package/Toml.cpp",
"src/Package/Solver.cpp",
"src/Package/Lockfile.cpp",
"src/Package/Archive.cpp",
"src/Package/Fetch.cpp",
"src/Package/RegistryClient.cpp",
"src/Provider/Provider.cpp",
"src/Install/Installer.cpp",
"src/Bridge/CMakeBridge.cpp",
"src/Modules/ModuleScanner.cpp",
"src/SelfHost/TestRegistryGen.cpp",
"recipes/VoidLibrary/VoidLibraryRecipe.cpp",
"recipes/SelfHost/VbsSelfHostRecipe.cpp",
})
.include_directory("include", Void::Build::Visibility::Public)
.include_directory("recipes", Void::Build::Visibility::Public)
.define("VBS_HAS_VOID_CRYPTO=1", Void::Build::Visibility::Public)
.define("VBS_HAS_VOID_ARCHIVE=1", Void::Build::Visibility::Public)
.link(sdk, Void::Build::Visibility::Public)
.link(library.target("Void::Configuration"), Void::Build::Visibility::Public)
.link(library.target("Void::Text"), Void::Build::Visibility::Public)
.link(library.target("Void::Unicode"), Void::Build::Visibility::Public)
.link(library.target("Void::Async"), Void::Build::Visibility::Public)
.link(library.target("Void::Algorithms"), Void::Build::Visibility::Public)
.link(library.target("Void::Crypto"), Void::Build::Visibility::Public)
.link(library.target("Void::Archive"), Void::Build::Visibility::Public);
BuildSupport::compiler_warnings(core, ctx);
// Generate profile-isolated BootstrapConfig.hpp inside $GEN/include/Void/Build/.
const std::string gen_script =
"mkdir -p \"$GEN/include/Void/Build\" && cat > "
"\"$GEN/include/Void/Build/BootstrapConfig.hpp\" "
"<<'EOF'\n"
"#pragma once\n"
"#include <string_view>\n"
"namespace Void::Build::Bootstrap {\n"
"inline constexpr std::string_view version = \"0.1.0\";\n"
"inline constexpr std::string_view os = \"" +
ctx.os +
"\";\n"
"inline constexpr std::string_view architecture = \"" +
ctx.architecture +
"\";\n"
"inline constexpr std::string_view source_dir = \"$PROJECT_ROOT\";\n"
"inline constexpr std::string_view binary_dir = \"$BUILD_DIR\";\n"
"inline constexpr std::string_view sdk_include_dir = \"$PROJECT_ROOT/include\";\n"
"inline constexpr std::string_view sdk_source_dir = \"$PROJECT_ROOT/src\";\n"
"}\n"
"EOF\n";
auto bootstrap_cfg = project.custom_action("GenerateBootstrapConfig");
bootstrap_cfg.command({"/bin/sh", "-c", gen_script})
.outputs({"include/Void/Build/BootstrapConfig.hpp"});
auto cli = project.executable("vbs");
cli.sources({"src/Main.cpp"}).link(sdk).link(library.target("Void::Configuration"));
BuildSupport::compiler_warnings(cli, project.context());
cli.cxx_standard(Void::Build::CxxStandard::Cxx26)
.sources({"src/Main.cpp"})
.depends_on(bootstrap_cfg)
.include_directory("$GEN/include", Void::Build::Visibility::Private)
.link(core)
.install("bin");
BuildSupport::compiler_warnings(cli, ctx);
auto registry_lib = project.static_library("VoidBuildRegistry");
registry_lib.cxx_standard(Void::Build::CxxStandard::Cxx26)
.sources({"registry/service/HttpServer.cpp", "registry/service/RegistryService.cpp"})
.include_directory("registry/include", Void::Build::Visibility::Public)
.link(core, Void::Build::Visibility::Public);
BuildSupport::compiler_warnings(registry_lib, ctx);
auto registry_cli = project.executable("vbs-registry");
registry_cli.cxx_standard(Void::Build::CxxStandard::Cxx26)
.sources({"registry/service/Main.cpp"})
.depends_on(bootstrap_cfg)
.include_directory("$GEN/include", Void::Build::Visibility::Private)
.link(registry_lib)
.install("bin");
BuildSupport::compiler_warnings(registry_cli, ctx);
}
+4 -19
View File
@@ -5,13 +5,14 @@ function(vbs_add_void_dependency)
set(VOID_ENABLE_TESTING OFF)
set(VOID_ENABLE_BENCHMARKS OFF)
set(BUILD_SHARED_LIBS OFF)
set(VOID_ENABLED_MODULES Configuration Text Unicode Async Algorithms)
set(VOID_FETCH_SQLITE3 OFF)
set(VOID_ENABLED_MODULES Configuration Text Unicode Async Algorithms Crypto Archive)
if(VBS_BUILD_TESTS)
list(APPEND VOID_ENABLED_MODULES Testing)
endif()
# Opportunistically enable VoidLibrary modules backed by optional system packages
# when those packages are present in the active toolchain environment.
# Crypto (VL-007) and Archive (VL-006) now work with zero external dependencies in VoidLibrary;
# Sqlite remains opportunistic when system SQLite3 is installed.
find_package(SQLite3 QUIET)
if(SQLite3_FOUND)
list(APPEND VOID_ENABLED_MODULES Sqlite)
@@ -20,22 +21,6 @@ function(vbs_add_void_dependency)
set(VBS_HAS_VOID_SQLITE OFF PARENT_SCOPE)
endif()
find_package(OpenSSL QUIET)
if(OpenSSL_FOUND)
list(APPEND VOID_ENABLED_MODULES Crypto)
set(VBS_HAS_VOID_CRYPTO ON PARENT_SCOPE)
else()
set(VBS_HAS_VOID_CRYPTO OFF PARENT_SCOPE)
endif()
find_package(LibArchive QUIET)
if(LibArchive_FOUND)
list(APPEND VOID_ENABLED_MODULES Archive)
set(VBS_HAS_VOID_ARCHIVE ON PARENT_SCOPE)
else()
set(VBS_HAS_VOID_ARCHIVE OFF PARENT_SCOPE)
endif()
if(VBS_VOID_SOURCE_DIR)
get_filename_component(_vbs_void_source "${VBS_VOID_SOURCE_DIR}" ABSOLUTE
BASE_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
+33 -249
View File
@@ -1,259 +1,43 @@
# VoidLibrary Upstream Feature Requests
Pinned baseline inspected: `9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5`.
Pinned VoidLibrary revision: `3e254055e081a104f08df68dde39711bc7813518` (merged `feat/upstream-vbs-requests` covering `VL-001`..`VL-013`; upgraded from `9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5`).
This ledger tracks reusable, non-build-system-specific capabilities needed by
VoidBuildSystem that are absent, incomplete, or tightly bound to external
system libraries in the pinned VoidLibrary revision. Until a dedicated
VoidLibrary worker implements these items and the pin is updated, VBS keeps
swappable local adapters behind clean internal interfaces.
## Status Summary
| ID | Capability | Upstream Status (`3e254055...`) | VBS Adoption Status |
| --- | --- | --- | --- |
| `VL-001` | Process group supervision (`Void::Process::spawn`, `communicate_blocking`, `enable_subreaper`) | Implemented | **Adopted** (`src/Platform/ProcessSupervisor.cpp`) |
| `VL-002` | TOML 1.0 parser & serializer (`Void::Data::Toml`) | Implemented | **Adopted** (`src/Package/Toml.cpp`) |
| `VL-003` | Kernel `inotify` recursive directory watcher (`Void::FileSystem::DirectoryWatcher`) | Implemented | **Adopted** (`src/Watch/Watcher.cpp`, `include/Void/Build/Watch/Watcher.hpp`) |
| `VL-004` | Concrete HTTP/1.1 server (`Void::Net::HttpServer`) | Implemented (requires Boost + OpenSSL) | Local loopback POSIX adapter retained for minimal `dev cpp-gcc` (no Boost/OpenSSL) |
| `VL-005` | Streaming HTTP client & TLS default (`Void::Net::HttpClient`) | Implemented (requires Boost + OpenSSL) | Local loopback POSIX + `curl` adapter retained for minimal `dev cpp-gcc` (no Boost/OpenSSL) |
| `VL-006` | Deterministic archive creation & safe staged extraction (`Void::Archive::create`, `extract_staged`) | Implemented (zero external deps for `.tar`) | **Adopted** (`src/Package/Archive.cpp`, always linked via `Void::Archive`) |
| `VL-007` | Zero-dependency built-in SHA-256 / BLAKE2b (`Void::Crypto::Hasher`) | Implemented (zero external deps when OpenSSL absent) | **Adopted** (`include/Void/Build/Util/Sha256.hpp`, `src/Util/Sha256.cpp`, always linked via `Void::Crypto`) |
| `VL-008` | Strict UTF-8 validation (`Void::Json::Strict`, `Void::Unicode::validate_utf8`) | Implemented | **Adopted** (`src/Util/Json.cpp`, `Void::Json::Strict` throughout) |
| `VL-009` | Native non-CMake `Void::Testing` registration API | Implemented | **Adopted** (supported alongside `vbs gen-tests` in `src/SelfHost/TestRegistryGen.cpp`) |
| `VL-010` | Advisory `FileLock`, `reflink_copy_file`, `set_canonical_mtime`, `atomic_symlink_swap` (`Void::FileSystem`) | Implemented | **Adopted** (`include/Void/Build/Platform/FileOps.hpp`, `src/Platform/FileOps.cpp`) |
| `VL-011a` | Subcommands, `option_many`, `positional_many`, `ParseOutcome::Help` (`Void::Argparse::Parser`) | Implemented | **Adopted** (`src/Main.cpp`, `src/Describe.cpp`, `registry/service/Main.cpp`, `benchmarks/EngineBenchmarks.cpp` — 100% auto-generated help) |
| `VL-011b` | Optional SQLite3 FetchContent (`Void::Sqlite`) | Implemented (`VOID_FETCH_SQLITE3`) | Opportunistic when system `SQLite3` is installed (`VOID_FETCH_SQLITE3=OFF` to keep offline configures fast); journaled atomic CAS store retained |
| `VL-012` | Naming consistency observation | Noted | VBS strictly uses `Void::Build`, `PascalCase` types/enums/paths, `snake_case` functions/methods |
| `VL-013` | Shorthand SemVer ranges (`^1.0`, `~1.2`, `>=1.2 <2`) in `Void::Semver::parse_range` | Implemented | **Adopted** (`src/Package/Solver.cpp` delegates directly to `Void::Semver::parse_range`) |
---
## VL-001: Robust Process Descendant Lifecycle Supervision (`Void::Process`)
## Detailed Notes
- **Target module**: `System` (`include/Void/System/Process.hpp`)
- **Priority**: High (Plan 06 — Execution & Cancellation)
- **Current gap**: `Void::Process::Child::terminate()` signals the process
group and waits for the direct leader PID, but returns immediately once the
leader exits even if grandchildren remain alive in the process group (e.g.
ignoring `SIGTERM`).
- **Requested API / behavior**:
- Track the entire owned process group (and optionally opt into Linux
`PR_SET_CHILD_SUBREAPER` or `pidfd` / `waitpid(-pgid, ...)` draining).
- `Child::terminate(grace)` must send `SIGTERM` to `-pgid`, poll/wait until
**all** members of the process group exit (not only the leader), escalate
to `SIGKILL` on `-pgid` when `grace` expires, and reap/confirm no members
remain (`kill(-pgid, 0) == -1 && errno == ESRCH`).
- **Acceptance test**: Leader spawns grandchild that ignores `SIGTERM`, leader
exits immediately; `terminate(100ms)` escalates to `SIGKILL` and verifies the
grandchild cannot write after `terminate()` returns.
- **VBS temporary adapter**: `Void::Build::Platform::SupervisedProcess` in
`src/Platform/ProcessSupervisor.cpp`.
### Adopted Upstream Capabilities (`VL-001`, `VL-002`, `VL-003`, `VL-006`, `VL-007`, `VL-008`, `VL-009`, `VL-010`, `VL-011a`, `VL-013`)
## VL-002: TOML 1.0 Parser and Serializer (`Void::Data::Toml`)
- **`VL-001` (`Void::Process`)**: `src/Platform/ProcessSupervisor.cpp` delegates process spawning, pipe multiplexing, timeouts, cancellation, `PR_SET_CHILD_SUBREAPER`, and `-pgid` `SIGTERM -> SIGKILL` termination to `Void::Process::spawn`, `Void::Process::communicate_blocking`, and `Void::Process::enable_subreaper`, adding post-leader process-group drain supervision for detached grandchildren with redirected stdio.
- **`VL-002` (`Void::Data::Toml`)**: `src/Package/Toml.cpp` delegates all TOML 1.0 parsing and canonical table serialization to `Void::Data::Toml::parse` and `Void::Data::Toml::serialize_table`.
- **`VL-003` (`Void::FileSystem::DirectoryWatcher`)**: `src/Watch/Watcher.cpp` wraps `Void::FileSystem::DirectoryWatcher` for recursive Linux `inotify` observation, ignore predicates, and `RescanRequired` overflow handling.
- **`VL-006` (`Void::Archive`)**: `CMakeLists.txt`, `cmake/VoidDependency.cmake`, `recipes/VoidLibrary/VoidLibraryRecipe.cpp`, and `recipes/SelfHost/VbsSelfHostRecipe.cpp` unconditionally enable `Void::Archive` (`VOID_ARCHIVE_HAS_LIBARCHIVE=0` built-in USTAR/PAX tar), and `src/Package/Archive.cpp` delegates archive creation and staged security-checked extraction to `Void::Archive::create` and `Void::Archive::extract_staged` + `StagedTree::publish`.
- **`VL-007` (`Void::Crypto`)**: `Void::Crypto` (`VOID_CRYPTO_HAS_OPENSSL=0` built-in FIPS 180-4 SHA-256) is unconditionally linked, and `src/Util/Sha256.cpp` delegates directly to `Void::Crypto::Hasher`, `Void::Crypto::sha256`, and `Void::Crypto::sha256_file`.
- **`VL-008` (`Void::Json::Strict` / `Void::Unicode`)**: Strict UTF-8 validation is active across `Void::Json::Strict` and `src/Util/Json.cpp`.
- **`VL-010` (`Void::FileSystem`)**: `src/Platform/FileOps.cpp` delegates `FileLock`, `copy_isolated`, `set_canonical_mtime`, and `atomic_swap_symlink` directly to `Void::FileSystem::FileLock`, `reflink_copy_file`, `set_canonical_mtime`, and `atomic_symlink_swap`.
- **`VL-011a` (`Void::Argparse::Parser`)**: Every VBS executable (`vbs`, `vbs-registry`, `vbs_describe`, `vbs_benchmarks`) uses `Void::Argparse::Parser::parse_detailed()` with native `subcommand()`, `option_many()`, `positional_many()`, and `require_subcommand()` — eliminating all custom help strings, manual `--help` checks, and manual repeatable-argument slicing.
- **`VL-013` (`Void::Semver::parse_range`)**: `src/Package/Solver.cpp` calls `Void::Semver::parse_range()` directly without local range normalization.
- **Target module**: `Data` (`include/Void/Data/Toml.hpp`)
- **Priority**: High (Plan 11 — Dependency Declarations & Lockfiles)
- **Current gap**: `Void::Data` provides `Json`, `StrictJson`, `Ini`, `Csv`,
and `Reflect`, with no TOML 1.0 parser/serializer.
- **Requested API / behavior**:
- Full TOML 1.0 parser returning `Void::Result::Result<Document, ParseError>`
with line/column source locations (`Origin{line, column}`) on every node
and error.
- Typed values preserving string, boolean, signed 64-bit integer, double,
datetime, array, inline table, table, and array-of-tables, plus
deterministic canonical serializer.
- **Acceptance test**: Round-trip TOML 1.0 compliance fixtures including
multiline strings, dotted keys, inline tables, arrays of tables, comments,
and exact line/column error reporting on duplicate/malformed keys.
- **VBS temporary adapter**: `Void::Build::Package::Toml` in
`src/Package/Toml.cpp`.
### Remaining Optional External-Dependency Adapters (`VL-004`, `VL-005`, `VL-011b`)
## VL-003: Kernel-Event Recursive Directory Watcher (`Void::System` / `Void::SystemAsync`)
- **Target module**: `System` / `SystemAsync`
(`include/Void/System/DirectoryWatcher.hpp` or extension to `AsyncWatcher.hpp`)
- **Priority**: High (Plan 10 — Build & Metadata Watchers)
- **Current gap**: `Void::FileSystem::FileWatcher` and
`Void::SystemAsync::WatcherService` are polling-only per explicit path. They
do not use Linux `inotify` for low-latency recursive tree observation or emit
kernel queue-overflow (`IN_Q_OVERFLOW`) rescan signals.
- **Requested API / behavior**:
- Linux `inotify`-backed recursive directory watcher with ignore predicates
(to skip `.git`, `build/`, etc.), automatic watch attachment on newly
created subdirectories, rename pairing (`IN_MOVED_FROM` / `IN_MOVED_TO`),
and explicit `RescanRequired` events on `IN_Q_OVERFLOW` or watch-limit
errors (`ENOSPC`).
- **Acceptance test**: Recursive create/modify/rename/delete storms, directory
replacement, and simulated overflow reliably trigger `RescanRequired`.
- **VBS temporary adapter**: `Void::Build::Watch::InotifyWatcher` in
`src/Watch/Watcher.cpp`.
## VL-004: Concrete HTTP/1.1 Server Transport (`Void::Net::HttpServer`)
- **Target module**: `Net` (`include/Void/Net/HttpServer.hpp`)
- **Priority**: High (Plan 16 & 17 — Hosted Registry Service & Web UI)
- **Current gap**: `Void::Net::Server.hpp` provides transport-neutral `Router`,
`StaticFileResolver`, and `WebSocketSessions`, while `Void::Net::Socket.hpp`
only provides `UdpSocket`. There is no concrete TCP/HTTP server listener.
- **Requested API / behavior**:
- Concrete loopback/configurable TCP HTTP/1.1 server dispatching through
`Void::Net::Router`, supporting ephemeral port binding (`port == 0` with
`bound_port()` query), configurable header/body size limits, graceful
shutdown, and streaming request/response bodies to/from files.
- **Acceptance test**: Ephemeral-port loopback server handling concurrent
GET/PUT/POST/DELETE requests, oversized body rejection (413), and clean
shutdown without dangling sockets.
- **VBS temporary adapter**: `Void::Build::Registry::HttpServer` in
`registry/service/HttpServer.cpp`.
## VL-005: Streaming HTTP Client & Secure TLS Default (`Void::Net::HttpClient`)
- **Target module**: `Net` (`include/Void/Net/Http.hpp`)
- **Priority**: Medium (Plan 12 — Package Fetching)
- **Current gap**: `HttpClient::send()` buffers the entire response body in
`std::string` and defaults `m_verify_tls = false`.
- **Requested API / behavior**:
- Add streaming download-to-file (`download_to_file`) and streaming
upload-from-file (`upload_file`) with byte quotas, cancellation
(`std::stop_token`), and incremental digest/progress callbacks.
- Provide a secure constructor/preset with TLS certificate verification
enabled by default and explicit redaction of `Authorization` headers in
diagnostics.
- **Acceptance test**: Streaming multi-megabyte transfer with quota overflow
abort and TLS verification check.
- **VBS temporary adapter**: `Void::Build::Package::HttpTransfer` in
`src/Package/Fetch.cpp`.
## VL-006: Archive Creation and Multi-Format Support (`Void::Archive`)
- **Target module**: `Archive` (`include/Void/Archive/Archive.hpp`)
- **Priority**: Medium (Plan 12 & 15 — Source/Binary Packaging)
- **Current gap**: `Void::Archive` currently exposes only `extract()` for
`tar`/`tar.zst` and requires external `LibArchive::LibArchive`. There is no
archive creation API (`create()`), nor pure-C++ USTAR/PAX tar fallback.
- **Requested API / behavior**:
- Add deterministic `Void::Archive::create()` accepting sorted entries,
canonical mtime/uid/gid/mode metadata (for reproducible archives), and
safe extraction for `.tar`, `.tar.gz`, `.tar.zst`.
- **Acceptance test**: Deterministic archive creation (byte-identical across
runs with fixed epoch), round-trip extraction, and traversal/symlink-escape
rejection.
- **VBS temporary adapter**: `Void::Build::Package::TarArchive` (pure-C++
deterministic PAX/USTAR tar reader/writer + optional gzip/zstd piping) in
`src/Package/Archive.cpp`.
## VL-007: Zero-Dependency Built-In SHA-256 / BLAKE2b Fallback (`Void::Crypto`)
- **Target module**: `Crypto` (`include/Void/Crypto/Crypto.hpp`)
- **Priority**: Medium (Plan 05, 07, 11, 12, 16)
- **Current gap**: `Void::Crypto` requires external `OpenSSL::Crypto`, which is
not installed in minimal C++ toolchain environments such as `dev cpp-gcc`.
- **Requested API / behavior**:
- Support a built-in pure-C++ FIPS 180-4 SHA-256 (and SHA-512) implementation
in `Void::Crypto` when OpenSSL is absent (or as a lightweight
`Void::CryptoHash` module without external dependencies), keeping the exact
`Void::Crypto::Hasher` API.
- **Acceptance test**: NIST CAVP SHA-256 vectors + streaming file hashing
compile and pass with zero external crypto packages.
- **VBS temporary adapter**: `Void::Build::Util::Sha256Hasher` in
`src/Util/Sha256.cpp` (with compile-time switch to `Void::Crypto::Hasher`
when `VBS_HAS_VOID_CRYPTO` is enabled).
## VL-008: Strict UTF-8 Validation in `Void::Json::Strict` (`Void::Data`)
- **Target module**: `Data` (`include/Void/Data/StrictJson.hpp`)
- **Priority**: Medium (Observed in V-002 review)
- **Current gap**: `Void::Json::Strict::parse()` accepts raw invalid UTF-8
bytes (e.g. `0xff`, overlong sequences, UTF-8 encoded surrogates) inside JSON
strings instead of rejecting them per RFC 8259.
- **Requested API / behavior**:
- Validate every UTF-8 byte sequence in JSON strings and object keys during
both `parse()` and serialization (reusing `Void::Unicode::is_scalar_value`
/ UTF-8 validation).
- **Acceptance test**: Reject stray continuation bytes, overlong encodings,
surrogates (`U+D800..U+DFFF`), and code points `> U+10FFFF` while preserving
all valid 1..4-byte Unicode scalars.
- **VBS temporary adapter**: `src/Util/Json.cpp` now delegates to
`Void::Unicode::validate_utf8` whenever `VBS_HAS_VOID_UNICODE` is enabled
(preserving a pure-C++ fallback for standalone SDK compilation), and
`src/Build.cpp` enforces `require_utf8()`.
## VL-009: Native Non-CMake Test Registration API (`Void::Testing`)
- **Target module**: `Testing` (`include/Void/Testing/Test.hpp`,
`cmake/VoidTestScanner.cmake`)
- **Priority**: High (Plan 18 — Strict Native Self-Hosting)
- **Current gap**: Test discovery currently relies on CMake running
`VoidTestScanner.cmake` at configure time to scan `.cpp` files and emit a
generated registration translation unit. Strict native self-hosting stages
cannot depend on CMake.
- **Requested API / behavior**:
- Provide either a first-class self-registering C++ macro/helper API in
`Void::Testing` (e.g. `VOID_TEST(suite, name)` with path-disambiguated
unique symbols avoiding basename collisions) or an officially supported
standalone C++ registration generator library/header contract.
- **Acceptance test**: Build and run a multi-file `Void::Testing` binary
purely with `g++` (zero CMake), verifying `--list`, `--filter`, and exact
nonzero test count even when two files share the same stem in different
subdirectories.
- **VBS temporary adapter**: Native C++ test registration generator in
`src/SelfHost/TestRegistryGen.cpp` (Plan 18).
## VL-010: Advisory File Locks, Atomic Symlink Swap, Reflink Copy & Canonical Timestamps (`Void::FileSystem`)
- **Target module**: `System` (`include/Void/System/Path.hpp`)
- **Priority**: Medium (Plan 05, 07, 09, 11)
- **Current gap**: `Void::FileSystem::replace_file()` covers atomic durable
regular-file replacement, but lacks:
- RAII advisory file locks (`flock` / `fcntl` shared & exclusive, blocking
and try-lock).
- Atomic symlink swap (`symlink` to temp name + `rename` + parent dir
`fsync`).
- Copy-on-write reflink copy (`ioctl(FICLONE)` with private-copy fallback,
explicitly never hardlinking).
- Canonical timestamp setter (`utimensat(..., AT_SYMLINK_NOFOLLOW)`).
- **Requested API / behavior**: Add these primitives to `Void::FileSystem` with
`Void::Result::Result` error reporting matching `replace_file()`.
- **VBS temporary adapter**: `Void::Build::Platform::FileOps` in
`src/Platform/FileOps.cpp`.
## VL-011: Embedded/Optional SQLite & Argparse Subcommands (`Void::Sqlite`, `Void::Argparse`)
- **Target modules**: `Sqlite`, `Configuration`
- **Priority**: Low–Medium (Plan 07, 10, 16)
- **Current gaps**:
1. `Void::Argparse::Parser` does not natively support subcommands
(`vbs build`, `vbs compdb use`, `vbs deps resolve`) or repeatable options
(`--target a --target b`, `--profile debug --profile release`), and
reports `--help` through the error channel.
2. `Void::Sqlite` requires system `SQLite3::SQLite3` (`find_package`) with no
optional FetchContent/amalgamation fallback when building in minimal tool
environments (`dev cpp-gcc`).
- **Requested API / behavior**:
- Add subcommand dispatch, repeatable `option_many()`, and distinct
`ParseOutcome::Help` vs `ParseOutcome::Error` in `Void::Argparse::Parser`.
- Allow optional FetchContent/amalgamation SQLite3 in
`cmake/Dependencies.cmake` (parallel to Boost) so `Void::Sqlite` works in
minimal shells.
- **VBS temporary adapter**: `src/Main.cpp`, `registry/service/Main.cpp`,
`src/Describe.cpp`, and `benchmarks/EngineBenchmarks.cpp` all delegate option
parsing and `--help` generation to `Void::Argparse::Parser` (with only thin
subcommand-dispatch and repeatable-flag extraction wrappers in `src/Main.cpp`).
`src/State/StateStore.cpp` provides a crash-safe journaled atomic-replace
backend using `Void::FileSystem::replace_file` while preserving a compile-time
`Void::Sqlite` switch when `SQLite3` is present.
## VL-012: VoidLibrary Naming Consistency Note
- **Observation**: Most VoidLibrary modules use `PascalCase` enums
(`Void::Crypto::HashAlgorithm::Sha256`, `Void::Sqlite::OpenMode::ReadOnly`,
`Void::Net::Method::Get`, `Void::Security::PasswordHashStrength::Moderate`)
and `snake_case` functions/methods. A few headers mix styles
(`Void::Crypto::sha256File` camelCase vs `Void::Security::hash_password`
snake_case; `Void::Process::EnvMode::inherit` snake_case vs
`Void::Sqlite::OpenMode::ReadOnly` PascalCase). VoidBuildSystem standardizes
strictly on `Void::Build` (`PascalCase` types/enums/filenames, `snake_case`
functions/methods) to align with the primary VoidLibrary style.
## VL-013: Shorthand SemVer Range Comparators (`Void::Semver::VersionRange`)
- **Target module**: `Text` (`include/Void/Text/Semver.hpp`)
- **Priority**: Medium (Plan 11 — Native Dependency Solver)
- **Current gap**: `Void::Semver::VersionRange::parse()` calls
`parse_strict()` on comparator/caret/tilde operands and rejects omitted minor
or patch components such as `^1`, `^1.0`, `^11.0`, `~1.2`, `>=1.2 <2`, or
`<2`. While wildcard tokens (`1.*`, `1.2.x`) are accepted, standard
Cargo/npm-style shorthand comparators fail to parse.
- **Requested API / behavior**:
- Support partial version bounds in `Void::Semver::VersionRange::parse()`:
- `^M` -> `>=M.0.0 <(M+1).0.0` (including `^0` -> `<1.0.0`)
- `^M.m` -> `^M.m.0`
- `~M` -> `>=M.0.0 <(M+1).0.0`, `~M.m` -> `~M.m.0`
- `>=M`, `>=M.m`, `<M`, `<M.m`, etc. padded to `.0` / `.0.0`.
- **Acceptance test**: `parse_range("^1.0")`, `parse_range("^11.0")`,
`parse_range("~1.2")`, `parse_range(">=1.2 <2")`, and `parse_range("<1.2.0")`
all parse cleanly and match the expected versions.
- **VBS temporary adapter**: `parse_semver_range_compat()` in
`src/Package/Solver.cpp`.
- **`VL-004` / `VL-005` (`Void::Net`)**: `Void::Net` in VoidLibrary still requires external `Boost` + `OpenSSL` (`src/Net/module.cmake`), which are absent in minimal `dev cpp-gcc`. VBS keeps its zero-dependency POSIX loopback `HttpServer` (`registry/service/HttpServer.cpp`) and `RegistryClient` (`src/Package/RegistryClient.cpp`) until a Boost-free/minimal-dependency transport is desired or available in the base toolchain.
- **`VL-011b` (`Void::Sqlite`)**: `cmake/VoidDependency.cmake` disables network fetches during CMake configure (`VOID_FETCH_SQLITE3=OFF`) and opportunistically enables `Void::Sqlite` when system `SQLite3` is installed; `src/State/StateStore.cpp` continues providing crash-safe atomic-replace CAS persistence in minimal shells.
+13 -8
View File
@@ -1,8 +1,8 @@
# Development state
Updated: 2026-11-26
Updated: 2026-11-27
Branch: main
Stage: VERIFIED — Full v1 implementation (Plans 01–19) complete, maximal VoidLibrary reuse wired, ready for commit & push
Stage: VERIFIED — Full v1 implementation (Plans 01–19) + VoidLibrary `VL-001`..`VL-013` adoption + self-building `vbs build` + live `Void::Log` progress + 100% auto-generated `Void::Argparse` CLI complete
## Completed delivery waves
@@ -16,18 +16,23 @@ Stage: VERIFIED — Full v1 implementation (Plans 01–19) complete, maximal Voi
- Implemented per-profile `compile_commands.json` projection with monotonic selection tickets, crash recovery, and unrelated root file preservation (`src/Editor/CompDb.cpp`).
- Implemented recursive Linux `inotify` watcher (`src/Watch/Watcher.cpp`) with overflow rescan and strict `MetadataOnly` boundary vs `FullBuild`.
- **Wave 3 (Plans 11–15, 18 — Packages, Foreign Providers, Bridge, Install & Self-Hosting)**:
- Implemented TOML 1.0 parser/merger (`src/Package/Toml.cpp`), PubGrub-style SemVer solver with shorthand comparator adapter (`src/Package/Solver.cpp`), context-aware atomic CAS `vbs.lock` (`src/Package/Lockfile.cpp`), deterministic PAX/USTAR `.tar` builder & safe extractor (`src/Package/Archive.cpp`), source/binary materialization (`src/Package/Fetch.cpp`).
- Implemented TOML 1.0 parser/merger (`src/Package/Toml.cpp`), PubGrub-style SemVer solver (`src/Package/Solver.cpp`), context-aware atomic CAS `vbs.lock` (`src/Package/Lockfile.cpp`), deterministic PAX/USTAR `.tar` builder & safe extractor (`src/Package/Archive.cpp`), source/binary materialization (`src/Package/Fetch.cpp`).
- Implemented CMake File API & Meson introspection providers + explicit missing-tool Conan2 adapter (`src/Provider/Provider.cpp`), `cmake/bridge/VbsDeps.cmake` + `vbs bridge` (`src/Bridge/CMakeBridge.cpp`), staged relocatable install/export/uninstall (`src/Install/Installer.cpp`), native `VoidLibrary` recipe (`recipes/VoidLibrary/VoidLibraryRecipe.cpp`), and non-CMake `Void::Testing` generator (`src/SelfHost/TestRegistryGen.cpp`).
- **Wave 4 (Plans 08, 16–17, 19 — Modern C++, Registry, Web UI, Benchmarks & CI)**:
- Implemented P1689r5 module scanning & topological collation for GCC 16 and `clang-scan-deps`, header units, and unity batching excluding modules/per-file overrides (`src/Modules/ModuleScanner.cpp`).
- Implemented `vbs-registry` HTTP/1.1 service (`registry/service/HttpServer.cpp`, `RegistryService.cpp`) with RBAC, salted password hashing, CSRF + HttpOnly SameSite cookies, immutable release 409 conflict checks, yank, redacted audit log, backup/restore, and DOM-safe web UI (`registry/web/`).
- Implemented `vbs` CLI (`src/Main.cpp`), benchmark harness (`benchmarks/EngineBenchmarks.cpp`), five `Void::Testing` executables, three CMake contract scripts, and `.github/workflows/ci.yml` template.
- **Wave 5 (Maximal VoidLibrary Reuse + Full Plan 08/11/12/16/18 Integration)**:
- Replaced manual CLI loops & help strings across `src/Main.cpp`, `registry/service/Main.cpp`, and `benchmarks/EngineBenchmarks.cpp` with `Void::Argparse::Parser` (`<Void/Configuration/Argparse.hpp>`).
- Replaced hand-rolled topological sorts, hex/URL encoding, UTF-8 validation, ASCII string helpers, scope guards, stopwatches, env lookups, and worker threads with VoidLibrary modules (`Void::Algorithms::topological_order`, `Void::Encoding::Hex`/`Url`, `Void::Unicode::validate_utf8`, `Void::Str`, `Void::Scope::on_exit`, `Void::Time::Stopwatch`, `Void::Configuration::get_env`/`get_env_or`, `Void::Concurrency::ThreadPool`).
- Adopted `Void::Algorithms::topological_order`, `Void::Encoding::Hex`/`Url`, `Void::Unicode::validate_utf8`, `Void::Str`, `Void::Scope::on_exit`, `Void::Time::Stopwatch`, `Void::Configuration::get_env`/`get_env_or`, `Void::Concurrency::ThreadPool`.
- Wired Plan 08 end-to-end into `Graph::lower_project_graph` (incompatible sanitizer rejection, unity batching, explicit `ActionKind::HeaderUnit`, GCC `-fmodule-mapper` & Clang two-step `.pcm` -> `.o` + transitive `-fmodule-file=` named modules & partitions) verified on BOTH GCC 16.2.0 and Clang 23.1.3.
- Added live HTTP/1.1 `Package::RegistryClient` (`src/Package/RegistryClient.cpp`) + `vbs publish` + live `DependencySourceKind::Package` resolution in `vbs deps` / `vbs build` verified end-to-end against `vbs-registry`.
- Added full native `recipes/SelfHost/VbsSelfHostRecipe.{hpp,cpp}` verified Stage 0 -> Stage 1 (full native `stage1/bin/vbs`, zero CMake) -> Stage 2 (`stage1/bin/vbs test` with trapped `cmake` on `PATH`).
- **Wave 6 (VoidLibrary `3e254055` Pin Bump, Upstream `VL-001`..`VL-013` Adoption, Real Self-Build, Live Logs & Generated CLI Help)**:
- Upgraded VoidLibrary pin to `3e254055e081a104f08df68dde39711bc7813518` (`Merge branch 'feat/upstream-vbs-requests' (VL-001..VL-013)`).
- Replaced local adapters with upstream VoidLibrary implementations across the board: `Void::Crypto` (`VL-007`), `Void::Archive` (`VL-006`), `Void::Data::Toml` (`VL-002`), `Void::Semver::parse_range` (`VL-013`), `Void::FileSystem::FileLock`/`reflink_copy_file`/`set_canonical_mtime`/`atomic_symlink_swap` (`VL-010`), `Void::FileSystem::DirectoryWatcher` (`VL-003`), `Void::Process::spawn`/`communicate_blocking`/`enable_subreaper` (`VL-001`), and `Void::Argparse::Parser` native subcommands + `option_many` + `parse_detailed` (`VL-011`).
- Eliminated all custom help text and manual `--help`/subcommand/repeatable-flag parsing across `src/Main.cpp`, `src/Describe.cpp`, `registry/service/Main.cpp`, and `benchmarks/EngineBenchmarks.cpp` — 100% auto-generated via `Void::Argparse::Parser`.
- Upgraded root `build.cpp` to declare the complete `VoidBuildSystem` (`VoidBuildSdk`, `VoidBuildCore`, `GenerateBootstrapConfig`, `vbs`, `VoidBuildRegistry`, `vbs-registry`), fixed snapshot root discovery (`collect_snapshot_inputs`), fixed snapshot remapping of external/build-dir dependency includes in `Graph.cpp`, fixed CMake File API provider `Void::*` alias & header-only `INTERNAL_DEPS` export + transitive link ordering in `Provider.cpp`, and verified real Stage 1 + Stage 2 self-builds of `VoidBuildSystem` via `vbs build`!
- Wired a live thread-safe `Void::Log` console sink in `src/Main.cpp` (`--verbose`/`-v`, `--quiet`/`-q`) logging every build phase (`Config`, `Toolchain`, `Eval`, `Deps`, `Fetch`, `Provider`, `Snapshot`, `Graph`, per-action `[seq/total] Compile/Archive/Link/Action ...` progress, and `Test`) with elapsed timings.
## Remaining future scope
@@ -35,6 +40,6 @@ Stage: VERIFIED — Full v1 implementation (Plans 01–19) complete, maximal Voi
## Environment notes & upstream boundaries
- External VoidLibrary pin `9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5` is preserved cleanly in [cmake/VoidDependency.cmake](../../cmake/VoidDependency.cmake), and VBS never writes to `/home/faumaray/Projects/VoidLibrary`.
- `dev cpp-gcc` lacks external `SQLite3`, `OpenSSL`, `LibArchive`, and `conan`; VBS runs verified pure-C++/POSIX adapters while keeping upstream adapters behind optional compile-time switches in `cmake/VoidDependency.cmake`.
- See [VERIFICATION.md](VERIFICATION.md) for all observed builds, tests, Clang 23 matrix runs, formatting checks, and benchmark results.
- External VoidLibrary pin `3e254055e081a104f08df68dde39711bc7813518` is set in [CMakeLists.txt](../../CMakeLists.txt), [cmake/VoidDependency.cmake](../../cmake/VoidDependency.cmake), and [build.cpp](../../build.cpp). VBS never writes to `/home/faumaray/Projects/VoidLibrary`.
- `Void::Crypto` and `Void::Archive` now build unconditionally with zero external dependencies in `dev cpp-gcc`; only `SQLite3`, `Boost`/`OpenSSL` (`Void::Net`), and `conan` remain optional external prerequisites.
- See [VERIFICATION.md](VERIFICATION.md) for all observed builds, tests, Clang 23 matrix runs, formatting checks, benchmark results, and real self-build verification.
+3 -2
View File
@@ -1,7 +1,7 @@
# Task graph and ownership
Updated: 2026-11-26
Base HEAD: `3cac890ce9b8a0681130a58601e0516231471ad8`
Updated: 2026-11-27
Base HEAD: `ab64147`
| Wave | Scope | Status | Primary Deliverables |
| --- | --- | --- | --- |
@@ -12,4 +12,5 @@ Base HEAD: `3cac890ce9b8a0681130a58601e0516231471ad8`
| Wave 3 (Plans 11–15, 18) | TOML 1.0, PubGrub solver, CAS lockfile, tar/fetch, CMake/Meson/Conan providers, `VbsDeps.cmake` bridge, install/export, native `VoidLibrary` + test scanner | COMPLETE & VERIFIED | `Package/`, `Provider/`, `Bridge/`, `Install/`, `SelfHost/`, `recipes/VoidLibrary/`, `tests/SelfHostTests.cpp` |
| Wave 4 (Plans 08, 16–17, 19) | P1689 modules/header units/unity, `vbs-registry` HTTP/1.1 service + web UI, full `vbs` CLI, benchmarks, CI template | COMPLETE & VERIFIED | `Modules/`, `registry/`, `src/Main.cpp`, `benchmarks/`, `.github/workflows/ci.yml`, `tests/RegistryTests.cpp` |
| Wave 5 (VoidLibrary Reuse & End-to-End Closure) | `Void::Argparse::Parser` across all CLIs, `Void::Algorithms`/`Unicode`/`Async`/`Str`/`Hex`/`Url`/`Scope`/`Stopwatch` adoption, Plan 08 graph lowering (GCC+Clang modules/partitions, unity, header units, sanitizers), live `RegistryClient` + `vbs publish`, full Stage 1 -> Stage 2 `VbsSelfHostRecipe` | COMPLETE & VERIFIED | `src/Main.cpp`, `src/Graph/Graph.cpp`, `src/Package/RegistryClient.cpp`, `recipes/SelfHost/VbsSelfHostRecipe.cpp`, expanded test suites |
| Wave 6 (Upstream `VL-001`..`VL-013` Pin Bump, Self-Building `vbs build`, Live Logs & Generated CLI Help) | Bump VoidLibrary pin to `3e254055e081a104f08df68dde39711bc7813518`; adopt `Void::Crypto`, `Void::Archive`, `Void::Data::Toml`, `Void::Semver::parse_range`, `Void::FileSystem::FileLock`/`DirectoryWatcher`/`reflink_copy_file`/`atomic_symlink_swap`/`set_canonical_mtime`, `Void::Process`, `Void::Argparse::Parser` subcommands + `option_many` + `parse_detailed`; full self-building root `build.cpp`; live `Void::Log` console progress | COMPLETE & VERIFIED | `CMakeLists.txt`, `cmake/VoidDependency.cmake`, `build.cpp`, `src/Main.cpp`, `src/Describe.cpp`, `registry/service/Main.cpp`, `benchmarks/EngineBenchmarks.cpp`, `src/Util/Sha256.cpp`, `src/Package/{Toml,Solver,Archive,Fetch}.cpp`, `src/Platform/{FileOps,ProcessSupervisor}.cpp`, `src/Watch/Watcher.cpp`, `src/Provider/Provider.cpp`, `src/Graph/Graph.cpp`, `src/Execution/Scheduler.cpp`, `recipes/`, updated contracts & docs |
| Future (Plan 20) | Native foreign build translation & Windows/macOS ports | PLANNED (unimplemented) | [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) |
+42 -22
View File
@@ -1,20 +1,20 @@
# Verification record
Updated: 2026-11-26
Updated: 2026-11-27
Working directory: `/home/faumaray/Projects/VoidBuildSystem`
All checks below were executed after the final C++ edits and formatting pass. Planned/non-executed items are separated explicitly under **Limits and Unrun Checks**.
## Toolchain & Dependency Integrity
- Configure baseline (`build/dev`): Ninja Debug C++26 (`-DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON`) pointing at workspace-local fetched pin `build/bootstrap-pinned/_deps/voidlibrary-src` (`modules=13`, enabling `Void::Algorithms`, `Void::Async`, `Void::Configuration`, `Void::Text`, `Void::Unicode`, `Void::Testing`, and core dependencies).
- Configure baseline (`build/dev`): Ninja Debug C++26 (`-DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON`) against clean detached checkout of VoidLibrary pin `3e254055e081a104f08df68dde39711bc7813518` (`modules=15`, enabling `Void::Algorithms`, `Void::Archive`, `Void::Async`, `Void::Configuration`, `Void::Crypto`, `Void::Text`, `Void::Unicode`, `Void::Testing`, and core dependencies with zero external crypto/archive libraries).
- Build command:
```sh
dev cpp-gcc -c cmake --build build/dev --parallel 4
```
- Exit status: `0` (all library targets `VoidBuild_Sdk`, `VoidBuild_Core`, `VoidBuild_Registry`, binaries `vbs`, `vbs-registry`, `vbs_describe`, `vbs_benchmarks`, and 5 `Void::Testing` executables compiled and linked with zero warnings in VBS-owned code; upstream `Void::Testing` headers still emit `-Wmissing-field-initializers`).
- Exit status: `0` (all library targets `VoidBuild_Sdk`, `VoidBuild_Core`, `VoidBuild_Registry`, binaries `vbs`, `vbs-registry`, `vbs_describe`, `vbs_benchmarks`, and 5 `Void::Testing` executables compiled and linked cleanly).
- Pin checks:
- `git -C build/bootstrap-pinned/_deps/voidlibrary-src rev-parse HEAD` -> `9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5` (exit `0`).
- Detached VoidLibrary checkout `HEAD` == `3e254055e081a104f08df68dde39711bc7813518` (`Merge branch 'feat/upstream-vbs-requests' (VL-001..VL-013)`).
- VBS made zero writes to `/home/faumaray/Projects/VoidLibrary`.
## Formatting Check
@@ -34,28 +34,47 @@ dev cpp-gcc -c clang-format --dry-run --Werror \
## CTest Suite Results (`dev cpp-gcc`)
```sh
dev cpp-gcc -c ctest --test-dir build/dev --verbose
dev cpp-gcc -c ctest --test-dir build/dev --output-on-failure
```
- Exit status: `0` — **8 / 8 passed (100%) in 62.92 sec**:
- Exit status: `0` — **8 / 8 passed (100%) in 85.66 sec**:
| # | CTest Name | Exact Runner Output / Scope Verified | Result | Time |
| # | CTest Name | Scope Verified | Result | Time |
| --- | --- | --- | --- | --- |
| 1 | `vbs_sdk_tests` | `17 tests: 17 ✔ in 6.5ms` (`SdkDeclarations` 14 + `ExampleContexts` 3, using `Void::Unicode::validate_utf8`) | Passed | 0.01s |
| 2 | `vbs_core_tests` | `6 tests: 6 ✔ in 11.29s`: SHA-256 NIST vectors (`Void::Encoding::Hex`), `ProcessSupervisor` exec-fail & grandchild `SIGKILL`, profile inheritance/cycles, snapshot mutation/symlinks/header-shadowing, CAS corruption/recovery/GC, end-to-end native frontend + deterministic build + `Void::Algorithms::topological_order` + `Void::Concurrency::ThreadPool` + deleted archive symbol removal | Passed | 11.30s |
| 3 | `vbs_v1_tests` | `8 tests: 8 ✔ in 11.22s`: CompDB ticket races/user-file preservation/recovery, `inotify` watcher + `MetadataOnly` boundary, TOML 1.0/PubGrub solver/CAS `vbs.lock`, PAX/USTAR `.tar` determinism/traversal/symlink rejection/binary ABI/secret redaction, real CMake & Meson providers + `VbsDeps.cmake` bridge + relocatable install + CLI `vbs install`/`vbs uninstall`, GCC 16 P1689 module scan/collation/execution + cycle/dup checks + unity exclusion, Clang check, AND full `Graph::lower_project_graph` Plan 08 integration (incompatible ASan+TSan rejection, GCC 16 module partition + primary interface + consumer, unity batching + per-file-option exclusion, explicit `ActionKind::HeaderUnit` build & import) | Passed | 11.22s |
| 4 | `vbs_registry_tests` | `2 tests: 2 ✔ in 3.06s`: (1) HTTP/1.1 loopback server, security headers (`CSP`, `X-Frame-Options: DENY`), path-traversal 403, RBAC 403/401, SHA-256 mismatch 400, tar validation 422, immutable release 409 conflict, CSRF 403 & HttpOnly SameSite=Strict session cookie, XSS-safe private UI/API, secret-free audit log, backup & restore; (2) full live CLI E2E `vbs publish` (`1.0.0` & `1.1.0`) -> `vbs deps resolve` -> `vbs build --locked` -> consumer execution against ephemeral `vbs-registry` with zero token leak in `vbs.lock` | Passed | 3.06s |
| 5 | `vbs_selfhost_tests` | `3 tests: 3 ✔ in 37.26s`: (1) basename-collision-safe native `Void::Testing` scanner (`vbs gen-tests`); (2) strict non-CMake native `VoidLibrary` + `VoidBuildSdk` + `stage1_sdk_tests` -> Stage 2 SDK consumer; (3) full Stage 0 -> Stage 1 native `VbsSelfHostRecipe` building the complete `stage1/bin/vbs` CLI binary (native `VoidLibrary` closure + `VoidBuildSdk` + `VoidBuildCore` + stage-isolated `BootstrapConfig.hpp`, zero CMake) -> Stage 2 executing `stage1/bin/vbs test` with trapped `cmake` on `PATH` | Passed | 37.27s |
| 6 | `vbs_sdk_registration` | `17 SDK test registrations verified; named JSON case executed` | Passed | 0.01s |
| 7 | `vbs_cli_contract` | `23 native CLI contracts verified` (all `Void::Argparse::Parser`-backed `vbs` commands including `vbs publish` + `vbs-registry --help`) | Passed | 0.03s |
| 8 | `vbs_description_contract` | `Four runtime profile/compiler contexts and six error contracts verified` (`debug`/`release` x `gcc`/`clang` JSON + CLI errors) | Passed | 0.02s |
| 1 | `vbs_sdk_tests` | 17 tests (`SdkDeclarations` 14 + `ExampleContexts` 3 for 6-target self-building `build.cpp` and pin `3e254055...`) | Passed | 0.01s |
| 2 | `vbs_core_tests` | 6 tests: `Void::Crypto` SHA-256 NIST vectors, `Void::Process` exec-fail & stubborn grandchild `SIGKILL`, profile inheritance/cycles, snapshot mutation/symlinks/header-shadowing (`Void::FileSystem` `reflink_copy_file`/`FileLock`/`set_canonical_mtime`), CAS recovery/GC, end-to-end native frontend + deterministic build | Passed | 11.34s |
| 3 | `vbs_v1_tests` | 8 tests: CompDB ticket races & `atomic_symlink_swap`, `Void::FileSystem::DirectoryWatcher` + `MetadataOnly` boundary, `Void::Data::Toml` + `Void::Semver::parse_range` PubGrub solver + CAS `vbs.lock`, `Void::Archive` `.tar` determinism & traversal/symlink/duplicate rejection, real CMake & Meson providers + `VbsDeps.cmake` bridge + relocatable install + CLI `vbs install`/`vbs uninstall`, GCC 16 P1689 modules + full Plan 08 graph integration (sanitizers, partitions, unity, header units) | Passed | 11.13s |
| 4 | `vbs_registry_tests` | 2 tests: `vbs-registry` HTTP/1.1 security/RBAC/CSRF/XSS/tar-422/backup-restore + full live CLI E2E `vbs publish` -> `vbs deps resolve` -> `vbs build --locked` | Passed | 3.98s |
| 5 | `vbs_selfhost_tests` | 3 tests: basename-collision-safe `vbs gen-tests`, strict non-CMake native `VoidLibrary` (including `Crypto` + `Archive`) + `VoidBuildSdk` + Stage 2, and full Stage 0 -> Stage 1 native `VbsSelfHostRecipe` (`stage1/bin/vbs`, zero CMake) -> Stage 2 `stage1/bin/vbs test` with trapped `cmake` on `PATH` | Passed | 59.12s |
| 6 | `vbs_sdk_registration` | 17 SDK test registrations verified; named JSON case executed | Passed | 0.01s |
| 7 | `vbs_cli_contract` | 27 native CLI & auto-generated `Void::Argparse::Parser` help/subcommand/error contracts verified (`vbs`, `vbs-registry`, `compdb`, `deps`, `build`, `install`, `publish`, etc.) | Passed | 0.04s |
| 8 | `vbs_description_contract` | Four runtime profile/compiler contexts (`debug`/`release` x `gcc`/`clang` for 6-target `build.cpp`), auto-generated `vbs_describe --help`, and five error contracts verified | Passed | 0.03s |
## Real Self-Build of VoidBuildSystem (`vbs build`)
### Stage 1: Bootstrap `vbs` builds complete `VoidBuildSystem` from root `build.cpp`
```sh
VBS_VOID_SOURCE_DIR=/home/faumaray/Projects/VoidBuildSystem/build/voidlibrary-pinned \
dev cpp-gcc -c build/dev/bin/vbs build --build-dir build/vbs-self --jobs 4
```
- Exit status: `0` — **`vbs: [debug] built (36 executed, 0 cached)`** in `38.79s`.
- Live progress logs verified cleanly across all phases: `[Config]`, `[Toolchain]`, `[Eval]` (`6 target(s), 1 dependenc(ies)`), `[Deps]`, `[Fetch]`, `[Provider]` (`Imported 100 target(s) from 'VoidLibrary'`), `[Snapshot]` (`70 file(s)`), `[Graph]` (`36 action(s)`), and per-action `[ 1/36] Action GenerateBootstrapConfig` .. `[35/36] Link build/vbs-self/profiles/debug/out/bin/vbs` & `[36/36] Link build/vbs-self/profiles/debug/out/bin/vbs-registry`.
### Stage 2: Self-built `vbs` verifies cached build & auto-generated CLI
```sh
VBS_VOID_SOURCE_DIR=/home/faumaray/Projects/VoidBuildSystem/build/voidlibrary-pinned \
dev cpp-gcc -c build/vbs-self/profiles/debug/out/bin/vbs build --build-dir build/vbs-self --jobs 4
build/vbs-self/profiles/debug/out/bin/vbs --version
build/vbs-self/profiles/debug/out/bin/vbs --help
```
- Exit status: `0` — **`vbs: [debug] built (0 executed, 36 cached)`**, `vbs 0.1.0`, and full auto-generated `Void::Argparse::Parser` root help output (`Usage: vbs [--version] [--verbose] [--quiet] <command>`).
## Clang 23.1.3 Target Matrix (`dev cpp`)
```sh
dev cpp -c build/dev/bin/vbs_v1_tests --no-color --filter clang23
```
- Exit status: `0` — `1 tests: 1 ✔ in 751.7ms` (`clang23_target_toolchain_and_p1689_module_scan`).
- Verified inside `dev cpp`: `Toolchain::discover_and_probe` discovers Clang 23.1.3 + `clang-scan-deps`, compiles/links/runs a `#ifdef __clang__` C++20 binary, AND executes a full `Graph::lower_project_graph` + `Execution::execute_graph` build of a module partition (`vbs.clangcalc:part`) + primary interface (`vbs.clangcalc`) + consumer `main.cpp` using `clang-scan-deps --format=p1689`, two-step `--precompile` `.pcm` (`ActionKind::ModuleBmi`) -> `.o` with transitive `-fmodule-file=`, linking, and exit code 0!
- Exit status: `0` — `1 tests: 1 ✔ in 745.2ms` (`clang23_target_toolchain_and_p1689_module_scan`).
- Verified inside `dev cpp`: Clang 23.1.3 + `clang-scan-deps` target probing, C++20 compilation, and full `Graph::lower_project_graph` + `Execution::execute_graph` build of module partition (`vbs.clangcalc:part`) + primary interface (`vbs.clangcalc`) + consumer `main.cpp` using two-step `--precompile` `.pcm` -> `.o` with transitive `-fmodule-file=`.
## Benchmarks (`dev cpp-gcc`)
@@ -64,12 +83,13 @@ dev cpp-gcc -c build/dev/bin/vbs_benchmarks --files 15
```
- Exit status: `0`:
```json
{"fixture_files":16,"compiler":"g++ (GCC) 16.2.0","snapshot_ms":18,"cold_build_ms":349,"cold_executed":17,"warm_noop_ms":11,"warm_executed":0,"warm_cached":17}
{"fixture_files":16,"compiler":"g++ (GCC) 16.2.0","snapshot_ms":17,"cold_build_ms":350,"cold_executed":17,"warm_noop_ms":16,"warm_executed":0,"warm_cached":17}
```
## Limits and Unrun Checks
1. **Conan2 live installation**: `conan` is absent in `dev cpp-gcc`; automated testing verified that `Provider::resolve_foreign_provider` fails explicitly with a missing-prerequisite error when `conan` is absent (`FullV1Tests.cpp`).
2. **External optional VoidLibrary modules**: `SQLite3`, `OpenSSL`, `LibArchive`, and `libsodium` are not present in `dev cpp-gcc`, so VBS built and tested its pure-C++/POSIX adapters (`StateStore`, `Sha256Hasher`, `TarArchive`, `HttpServer`, `RegistryClient`); the optional CMake switches (`VBS_HAS_VOID_SQLITE`, `VBS_HAS_VOID_CRYPTO`, `VBS_HAS_VOID_ARCHIVE`) remain ready for environments providing them.
3. **CI workflow & Web UI browser**: [.github/workflows/ci.yml](../../.github/workflows/ci.yml) has not been executed on remote GitHub Actions runners, and `registry/web/` was verified via HTTP/header/static-serving/API/XSS/CSRF tests without a headless browser runner.
4. **Plan 20 ([20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Native foreign graph translation and non-Linux OS ports (Windows/macOS) remain unimplemented planned scope.
1. **HTTPS git fetch in proxy-restricted environment**: Inside this execution environment, outbound HTTPS to `https://git.faumaray.com/Void/VoidLibrary.git` encountered `Proxy CONNECT aborted`; CMake configure and `vbs build` were therefore verified against a clean local detached checkout of the exact pinned commit `3e254055e081a104f08df68dde39711bc7813518` via `VBS_VOID_SOURCE_DIR`.
2. **Conan2 live installation**: `conan` is absent in `dev cpp-gcc`; automated testing verified explicit missing-prerequisite failure (`FullV1Tests.cpp`).
3. **Optional external VoidLibrary modules (`Void::Net`, `Void::Sqlite`)**: `Boost`, `OpenSSL`, and `SQLite3` are not installed in `dev cpp-gcc`, so VBS continues using its pure-C++/POSIX loopback HTTP adapters (`HttpServer`, `RegistryClient`) and journaled atomic CAS store (`StateStore`), while retaining optional `Void::Sqlite` CMake detection.
4. **CI workflow & Web UI browser**: [.github/workflows/ci.yml](../../.github/workflows/ci.yml) has not been executed on remote GitHub Actions runners, and `registry/web/` was verified via HTTP/header/static-serving/API/XSS/CSRF tests without a headless browser runner.
5. **Plan 20 ([20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Native foreign graph translation and non-Linux OS ports (Windows/macOS) remain unimplemented planned scope.
@@ -35,8 +35,10 @@ struct ExecutionEvent {
Kind kind{Kind::ActionStarted};
std::string action_id;
std::string target_name;
std::string label;
std::size_t completed{0};
std::size_t total{0};
std::chrono::milliseconds elapsed{0};
std::string message;
};
+12 -11
View File
@@ -2,6 +2,7 @@
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/System/Path.hpp>
#include <cstdint>
#include <filesystem>
@@ -15,27 +16,27 @@ namespace Void::Build::Platform {
enum class LockMode { Shared, Exclusive };
// RAII advisory flock lock (VL-010).
// RAII advisory flock lock delegating directly to Void::FileSystem::FileLock (VL-010).
class FileLock {
public:
FileLock() noexcept = default;
~FileLock() noexcept;
~FileLock() noexcept = default;
FileLock(const FileLock &) = delete;
FileLock &operator=(const FileLock &) = delete;
FileLock(FileLock &&other) noexcept;
FileLock &operator=(FileLock &&other) noexcept;
FileLock(FileLock &&other) noexcept = default;
FileLock &operator=(FileLock &&other) noexcept = default;
[[nodiscard]] static Void::Result::Result<FileLock, Void::Result::Error>
acquire(const std::filesystem::path &lock_path, LockMode mode = LockMode::Exclusive,
bool non_blocking = false);
[[nodiscard]] bool valid() const noexcept { return fd_ >= 0; }
void release() noexcept;
[[nodiscard]] bool valid() const noexcept { return lock_.locked(); }
void release() noexcept { lock_.unlock(); }
private:
explicit FileLock(int fd) noexcept : fd_{fd} {}
int fd_{-1};
explicit FileLock(Void::FileSystem::FileLock lock) noexcept : lock_{std::move(lock)} {}
Void::FileSystem::FileLock lock_;
};
struct FileMetadata {
@@ -57,13 +58,13 @@ struct FileMetadata {
[[nodiscard]] Void::Result::Result<FileMetadata, Void::Result::Error>
stat_lstat(const std::filesystem::path &path);
// Private isolated file copy: tries Linux FICLONE reflink, falls back to byte copy.
// Private isolated file copy delegating to Void::FileSystem::reflink_copy_file (VL-010).
// NEVER creates hardlinks. Guarantees distinct inode and nlink == 1 on destination.
[[nodiscard]] 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 = std::nullopt);
// Canonicalizes mtime/atime via utimensat(..., AT_SYMLINK_NOFOLLOW).
// Canonicalizes mtime/atime via Void::FileSystem::set_canonical_mtime (VL-010).
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
set_canonical_mtime(const std::filesystem::path &path, std::int64_t epoch_seconds);
@@ -75,7 +76,7 @@ atomic_write_file(const std::filesystem::path &path, std::string_view content,
atomic_write_bytes(const std::filesystem::path &path, std::span<const std::byte> bytes,
bool durable_sync = true, unsigned mode = 0644);
// Atomically replaces symlink at `link_path` pointing to `target` + parent fsync.
// Atomically replaces symlink via Void::FileSystem::atomic_symlink_swap (VL-010).
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
atomic_swap_symlink(const std::filesystem::path &link_path, const std::filesystem::path &target);
+6 -9
View File
@@ -1,5 +1,6 @@
#pragma once
#include <Void/Crypto/Crypto.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
@@ -7,6 +8,7 @@
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <optional>
#include <span>
#include <string>
#include <string_view>
@@ -15,11 +17,10 @@ namespace Void::Build::Util {
using Sha256Digest = std::array<std::uint8_t, 32>;
// Streaming FIPS 180-4 SHA-256 hasher (VL-007: delegates to Void::Crypto when
// OpenSSL is available; provides zero-dependency built-in fallback otherwise).
// Streaming FIPS 180-4 SHA-256 hasher backed directly by Void::Crypto::Hasher (VL-007).
class Sha256Hasher {
public:
Sha256Hasher() noexcept;
Sha256Hasher();
void update(std::span<const std::byte> data) noexcept;
void update(std::span<const std::uint8_t> data) noexcept;
@@ -31,12 +32,8 @@ class Sha256Hasher {
[[nodiscard]] std::string finalize_hex() noexcept;
private:
void transform(const std::uint8_t block[64]) noexcept;
std::uint32_t state_[8];
std::uint64_t bit_count_{0};
std::uint8_t buffer_[64]{};
std::size_t buffer_len_{0};
std::optional<Void::Crypto::Hasher> hasher_;
Sha256Digest cached_digest_{};
bool finalized_{false};
};
+10 -15
View File
@@ -8,6 +8,7 @@
#include <Void/Build/State/StateStore.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/System/DirectoryWatcher.hpp>
#include <chrono>
#include <cstddef>
@@ -27,18 +28,17 @@ struct WatchBatch {
bool rescan_required{false};
};
// Linux inotify recursive directory watcher (VL-003).
// Automatically excludes build/cache/VCS trees to prevent feedback loops, attaches watches
// to newly created subdirectories, and reports IN_Q_OVERFLOW as rescan_required.
// Linux inotify recursive directory watcher delegating directly to
// Void::FileSystem::DirectoryWatcher (VL-003).
class InotifyWatcher {
public:
InotifyWatcher() = default;
~InotifyWatcher() noexcept;
~InotifyWatcher() noexcept = default;
InotifyWatcher(const InotifyWatcher &) = delete;
InotifyWatcher &operator=(const InotifyWatcher &) = delete;
InotifyWatcher(InotifyWatcher &&other) noexcept;
InotifyWatcher &operator=(InotifyWatcher &&other) noexcept;
InotifyWatcher(InotifyWatcher &&other) noexcept = default;
InotifyWatcher &operator=(InotifyWatcher &&other) noexcept = default;
[[nodiscard]] static Void::Result::Result<InotifyWatcher, Void::Result::Error>
create(const std::filesystem::path &root_dir,
@@ -54,19 +54,14 @@ class InotifyWatcher {
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> rescan_watches();
[[nodiscard]] std::size_t watched_directory_count() const noexcept {
return wd_to_path_.size();
return watcher_ ? watcher_->watch_count() : 0;
}
private:
explicit InotifyWatcher(int fd, std::filesystem::path root, std::vector<std::string> excluded);
void close_fd() noexcept;
Void::Result::Result<void, Void::Result::Error> watch_tree(const std::filesystem::path &dir);
bool is_excluded(const std::filesystem::path &rel) const;
explicit InotifyWatcher(Void::FileSystem::DirectoryWatcher watcher) noexcept
: watcher_{std::move(watcher)} {}
int fd_{-1};
std::filesystem::path root_;
std::vector<std::string> excluded_;
std::map<int, std::filesystem::path> wd_to_path_;
std::optional<Void::FileSystem::DirectoryWatcher> watcher_;
};
enum class WatchMode { FullBuild, MetadataOnly };
+7 -3
View File
@@ -38,8 +38,8 @@ add_vbs_selfhost_native(Project &project, const VbsSelfHostConfig &config) {
}
// 2. Declare the native VoidLibrary module closure (pure C++26, zero CMake).
std::vector<std::string> void_mods = {"Configuration", "Text", "Unicode", "Async",
"Algorithms"};
std::vector<std::string> void_mods = {"Configuration", "Text", "Unicode", "Async",
"Algorithms", "Crypto", "Archive"};
if (config.include_tests) {
void_mods.push_back("Testing");
}
@@ -63,12 +63,16 @@ add_vbs_selfhost_native(Project &project, const VbsSelfHostConfig &config) {
.include_directory((root / "include").string(), Visibility::Public)
.include_directory((root / "recipes").string(), Visibility::Public)
.compile_option("-freflection", Visibility::Public)
.define("VBS_HAS_VOID_CRYPTO=1", Visibility::Public)
.define("VBS_HAS_VOID_ARCHIVE=1", Visibility::Public)
.link(sdk, Visibility::Public)
.link(void_libs.modules.at("Configuration"), Visibility::Public)
.link(void_libs.modules.at("Text"), Visibility::Public)
.link(void_libs.modules.at("Unicode"), Visibility::Public)
.link(void_libs.modules.at("Async"), Visibility::Public)
.link(void_libs.modules.at("Algorithms"), Visibility::Public);
.link(void_libs.modules.at("Algorithms"), Visibility::Public)
.link(void_libs.modules.at("Crypto"), Visibility::Public)
.link(void_libs.modules.at("Archive"), Visibility::Public);
const std::vector<std::string> core_sources = {
"src/Util/Sha256.cpp",
@@ -28,6 +28,8 @@ const std::map<std::string, ModuleDef, std::less<>> &known_modules() {
{"Data", {{"Core", "Math", "Time"}, false}},
{"System", {{"Functional", "Time", "LogState"}, true}},
{"Async", {{"Functional", "Time", "LogState"}, true}},
{"Crypto", {{"Functional"}, false}},
{"Archive", {{"Functional", "Time", "System"}, false}},
{"Configuration", {{"Core", "Functional", "System", "Data", "Time", "LogState"}, true}},
{"Testing", {{"Core", "Functional", "Time", "LogState", "Configuration", "Text"}, true}},
};
@@ -100,6 +102,12 @@ VoidLibraryTargets add_void_library_native(Project &project,
if (def.needs_threads) {
tgt.link_option("-pthread", Visibility::Public);
}
if (mod == "Crypto") {
tgt.define("VOID_CRYPTO_HAS_OPENSSL=0", Visibility::Public);
}
if (mod == "Archive") {
tgt.define("VOID_ARCHIVE_HAS_LIBARCHIVE=0", Visibility::Public);
}
if (mod == "Testing") {
tgt.define("VOID_HAS_CONFIGURATION", Visibility::Public)
.define("VOID_HAS_TEXT", Visibility::Public);
+5 -12
View File
@@ -8,7 +8,6 @@
#include <cstdint>
#include <iostream>
#include <string>
#include <string_view>
int main(int argc, char **argv) {
std::string data_dir;
@@ -34,19 +33,13 @@ int main(int argc, char **argv) {
"environment variable holding bootstrap admin password", pass_env,
"VBS_REGISTRY_ADMIN_PASSWORD");
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;
}
for (int i = 1; i < argc; ++i) {
if (std::string_view{argv[i]} == "--help" || std::string_view{argv[i]} == "-h") {
std::cerr << "vbs-registry: --help must be used alone\n";
return 2;
}
}
if (auto parsed = parser.parse(argc, argv); !parsed) {
std::cerr << "vbs-registry: " << parsed.error() << '\n';
if (parsed.is_error()) {
std::cerr << "vbs-registry: " << parsed.message << '\n';
return 2;
}
+7 -12
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
File diff suppressed because it is too large. Load diff
+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;
}
+27
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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;
+18 -14
View File
@@ -14,27 +14,31 @@ function(check_process expected_code expected_out_regex expected_err_regex)
endif()
endfunction()
check_process(0 "Usage: vbs <command>" "" )
check_process(0 "Usage: vbs <command>" "" --help)
check_process(0 "Usage: vbs <command>" "" -h)
check_process(0 "Usage: vbs .*<command>.*Commands:" "" )
check_process(0 "Usage: vbs .*<command>.*Commands:" "" --help)
check_process(0 "Usage: vbs .*<command>.*Commands:" "" -h)
check_process(0 "^vbs ${VBS_VERSION}\n$" "" --version)
check_process(0 "^vbs ${VBS_VERSION}\n$" "" -V)
check_process(2 "" "--help must be used alone" --help --invalid)
check_process(2 "" "unexpected argument after --version" --version --invalid)
check_process(2 "" "unknown command 'invalid'" invalid)
check_process(0 "Usage: vbs build" "" build --help)
check_process(0 "Usage: vbs test" "" test --help)
check_process(2 "" "unknown option: --invalid" --version --invalid)
check_process(2 "" "--version cannot be combined with subcommands" --version build)
check_process(2 "" "unknown subcommand: invalid" invalid)
check_process(0 "Usage: vbs build .*--profile.*\\(repeatable\\)" "" build --help)
check_process(0 "Usage: vbs test " "" test --help)
check_process(2 "" "multi-profile build requires --editor-profile" build --profile debug --profile release)
check_process(2 "" "must be one of the requested profiles" build --profile debug --profile release --editor-profile custom)
check_process(2 "" "expected subcommand" compdb)
check_process(2 "" "unknown subcommand" compdb bogus)
check_process(2 "" "expected 'resolve' or 'update'" deps)
check_process(0 "Usage: vbs compdb <command>.*Commands:.*use.*show.*export.*watch" "" compdb --help)
check_process(0 "Usage: vbs compdb use " "" compdb use --help)
check_process(2 "" "missing subcommand for 'vbs compdb'" compdb)
check_process(2 "" "unknown subcommand: bogus" compdb bogus)
check_process(0 "Usage: vbs deps <command>.*Commands:.*resolve.*update" "" deps --help)
check_process(0 "Usage: vbs deps resolve " "" deps resolve --help)
check_process(2 "" "missing subcommand for 'vbs deps'" deps)
check_process(2 "" "--request and --output are required" bridge)
check_process(0 "Usage: vbs install" "" install --help)
check_process(0 "Usage: vbs install " "" install --help)
check_process(2 "" "--prefix is required" install)
check_process(2 "" "--prefix is required" uninstall)
check_process(2 "" "--input and --output-dir are required" gen-tests)
check_process(0 "Usage: vbs publish" "" publish --help)
check_process(0 "Usage: vbs publish " "" publish --help)
check_process(2 "" "--registry, --name, and --version are required" publish)
execute_process(COMMAND "${VBS_REGISTRY}" --help
@@ -42,4 +46,4 @@ execute_process(COMMAND "${VBS_REGISTRY}" --help
if(NOT "${reg_code}" STREQUAL "0" OR NOT reg_out MATCHES "Usage: vbs-registry")
message(FATAL_ERROR "vbs-registry --help failed: code=${reg_code}\nstdout=[${reg_out}]\nstderr=[${reg_err}]")
endif()
message(STATUS "23 native CLI contracts verified")
message(STATUS "27 native CLI and auto-generated Argparse help contracts verified")
+23 -7
View File
@@ -35,13 +35,23 @@ foreach(profile IN ITEMS debug release)
expect_json(file targets 0 sources 0 kind)
expect_json(src/Build.cpp targets 0 sources 0 path)
expect_json(public targets 0 include_directories 0 visibility)
expect_json(vbs targets 1 name)
expect_json(executable targets 1 kind)
expect_json(VoidBuildCore targets 1 name)
expect_json(static_library targets 1 kind)
expect_json(VoidBuildSdk targets 1 links 0 target)
expect_json(private targets 1 links 0 visibility)
expect_json(public targets 1 links 0 visibility)
expect_json(VoidLibrary targets 1 links 1 dependency)
expect_json(Void::Configuration targets 1 links 1 target)
foreach(index IN ITEMS 0 1)
expect_json(GenerateBootstrapConfig targets 2 name)
expect_json(custom_action targets 2 kind)
expect_json(vbs targets 3 name)
expect_json(executable targets 3 kind)
expect_json(VoidBuildCore targets 3 links 0 target)
expect_json(private targets 3 links 0 visibility)
expect_json(VoidBuildRegistry targets 4 name)
expect_json(static_library targets 4 kind)
expect_json(vbs-registry targets 5 name)
expect_json(executable targets 5 kind)
foreach(index IN ITEMS 0 1 3 4 5)
if(compiler STREQUAL "gcc")
expect_json(-Wduplicated-cond targets "${index}" compile_options 2)
else()
@@ -49,7 +59,7 @@ foreach(profile IN ITEMS debug release)
endif()
endforeach()
expect_json(git dependencies 0 source kind)
expect_json(9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5 dependencies 0 source revision)
expect_json(3e254055e081a104f08df68dde39711bc7813518 dependencies 0 source revision)
expect_json(cmake dependencies 0 builder)
string(JSON option_type TYPE "${graph}" dependencies 0 options BUILD_SHARED_LIBS)
if(NOT option_type STREQUAL "BOOLEAN")
@@ -58,6 +68,13 @@ foreach(profile IN ITEMS debug release)
endforeach()
endforeach()
execute_process(COMMAND "${DESCRIBE}" --help
RESULT_VARIABLE help_code OUTPUT_VARIABLE help_out ERROR_VARIABLE help_err TIMEOUT 10)
if(NOT "${help_code}" STREQUAL "0" OR NOT "${help_err}" STREQUAL "" OR
NOT help_out MATCHES "Usage: vbs_describe")
message(FATAL_ERROR "vbs_describe --help failed: code=${help_code}\nstdout=[${help_out}]\nstderr=[${help_err}]")
endif()
function(expect_error expected)
execute_process(COMMAND "${DESCRIBE}" ${ARGN}
RESULT_VARIABLE code OUTPUT_VARIABLE out ERROR_VARIABLE err TIMEOUT 10)
@@ -71,5 +88,4 @@ expect_error("unknown compiler 'msvc' (expected gcc or clang)" --compiler msvc)
expect_error("option '--profile' requires a value" --profile)
expect_error("unknown option: --invalid" --invalid)
expect_error("unexpected positional argument: invalid" invalid)
expect_error("--help must be used alone" --help --invalid)
message(STATUS "Four runtime profile/compiler contexts and six error contracts verified")
message(STATUS "Four runtime profile/compiler contexts, generated help, and five error contracts verified")
+13 -2
View File
@@ -13,7 +13,11 @@ Void::Testing::Test example_uses_runtime_compiler() {
definitions.resolve("debug", Void::Build::CompilerFamily::Clang, "linux", "x86_64")};
build(gcc);
build(clang);
Void::Testing::expect_eq(gcc.targets().size(), clang.targets().size());
for (std::size_t index = 0; index < gcc.targets().size(); ++index) {
if (gcc.targets().at(index).kind == Void::Build::TargetKind::CustomAction) {
continue;
}
Void::Testing::expect(std::ranges::contains(gcc.targets().at(index).compile_options,
std::string{"-Wduplicated-cond"}));
Void::Testing::expect(!std::ranges::contains(gcc.targets().at(index).compile_options,
@@ -47,15 +51,22 @@ Void::Testing::Test example_records_sources_links_and_pin() {
Void::Build::Project project{Void::Build::default_profiles().resolve(
"debug", Void::Build::CompilerFamily::Gcc, "linux", "x86_64")};
build(project);
Void::Testing::expect_eq(project.targets().size(), std::size_t{2});
Void::Testing::expect_eq(project.targets().size(), std::size_t{6});
Void::Testing::expect_eq(project.targets().at(0).name, std::string{"VoidBuildSdk"});
Void::Testing::expect_eq(project.targets().at(0).sources.at(0).path,
std::string{"src/Build.cpp"});
Void::Testing::expect_eq(project.targets().at(1).name, std::string{"VoidBuildCore"});
Void::Testing::expect_eq(project.targets().at(1).links.at(0).target,
std::string{"VoidBuildSdk"});
Void::Testing::expect_eq(project.targets().at(1).links.at(1).target,
std::string{"Void::Configuration"});
Void::Testing::expect_eq(project.targets().at(2).name, std::string{"GenerateBootstrapConfig"});
Void::Testing::expect_eq(project.targets().at(3).name, std::string{"vbs"});
Void::Testing::expect_eq(project.targets().at(3).links.at(0).target,
std::string{"VoidBuildCore"});
Void::Testing::expect_eq(project.targets().at(4).name, std::string{"VoidBuildRegistry"});
Void::Testing::expect_eq(project.targets().at(5).name, std::string{"vbs-registry"});
Void::Testing::expect_eq(project.dependencies().at(0).revision,
std::string{"9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5"});
std::string{"3e254055e081a104f08df68dde39711bc7813518"});
Void::Testing::expect_eq(project.dependencies().at(0).builder, std::string{"cmake"});
}